DES加密解密报错【不正确的数据】急急急求大神帮助
碎碎0_o 2017-09-19 05:32:24 加密解密,有些能加密解密出来,有些报错说【不正确的数据。】,还有些加密解密出来是错的
例:textBox1中文本为【BLue@210896】时,就是不正确的数据,文本改成【BLue@210896 】(后面随便加空格什么的),就正常了。
private void button1_Click(object sender, EventArgs e)
{
this.textBox2.Text = EncryptorStr1(this.textBox1.Text, enckey, encIV);
this.textBox3.Text = DecryptorStr1(this.textBox2.Text, enckey, encIV);
}
Byte[] enckey = { 0x01, 0x11, 0x11, 0x11, 0x01, 0x01, 0x01, 0x01 };
Byte[] encIV = { 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 };
#region 加密
//加密后返回十六进制字符串
private string EncryptorStr1(string encyptstr, byte[] key, byte[] IV)
{
byte[] enbyte = Encoding.Unicode.GetBytes(encyptstr);//ConvertStringToByteArray(encyptstr);
MemoryStream fs = new MemoryStream(enbyte, 0, enbyte.Length);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
ICryptoTransform desencrypt = des.CreateEncryptor(key, IV);
CryptoStream cryptostream = new CryptoStream(fs, desencrypt, CryptoStreamMode.Read);
string str = (new StreamReader(cryptostream, new UnicodeEncoding())).ReadToEnd();
fs.Close();
cryptostream.Close();
//转换为十六进制
byte[] aa = Encoding.Unicode.GetBytes(str);
str = "";
for (int i = 0; i < aa.Length; i++)
{
if (aa[i].ToString("X").Length == 1)
str += "0";
str += aa[i].ToString("X");
}
return str;
}
#endregion
#region 解密
public string DecryptorStr1(string decryptstr, byte[] key, byte[] IV)
{
try
{
//先将十六进制转换为DES加密的字符串的原形
string str;
int len = decryptstr.Length / 2;
byte[] aa = new Byte[len];
int j; int k = 0;
for (int i = 0; i < decryptstr.Length; i++)
{
j = Uri.FromHex(Uri.HexUnescape(decryptstr, ref k));
i++;
j = j * 16 + Uri.FromHex(Uri.HexUnescape(decryptstr, ref k));
aa[i / 2] = Convert.ToByte(j);
}
decryptstr = Encoding.Unicode.GetString(aa, 0, aa.Length);
byte[] enbyte = ConvertStringToByteArray(decryptstr);
MemoryStream fsread = new MemoryStream(enbyte, 0, enbyte.Length);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
ICryptoTransform desdecrypt = des.CreateDecryptor(key, IV);
CryptoStream cryptostreamDecr = new CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read);
str = (new StreamReader(cryptostreamDecr, new UnicodeEncoding())).ReadToEnd();
fsread.Close();
cryptostreamDecr.Close();
return str;
}
catch (Exception ex)
{
return ex.Message;
}
}
#endregion