C# DES加密解密类分享
2012-03-16 20:44 Andrew.Wangxu 阅读(332) 评论(0) 编辑 收藏 举报直接上代码了。
public class DESEncrypt { //密钥 private static string key = "mykey"; /// <summary> /// DES加密 /// </summary> /// <param name="encryptString">需要加密的字符串</param> /// <returns>返回已加密的字符串</returns> public static string DesEncrypt(string encryptString) { if (string.IsNullOrEmpty(encryptString)) { return string.Empty; } byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 8)); byte[] keyIV = keyBytes; byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString); DESCryptoServiceProvider provider = new DESCryptoServiceProvider(); MemoryStream mStream = new MemoryStream(); CryptoStream cStream = new CryptoStream(mStream, provider.CreateEncryptor(keyBytes, keyIV), CryptoStreamMode.Write); cStream.Write(inputByteArray, 0, inputByteArray.Length); cStream.FlushFinalBlock(); return Convert.ToBase64String(mStream.ToArray()); } /// <summary> /// DES解密 /// </summary> /// <param name="decryptString">需要解密的字符串</param> /// <returns>已解密的字符串</returns> public static string DesDecrypt(string decryptString) { if (string.IsNullOrEmpty(decryptString)) { return string.Empty ; } byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 8)); byte[] keyIV = keyBytes; byte[] inputByteArray = Convert.FromBase64String(decryptString); DESCryptoServiceProvider provider = new DESCryptoServiceProvider(); MemoryStream mStream = new MemoryStream(); CryptoStream cStream = new CryptoStream(mStream, provider.CreateDecryptor(keyBytes, keyIV), CryptoStreamMode.Write); cStream.Write(inputByteArray, 0, inputByteArray.Length); cStream.FlushFinalBlock(); return Encoding.UTF8.GetString(mStream.ToArray()); } }
注:
//密钥
private static string key = "mykey";
mykey 是设定的密钥,自行设置一个就可以了。