[英]Encrypting in MySQL, Decrypting in C#
我在MySQL中加密了我的數據,我將其存儲為BLOB,然后我需要在C#中解密它,但我沒有得到預期的結果。
MYSQL中的BLOB:
這是我的結果:
它應該只是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字節,因此輸入數據需要填充為塊大小倍數,即PKCS#7填充的最后兩個0x02
字節。 因此,最后兩個字節:“PD001KY6900430 \\ u0002 \\ u0002”(其中\\ u0002表示UTF-16中的0x02
的單個字節)是填充。
通常通過為解密方法指定PKCS#7填充來處理(移除)。
修復:
更改
Crypto.Padding = PaddingMode.None;
至
Crypto.Padding = PaddingMode.PKCS7;
最好完全指定所有選項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.