AES
1 /// <summary> 2 /// AES 加密 3 /// </summary> 4 /// <param name="str">明文(待加密)</param> 5 /// <param name="key">密文</param> 6 /// <returns></returns> 7 public static string AesEncrypt(string str, string key) 8 { 9 if (string.IsNullOrEmpty(str)) return null; 10 Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str); 11 12 System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged 13 { 14 Key = Encoding.UTF8.GetBytes(key), 15 Mode = System.Security.Cryptography.CipherMode.ECB, 16 Padding = System.Security.Cryptography.PaddingMode.PKCS7 17 }; 18 19 System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateEncryptor(); 20 Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); 21 22 return Convert.ToBase64String(resultArray, 0, resultArray.Length); 23 } 24 /// <summary> 25 /// AES 解密 26 /// </summary> 27 /// <param name="str">明文(待解密)</param> 28 /// <param name="key">密文</param> 29 /// <returns></returns> 30 public static string AesDecrypt(string str, string key) 31 { 32 if (string.IsNullOrEmpty(str)) return null; 33 Byte[] toEncryptArray = Convert.FromBase64String(str); 34 35 System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged 36 { 37 Key = Encoding.UTF8.GetBytes(key), 38 Mode = System.Security.Cryptography.CipherMode.ECB, 39 Padding = System.Security.Cryptography.PaddingMode.PKCS7 40 }; 41 42 System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateDecryptor(); 43 Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); 44 45 return Encoding.UTF8.GetString(resultArray); 46 }
如果提示key不是有效位数,需要转换
byte[] keyArray = null; using (var sha1 = new SHA1CryptoServiceProvider()) { byte[] hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(key)); var rd = sha1.ComputeHash(hash); keyArray = rd.Take(16).ToArray(); }
3DES
public static string Encrypt3DES(string text, string key)
{
TripleDESCryptoServiceProvider tripleDes = new TripleDESCryptoServiceProvider();
byte[] inputArray = Encoding.UTF8.GetBytes(text);
tripleDes.Key = Encoding.UTF8.GetBytes(key);
tripleDes.Mode = CipherMode.ECB;
tripleDes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tripleDes.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length);
tripleDes.Clear();
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
public static string Decrypt3DES(string input, string key)
{
byte[] inputArray = Convert.FromBase64String(input);
TripleDESCryptoServiceProvider tripleDes = new TripleDESCryptoServiceProvider();
tripleDes.Key = Encoding.UTF8.GetBytes(key);
tripleDes.Mode = CipherMode.ECB;
tripleDes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tripleDes.CreateDecryptor();
byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length);
tripleDes.Clear();
return Encoding.UTF8.GetString(resultArray);
}
浙公网安备 33010602011771号