RC2解密问题(数据丢失) [英] RC2 Decryption problem (lost of data)
本文介绍了RC2解密问题(数据丢失)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
private void button1_Click_1(object sender, EventArgs e)
{
string enc = rc("some string", "some key", true);
MessageBox.Show(enc);
string dec = rc(enc, "some key", false);
MessageBox.Show(dec);
}
private string rc(string text, string key, bool enc)
{
string plainText = text;
byte[] buffer = ASCIIEncoding.ASCII.GetBytes(plainText);
RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider();
rc2.Key = ASCIIEncoding.ASCII.GetBytes(key);
rc2.GenerateIV();
if (enc)
{
string encryptedString = Convert.ToBase64String(
rc2.CreateEncryptor().TransformFinalBlock(
buffer, 0, buffer.Length));
return encryptedString;
}
else
{
buffer = Convert.FromBase64String(text);
byte[] b_dec = rc2.CreateDecryptor().TransformFinalBlock(buffer, 0, buffer.Length);
string decryptedString = ASCIIEncoding.ASCII.GetString(b_dec);
return decryptedString;
}
}
为什么:
-每次加密的字符串都不相同
-解密的字符串是错误的("ing"之前的所有字符都不可读)
?
请帮助.
Why:
- encrypted string is different each time
- decrypted string is wrong(all characters before ''ing'' are unreadable)
?
Please, help.
推荐答案
rc2.GenerateIV()
需要替换为以下固定内容:
rc2.IV = new byte[] { 23, 10, 99, 73, 44, 69, 35, 80 };
rc2.GenerateIV()
was needed to replace with something fixed as this:
rc2.IV = new byte[] { 23, 10, 99, 73, 44, 69, 35, 80 };
我对RC2不太了解,但是您确定它不应该每次都生成一个新的加密字符串吗?可能不是,但是我以前听说过.
I don''t know much about RC2, but are you sure that it is not supposed to make a new encrypted string everytime? Probably not, but I''ve heard of it before.
问题是下面的行
The problem is that the following line
halabella写道:
halabella wrote:
rc2.GenerateIV();
rc2.GenerateIV();
每次调用都会生成一个 new 随机向量.
快速修复:
添加以下类成员变量:
every time is called generates a new random vector.
Quick fix:
Add the following class member variable:
byte [] iv =null;
然后以这种方式修改功能:
then modify the function this way:
private string rc(string text, string key, bool enc)
{
string plainText = text;
byte[] buffer = ASCIIEncoding.ASCII.GetBytes(plainText);
RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider();
rc2.Key = ASCIIEncoding.ASCII.GetBytes(key);
if (iv == null)
{
rc2.GenerateIV();
iv = rc2.IV;
}
else
{
rc2.IV = iv;
}
if (enc)
{
string encryptedString = Convert.ToBase64String(
rc2.CreateEncryptor().TransformFinalBlock(
buffer, 0, buffer.Length));
return encryptedString;
}
else
{
buffer = Convert.FromBase64String(text);
byte[] b_dec = rc2.CreateDecryptor().TransformFinalBlock(buffer, 0, buffer.Length);
string decryptedString = ASCIIEncoding.ASCII.GetString(b_dec);
return decryptedString;
}
}
当然,根据您的需求,您可能会发现更优雅的灵魂
Of course you may find a more elegant soultion depending on your needs
这篇关于RC2解密问题(数据丢失)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文