C#的DES加密,一個demo記錄一下。
DES加密管理類
/// <summary> /// DES加密管理類 /// </summary> public class DESEncryptHelper { private static string DES_Key = "****************"; /// <summary> /// DES加密 /// </summary> /// <param name="str">需要加密的</param> /// <returns></returns> public static string Encrypt(string str) { if (string.IsNullOrEmpty(str)) { return "加密處理失敗,加密字符串為空"; } //加密秘鑰補位處理 string encryptKeyall = Convert.ToString(DES_Key); //定義密鑰 if (encryptKeyall.Length < 9) { for (; ; ) { if (encryptKeyall.Length < 9) encryptKeyall += encryptKeyall; else break; } } string encryptKey = encryptKeyall.Substring(0, 8); DES_Key = encryptKey; DESCryptoServiceProvider des = new DESCryptoServiceProvider(); byte[] inputByteArray = Encoding.Default.GetBytes(str); des.Key = ASCIIEncoding.UTF8.GetBytes(DES_Key); // 密匙 des.IV = ASCIIEncoding.UTF8.GetBytes(DES_Key); // 向量 MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); var result = Convert.ToBase64String(ms.ToArray()); return result; } /// <summary> /// DES解密 /// </summary> /// <param name="str">需要解密的</param> /// <returns></returns> public static string Decrypt(string str) { if (string.IsNullOrEmpty(str)) { return "解密處理失敗,解密字符串為空"; } //解密秘鑰補位處理 string encryptKeyall = Convert.ToString(DES_Key); if (encryptKeyall.Length < 9) { for (; ; ) { if (encryptKeyall.Length < 9) encryptKeyall += encryptKeyall; else break; } } string encryptKey = encryptKeyall.Substring(0, 8); DES_Key = encryptKey; //解密處理 DESCryptoServiceProvider des = new DESCryptoServiceProvider(); byte[] inputByteArray = Convert.FromBase64String(str); des.Key = ASCIIEncoding.UTF8.GetBytes(DES_Key); //秘鑰---加密解密秘鑰需要一致 des.IV = ASCIIEncoding.UTF8.GetBytes(DES_Key); //向量 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()); } }
方法調用:
string resultStr = DESEncryptHelper.Encrypt(“123456”); string resultStr = DESEncryptHelper.Decrypt(“123456”);
學習:
DES算法原理:https://blog.csdn.net/qq_27570955/article/details/52442092
歡迎相互交流學習!