C# 对称加解密
///
/// DES加密调用
///
/// 需要加密的字符串
///
public static string DESEncrypt(string inputStr)
{
return Encrypt(inputStr,”Futpower”);
}
///
/// DES解密调用
///
/// 需要解密的字符串
///
public static string DESDecrypt(string inputStr)
{
return Decrypt(inputStr, “Futpower”);
}
///
/// 进行DES加密。
///
/// 要加密的字符串。
/// 密钥,且必须为8位。
///
public static 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);
MemoryStream ms = new 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;
}
}
///
/// 进行DES解密。
///
/// 要解密的以Base64
/// 密钥,且必须为8位。
///
public static 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);
MemoryStream ms = new 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;
}
}
还没有评论,来说两句吧...