直接上代码了。
public class DESEncrypt { //密钥 private static string key = "mykey"; ////// DES加密 /// /// 需要加密的字符串 ///返回已加密的字符串 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()); } ////// DES解密 /// /// 需要解密的字符串 ///已解密的字符串 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 是设定的密钥,自行设置一个就可以了。
参考: