/// <summary>
/// DES解密字符串
/// </summary>
/// <param name="decryptString">待解密的字符串</param>
/// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
/// <returns>解密成功返回解密后的字符串,失败返源串</returns>
public static string Decrypt(string cryptedString, string decryptKey)
{
byte[] bytes = ASCIIEncoding.ASCII.GetBytes(decryptKey);
string s1 = string.Empty;
if (String.IsNullOrEmpty(cryptedString))
{
throw new ArgumentNullException("The string which needs to be decrypted can not be null.");
} DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
cryptoProvider.Mode = CipherMode.ECB;
cryptoProvider.Padding = PaddingMode.Zeros; // 通过Base64解密出16进制
s1 = Encoding.Default.GetString(Convert.FromBase64String(cryptedString)); // 16进制数据在转成字符串
//cryptedString = DivideString(s1,2); // 16进制数据转BYTE
Byte[] bBuffer = Hex2ByteArr(s1); // 开始解密
MemoryStream memoryStream = new MemoryStream(bBuffer);
CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateDecryptor(bytes, bytes), CryptoStreamMode.Read);
StreamReader reader = new StreamReader(cryptoStream); return reader.ReadToEnd();
}以上代码解密的时候容易出错。
执行到以下代码的时候就报错。
// 通过Base64解密出16进制
s1 = Encoding.Default.GetString(Convert.FromBase64String(cryptedString));
报错错误是:Base-64 字符串中的无效字符。请高手指教。多谢!
/// <summary>
/// 进行DES加密。
/// </summary>
/// <param name="pToEncrypt">要加密的字符串。</param>
/// <param name="sKey">密钥,且必须为8位。</param>
/// <returns>以Base64格式返回的加密字符串。</returns>
public string Encrypt(string pToEncrypt, string sKey)
{
using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
{
byte[] inputByteArray = Encoding.UTF8.GetBytes(pToEncrypt);
des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
cs.Close();
}
string str = Convert.ToBase64String(ms.ToArray());
ms.Close();
return str;
}
} /// <summary>
/// 进行DES解密。
/// </summary>
/// <param name="pToDecrypt">要解密的以Base64</param>
/// <param name="sKey">密钥,且必须为8位。</param>
/// <returns>已解密的字符串。</returns>
public string Decrypt(string pToDecrypt, string sKey)
{
byte[] inputByteArray = Convert.FromBase64String(pToDecrypt);
using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
{
des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
cs.Close();
}
string str = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
return str;
}
}
http://zhoufoxcn.blog.51cto.com/792419/167095