gpt4 book ai didi

c# - 在 MySQL 中加密,在 C# 中解密

转载 作者:可可西里 更新时间:2023-11-01 07:32:07 26 4
gpt4 key购买 nike

我在 MySQL 中加密了我的数据,我将它存储为 BLOB,然后我需要在 C# 中解密它,但我没有得到预期的结果。

MYSQL 中的 BLOB:

BLOB in MySQL

这是我的结果:

Result

应该只是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 默认) block 大小为 16 字节因此输入数据需要填充到 block 大小的倍数,即最后两个 0x02 字节PKCS#7 padding .因此,最后两个字节:“PD001KY6900430\u0002\u0002”(其中\u0002 表示 UTF-16 中 0x02 的单个字节)是填充。

这通常通过为解密方法指定 PKCS#7 填充来处理(删除)。

The Fix:

改变
Crypto.Padding = PaddingMode.None;

Crypto.Padding = PaddingMode.PKCS7;

最好完全指定所有选项。

关于c# - 在 MySQL 中加密,在 C# 中解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45808318/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com