gpt4 book ai didi

c# - Visual C# 独立解密错误 : length of data to decrypt is invalid

转载 作者:行者123 更新时间:2023-12-03 08:56:22 25 4
gpt4 key购买 nike

在我的可视 C# 加密/解密程序中,我试图独立加密和解密
当我尝试解密先前加密的数据时,我得到一段要解密的数据是无效错误

String filename;
String filename2;

private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK) {
filename = ofd.FileName;
textBox1.Text = filename;
button2.Enabled = true;
}
}

private void button2_Click(object sender, EventArgs e)
{
StreamReader sr = new StreamReader(filename);
String toencrypt = sr.ReadToEnd();
sr.Dispose();

MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
UTF8Encoding utf8 = new UTF8Encoding();
TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();
tripleDES.Key = md5.ComputeHash(utf8.GetBytes(toencrypt));
tripleDES.Mode = CipherMode.ECB;
tripleDES.Padding = PaddingMode.PKCS7;
ICryptoTransform trans = tripleDES.CreateEncryptor();
String encrypted = BitConverter.ToString(trans.TransformFinalBlock(utf8.GetBytes(textBox2.Text), 0, utf8.GetBytes(textBox2.Text).Length));

StreamWriter sw = new StreamWriter(filename);
sw.Write(encrypted);
sw.Dispose();
}

private void button3_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
filename2 = ofd.FileName;
textBox3.Text = filename2;
button4.Enabled = true;
}
}

private void button4_Click(object sender, EventArgs e)
{
StreamReader sr = new StreamReader(filename2);
String todecrypt = sr.ReadToEnd();
sr.Dispose();

MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
UTF8Encoding utf8 = new UTF8Encoding();
TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();
tripleDES.Key = md5.ComputeHash(utf8.GetBytes(textBox4.Text));
tripleDES.Mode = CipherMode.ECB;
tripleDES.Padding = PaddingMode.PKCS7;
ICryptoTransform trans = tripleDES.CreateDecryptor();
String decrypted = BitConverter.ToString(trans.TransformFinalBlock(utf8.GetBytes(todecrypt), 0, utf8.GetBytes(todecrypt).Length));

StreamWriter sw = new StreamWriter(filename2);
sw.Write(decrypted);
sw.Dispose();
}

基本上我在这里要做的是打开一个 txt 文件,获取里面的数据以加密(工作正常)然后解密(如果我收到错误)当它给我错误时我不知道要更改什么解决这个问题,因为数据的长度使用相同的键和填充以及其他所有适用的...

最佳答案

首先:

String encrypted = BitConverter.ToString(trans.TransformFinalBlock(utf8.GetBytes(textBox2.Text), 0, utf8.GetBytes(textBox2.Text).Length));

字符串“加密”的格式为
0C-4C-9B-01-00-0D-81-EC-D6-C5-2C-9A-EC-CE-08-95

但是您尝试解密格式化字符串的 Utf8 字节。那失败了;大部分时间是由于长度不正确。您想使用 BitConverter 将字符串转换为字节数组 - 而不是使用 Utf8。

除此之外:
1)不要使用欧洲央行
2) 使用静脉输液
3)使用文件的哈希值作为键是有问题的

编辑:格式化

关于c# - Visual C# 独立解密错误 : length of data to decrypt is invalid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24070839/

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