最近常遇到需要使用AES加解密的需求,無論是網路傳輸/API相關的部份。
分享一下
Github原始碼下載
https://github.com/superlevin/CSharpAES
using System.Security.Cryptography;
public static string SHAEncrypt(string str)
{
var crypt = new System.Security.Cryptography.SHA256Managed();
var hash = new System.Text.StringBuilder();
byte[] crypto = crypt.ComputeHash(Encoding.UTF8.GetBytes(str));
foreach (byte theByte in crypto)
{
hash.Append(theByte.ToString("x2"));
// x小寫 X 大寫 x2 補0
}
return hash.ToString();
}
public static string AESEncrypt(string str, string strkey, string strivKey, bool isVasEncrypt = false)
{
var aesCipher = new AesManaged
{
KeySize = 128,
BlockSize = 128,
Mode = CipherMode.CBC,
Padding = PaddingMode.PKCS7
};
var keyStr = KeyGenerator(strkey);
var key = Convert.FromBase64String(keyStr);
var ivKey = Encoding.UTF8.GetBytes(strivKey);
var input = str;
var ivStr = Convert.ToBase64String(ivKey);
aesCipher.Key = key;
aesCipher.IV = ivKey;
byte[] b = System.Text.Encoding.UTF8.GetBytes(str); // plain text to be encrypted
ICryptoTransform encryptTransform = aesCipher.CreateEncryptor();
byte[] cipherText = encryptTransform.TransformFinalBlock(b, 0, b.Length);
return Convert.ToBase64String(cipherText);
}
public static string AESDecrypt(string encstring, string strkey, string strivKey)
{
var aesCipher = new AesManaged
{
KeySize = 128,
BlockSize = 128,
Mode = CipherMode.CBC,
Padding = PaddingMode.PKCS7
};
var keyStr = KeyGenerator(strkey);
var key = Convert.FromBase64String(keyStr);
aesCipher.Key = key;
aesCipher.IV = Encoding.UTF8.GetBytes(strivKey);
var encryptBytes = Convert.FromBase64String(encstring);
ICryptoTransform decryptTransform = aesCipher.CreateDecryptor();
byte[] plainText = decryptTransform.TransformFinalBlock(encryptBytes, 0, encryptBytes.Length);
return System.Text.Encoding.UTF8.GetString(plainText);
}