4 / 4 / 4
Регистрация: 24.06.2014
Сообщений: 100
1

Шифрование AES 256

08.01.2015, 10:35. Показов 7873. Ответов 4
Метки нет (Все метки)

Доброго времени суток, помогите реализовать шифрование

сам код шифрование

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public static string Encrypt(string plainText, string password,
        string salt = "Kosher", string hashAlgorithm = "SHA1",
        int passwordIterations = 2, string initialVector = "OFRna73m*aze01xY",
        int keySize = 256)
        {
            if (string.IsNullOrEmpty(plainText))
                return "";
 
            byte[] initialVectorBytes = Encoding.ASCII.GetBytes(initialVector);
            byte[] saltValueBytes = Encoding.ASCII.GetBytes(salt);
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
 
            PasswordDeriveBytes derivedPassword = new PasswordDeriveBytes
             (password, saltValueBytes, hashAlgorithm, passwordIterations);
 
            byte[] keyBytes = derivedPassword.GetBytes(keySize / 8);
            RijndaelManaged symmetricKey = new RijndaelManaged();
            symmetricKey.Mode = CipherMode.CBC;
 
            byte[] cipherTextBytes = null;
 
            using (ICryptoTransform encryptor = symmetricKey.CreateEncryptor
            (keyBytes, initialVectorBytes))
            {
                using (MemoryStream memStream = new MemoryStream())
                {
                    using (CryptoStream cryptoStream = new CryptoStream
                             (memStream, encryptor, CryptoStreamMode.Write))
                    {
                        cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                        cryptoStream.FlushFinalBlock();
                        cipherTextBytes = memStream.ToArray();
                        memStream.Close();
                        cryptoStream.Close();
                    }
                }
            }
 
            symmetricKey.Clear();
            return Convert.ToBase64String(cipherTextBytes);
        }
Код расшифровки

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public static string Decrypt(string cipherText, string password,
   string salt = "Kosher", string hashAlgorithm = "SHA1",
   int passwordIterations = 2, string initialVector = "OFRna73m*aze01xY",
   nt keySize = 256)
   {
    if (string.IsNullOrEmpty(cipherText))
       return "";
 
    byte[] initialVectorBytes = Encoding.ASCII.GetBytes(initialVector);
    byte[] saltValueBytes = Encoding.ASCII.GetBytes(salt);
    byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
 
    PasswordDeriveBytes derivedPassword = new PasswordDeriveBytes
    (password, saltValueBytes, hashAlgorithm, passwordIterations);
            byte[] keyBytes = derivedPassword.GetBytes(keySize / 8);
 
            RijndaelManaged symmetricKey = new RijndaelManaged();
            symmetricKey.Mode = CipherMode.CBC;
 
            byte[] plainTextBytes = new byte[cipherTextBytes.Length];
            int byteCount = 0;
 
            using (ICryptoTransform decryptor = symmetricKey.CreateDecryptor
                     (keyBytes, initialVectorBytes))
            {
                using (MemoryStream memStream = new MemoryStream(cipherTextBytes))
                {
                    using (CryptoStream cryptoStream
                    = new CryptoStream(memStream, decryptor, CryptoStreamMode.Read))
                    {
                        byteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                        memStream.Close();
                        cryptoStream.Close();
                    }
                }
            }
 
            symmetricKey.Clear();
            return Encoding.UTF8.GetString(plainTextBytes, 0, byteCount);
        }
Код использования функции шифрования

C#
1
2
using System.Security.Cryptography;
string FinalValue=AESEncryption.Encrypt("Text", "Password1", "Password2", "SHA1", 2, "16CHARSLONG12345", 256);
Но вот тут то и пишет ошибку мол Ошибка 1 Элемент "AESEncryption" не существует в текущем контексте.
Подскажите, как исправить?
Спасибо!
0
Лучшие ответы (1)
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
08.01.2015, 10:35
Ответы с готовыми решениями:

Шифрование строки AES (готовое решение)
искал на форуме простое шифрование строки с AES но не смог найти что искал может плохо искал в...

Шифрование AES-256 GCM
Как на C# можно сделать шифрование AES-256 GCM, без библиотек, хоть что можете предложить WinAPI и...

AES 256 CBC Decode
Добрый день. Подскажите пожалуйста, каким образом можно дешифровать запрос, зная, что тип...

Нужен полный код алгоритма шифрования AES 256
Собсна, сабж. Знаю, что оно делается в несколько строк, но именно это мне и не надо. Надо БЕЗ...

4
34 / 39 / 18
Регистрация: 04.05.2013
Сообщений: 212
08.01.2015, 10:53 2
Вова Ковальчук, покажите, как у вас объявлен класс AESEncryption.
1
4 / 4 / 4
Регистрация: 24.06.2014
Сообщений: 100
08.01.2015, 10:55  [ТС] 3
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.IO;
 
namespace Password_Keeper
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        
        public static string Encrypt(string plainText, string password,
        string salt = "Kosher", string hashAlgorithm = "SHA1",
        int passwordIterations = 2, string initialVector = "OFRna73m*aze01xY",
        int keySize = 256)
        {
            if (string.IsNullOrEmpty(plainText))
                return "";
 
            byte[] initialVectorBytes = Encoding.ASCII.GetBytes(initialVector);
            byte[] saltValueBytes = Encoding.ASCII.GetBytes(salt);
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
 
            PasswordDeriveBytes derivedPassword = new PasswordDeriveBytes
             (password, saltValueBytes, hashAlgorithm, passwordIterations);
 
            byte[] keyBytes = derivedPassword.GetBytes(keySize / 8);
            RijndaelManaged symmetricKey = new RijndaelManaged();
            symmetricKey.Mode = CipherMode.CBC;
 
            byte[] cipherTextBytes = null;
 
            using (ICryptoTransform encryptor = symmetricKey.CreateEncryptor
            (keyBytes, initialVectorBytes))
            {
                using (MemoryStream memStream = new MemoryStream())
                {
                    using (CryptoStream cryptoStream = new CryptoStream
                             (memStream, encryptor, CryptoStreamMode.Write))
                    {
                        cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                        cryptoStream.FlushFinalBlock();
                        cipherTextBytes = memStream.ToArray();
                        memStream.Close();
                        cryptoStream.Close();
                    }
                }
            }
 
            symmetricKey.Clear();
            return Convert.ToBase64String(cipherTextBytes);
        }
        
        public static string Decrypt(string cipherText, string password,
   string salt = "Kosher", string hashAlgorithm = "SHA1",
   int passwordIterations = 2, string initialVector = "OFRna73m*aze01xY",
   int keySize = 256)
   {
    if (string.IsNullOrEmpty(cipherText))
       return "";
 
    byte[] initialVectorBytes = Encoding.ASCII.GetBytes(initialVector);
    byte[] saltValueBytes = Encoding.ASCII.GetBytes(salt);
    byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
 
    PasswordDeriveBytes derivedPassword = new PasswordDeriveBytes
    (password, saltValueBytes, hashAlgorithm, passwordIterations);
            byte[] keyBytes = derivedPassword.GetBytes(keySize / 8);
 
            RijndaelManaged symmetricKey = new RijndaelManaged();
            symmetricKey.Mode = CipherMode.CBC;
 
            byte[] plainTextBytes = new byte[cipherTextBytes.Length];
            int byteCount = 0;
 
            using (ICryptoTransform decryptor = symmetricKey.CreateDecryptor
                     (keyBytes, initialVectorBytes))
            {
                using (MemoryStream memStream = new MemoryStream(cipherTextBytes))
                {
                    using (CryptoStream cryptoStream
                    = new CryptoStream(memStream, decryptor, CryptoStreamMode.Read))
                    {
                        byteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                        memStream.Close();
                        cryptoStream.Close();
                    }
                }
            }
 
            symmetricKey.Clear();
            return Encoding.UTF8.GetString(plainTextBytes, 0, byteCount);
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
 
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            string FinalValue = AESEncryption.Encrypt("Text", "Password1", "Password2", "SHA1", 2, "16CHARSLONG12345", 256);
            
        }
    }
}
0
34 / 39 / 18
Регистрация: 04.05.2013
Сообщений: 212
08.01.2015, 10:58 4
Лучший ответ Сообщение было отмечено Вова Ковальчук как решение

Решение

Вова Ковальчук, пишите просто
C#
1
string FinalValue = Encrypt("Text", "Password1", "Password2", "SHA1", 2, "16CHARSLONG12345", 256);
1
4 / 4 / 4
Регистрация: 24.06.2014
Сообщений: 100
08.01.2015, 11:02  [ТС] 5
Спасибо!)
0
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
08.01.2015, 11:02
Помогаю со студенческими работами здесь

AES шифрование
Видел кучу тем на эту тему, но так для себя решения и не нашел, здесь реализация заточена на текст,...

Шифрование AES 128.
Привет. Нужно зашифровать string используя AES 128 битный. Что-то написал, но работать...

Шифрование нетекстовых данных AES
Приветствую вспех форумчан! Я не программист, но возникла необходимость реализовать шифрование...

AES шифрование. Заполнение неверно и не может быть удалено
На строке cs.Close(); возникает ошибка: Заполнение неверно и не может быть удалено. Что делать? ...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
5
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2023, CyberForum.ru