Я зашифровал свои данные в MySQL, я храню их как BLOB, затем мне нужно расшифровать их в C #, но я не получаю ожидаемого результата.
BLOB в MYSQL:
Это мой результат:
Это должно быть просто PD001KY6900430
Вот мой код в C #
string ConnectionString = "Data Source=win-3doecchgfbt;Initial Catalog=DWH;User id=sa;Password=Password123;";
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
string query = "SELECT * FROM tb_investor";
SqlDataAdapter adapter = new SqlDataAdapter();
var command = new SqlCommand(query, connection);
adapter.SelectCommand = command;
DataTable dTable = new DataTable();
adapter.Fill(dTable);
for(var x =0; x < dTable.Rows.Count; x++)
{
var dr = dTable.Rows;
byte[] accNoByte = (byte[])dr[x].ItemArray[1];
byte[] key = mkey("satu");
var rkey = BitConverter.ToString(key).Replace("-", "");
var decAccNo = decrypt_function(accNoByte, key);
}
}
Вот метод Mkey:
Encoding winLatinCodePage = Encoding.GetEncoding(1252);
byte[] key = Encoding.UTF8.GetBytes(skey);
byte[] k = new byte[16] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
for (int i = 0; i < key.Length; i++)
{
k[i % 16] = (byte)(k[i % 16] ^ key[i]);
}
return k;
Вот метод decrypt_function:
RijndaelManaged Crypto = null;
MemoryStream MemStream = null;
ICryptoTransform Decryptor = null;
CryptoStream Crypto_Stream = null;
StreamReader Stream_Read = null;
string Plain_Text;
try
{
Crypto = new RijndaelManaged();
Crypto.Key = Key;
Crypto.Mode = CipherMode.ECB;
Crypto.Padding = PaddingMode.None;
MemStream = new MemoryStream(Cipher_Text);
Crypto.GenerateIV();
//Create Decryptor make sure if you are decrypting that this is here and you did not copy paste encryptor.
Decryptor = Crypto.CreateDecryptor(Crypto.Key, Crypto.IV);
//This is different from the encryption look at the mode make sure you are reading from the stream.
Crypto_Stream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read);
//I used the stream reader here because the ReadToEnd method is easy and because it return a string, also easy.
Stream_Read = new StreamReader(Crypto_Stream);
Plain_Text = Stream_Read.ReadToEnd();
}
finally
{
if (Crypto != null)
Crypto.Clear();
MemStream.Flush();
MemStream.Close();
}
return Plain_Text;
Пожалуйста, покажи мне ошибку, которую я сделал.
«PD001KY6900430» составляет 14 байтов, размер блока AES (по умолчанию RijndaelManaged) составляет 16 байтов, поэтому входные данные должны быть дополнены до кратного размера блока, то есть двух последних 0x02
байты PKCS # 7 отступы. Таким образом, два последних байта: «PD001KY6900430 \ u0002 \ u0002» (где \ u0002 представляет один байт 0x02
в UTF-16) это отступы.
Это обычно обрабатывается (удаляется) путем указания заполнения PKCS # 7 для метода дешифрования.
Исправление:
+ Изменить
Crypto.Padding = PaddingMode.None;
в
Crypto.Padding = PaddingMode.PKCS7;
Всегда лучше полностью указать все параметры.
Других решений пока нет …