C#DESC解密问题
我在网上找了个实例,实际运行测试了下,可运行到byte[] result = desencrypt.TransformFinalBlock(data, 0, data.Length);时老是报CryptographicException异常,请哪位高手指点下哪里有错,还是参数错误。
public string DecryptString(string inputInfo, string sKey)
{
string[] sInput = inputInfo.Split("-".ToCharArray());
byte[] data = new byte[sInput.Length];
for (int i = 0; i < sInput.Length; i++)
{
data[i] = byte.Parse(sInput[i], NumberStyles.HexNumber);
}
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
ICryptoTransform desencrypt = DES.CreateDecryptor();
byte[] result = desencrypt.TransformFinalBlock(data, 0, data.Length);
return Encoding.UTF8.GetString(result);
}
[解决办法]
/// <summary>
/// DES对称加密方法
/// </summary>
/// <param name="InitData">原始待加密数据</param>
/// <param name="SecretKey">加密密钥,密钥长度必须为八位有效英文字符</param>
public static string EncryptData(object InitData, string SecretKey)
{
try
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
//把字符串放到byte数组中
Byte[] inputByteArray = Encoding.Default.GetBytes(InitData.ToString());
//建立加密对象的密钥和偏移量
des.Key = ASCIIEncoding.ASCII.GetBytes(SecretKey);
//原文使用ASCIIEncoding.ASCII方法的GetBytes方法
des.IV = ASCIIEncoding.ASCII.GetBytes(SecretKey);
//使得输入密码必须输入英文文本
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
StringBuilder ret = new StringBuilder();
foreach (Byte b in ms.ToArray())
{
ret.AppendFormat("{0:X2}", b);
}
ret.ToString();
return ret.ToString();
}
catch
{
return "";
}
}
/// <summary>
/// DES对称解密方法
/// </summary>
/// <param name="EncryptedData">待解密数据</param>
/// <param name="SecretKey">解密密钥,必须是加密时的密钥,密钥长度必须为八位有效英文字符,例如"12secret"</param>
public static string DecryptData(object EncryptedData, string SecretKey)
{
try
{
string pToDecrypt = EncryptedData.ToString();
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
Byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
for (int x = 0; x < pToDecrypt.Length / 2; x++)
{
int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
inputByteArray[x] = (byte)i;
}
//建立加密对象的密钥和偏移量,此值重要,不能修改
des.Key = ASCIIEncoding.ASCII.GetBytes(SecretKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(SecretKey);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
return System.Text.Encoding.Default.GetString(ms.ToArray());
}
catch
{
return "";
}
}