|
c#版
/// <summary>
/// AES加密
/// </summary>
/// <param name=&#34;input&#34;>明文</param>
/// <param name=&#34;key&#34;>密钥</param>
/// <returns></returns>
public string AESEncrypt(string input, string key)
{
byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(input);
RijndaelManaged rDel = new RijndaelManaged();
rDel.Key = keyArray;
rDel.IV = keyArray;
rDel.Mode = CipherMode.CBC;
rDel.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = rDel.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
/// <summary>
/// AES解密
/// </summary>
/// <param name=&#34;input&#34;>密文</param>
/// <param name=&#34;key&#34;>密钥</param>
/// <returns></returns>
public string AESDecrypt(string input, string key)
{
byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
byte[] toEncryptArray = Convert.FromBase64String(input);
RijndaelManaged rDel = new RijndaelManaged();
rDel.Key = keyArray;
rDel.IV = keyArray;
rDel.Mode = CipherMode.CBC;
rDel.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = rDel.CreateDecryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
return UTF8Encoding.UTF8.GetString(resultArray);
}
nodejs-javascript版
public static aesEncrypt(input: string, key: string): string {
var iv = key;
var cipher = crypto.createCipheriv(&#39;aes-128-cbc&#39;, key, iv);
var crypted = cipher.update(input, &#39;utf8&#39;, &#39;binary&#39;);
crypted += cipher.final(&#39;binary&#39;);
crypted = Buffer.from(crypted, &#39;binary&#39;).toString(&#39;base64&#39;);
return crypted;
}
public static aesDecrypt(input: string, key: string): string {
var iv = key;
var decode = Buffer.from(input, &#34;base64&#34;).toString(&#34;binary&#34;)
var cipher = crypto.createDecipheriv(&#39;aes-128-cbc&#39;, key, iv);
var decrypted = cipher.update(decode, &#39;binary&#39;, &#39;utf8&#39;);
decrypted += cipher.final(&#39;utf8&#39;);
return decrypted;
}
key 可以参考设置为:sfe023f_9fd&fwfl
参考来源:https://github.com/fan4428/aes-128-cbc |
|