AES算法可以实现字符串的加解密,本文主要介绍.NET Core(C#)和Js(JavaScript)中实现AES(CBC)相互加解密,分别通过.NET Core(C# RijndaelManaged CryptoStream)和aes.js实现方法及示例代码。

1、项目中引用命名空间

using System.Security.Cryptography;
using System.Text;

2、.NET Core(C#)的AES加解密实现代码

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace ConsoleApp2
{
    class Program
    {
        /// <summary>  
        /// AES加密算法  
        /// </summary>  
        /// <param name="input">明文字符串</param>  
        /// <returns>字符串</returns>  
        public static string EncryptByAES(string input, string key, string iv)
        {
            if (string.IsNullOrWhiteSpace(input))
            {
                return input;
            }
            using (RijndaelManaged rijndaelManaged = new RijndaelManaged())
            {
                rijndaelManaged.Mode = CipherMode.CBC;
                rijndaelManaged.Padding = PaddingMode.PKCS7;
                rijndaelManaged.FeedbackSize = 128;
                rijndaelManaged.Key = Encoding.UTF8.GetBytes(key);
                rijndaelManaged.IV = Encoding.UTF8.GetBytes(iv);
                ICryptoTransform encryptor = rijndaelManaged.CreateEncryptor(rijndaelManaged.Key, rijndaelManaged.IV);
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            swEncrypt.Write(input);
                        }
                        byte[] bytes = msEncrypt.ToArray();
                        return Convert.ToBase64String(bytes);
                    }
                }
            }
        }
        /// <summary>  
        /// AES解密  
        /// </summary>  
        /// <param name="input">密文字节数组</param>  
        /// <returns>返回解密后的字符串</returns>  
        public static string DecryptByAES(string input, string key, string iv)
        {
            if (string.IsNullOrWhiteSpace(input))
            {
                return input;
            }
            var buffer = Convert.FromBase64String(input);
            using (RijndaelManaged rijndaelManaged = new RijndaelManaged())
            {
                rijndaelManaged.Mode = CipherMode.CBC;
                rijndaelManaged.Padding = PaddingMode.PKCS7;
                rijndaelManaged.FeedbackSize = 128;
                rijndaelManaged.Key = Encoding.UTF8.GetBytes(key);
                rijndaelManaged.IV = Encoding.UTF8.GetBytes(iv);
                ICryptoTransform decryptor = rijndaelManaged.CreateDecryptor(rijndaelManaged.Key, rijndaelManaged.IV);
                using (MemoryStream msEncrypt = new MemoryStream(buffer))
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srEncrypt = new StreamReader(csEncrypt))
                        {
                            return srEncrypt.ReadToEnd();
                        }
                    }
                }
            }
        }
        static void Main(string[] args)
        {
            Console.WriteLine(EncryptByAES("137", "CJAVAPmXcuAksWmF", "V33CQ1428SI8ZNMT"));
            Console.WriteLine(DecryptByAES( "v9BxRJX+ojPDhyJFrglcbA==","CJAVAPmXcuAksWmF","V33CQ1428SI8ZNMT"));
            Console.ReadKey();


        }
    }
}

3、js的aes.js加解密实现代码

aes.js下载引用地址https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js

//加密
function encrypt(e,key,iv) {
       var r =  CryptoJS.enc.Utf8.parse(key),
       var n =  CryptoJS.enc.Utf8.parse(iv),
       var  o =  CryptoJS.enc.Utf8.parse(e),
       var u = {
            iv: n,
            mode:  CryptoJS.mode.CBC,
            padding:  CryptoJS.pad.Pkcs7
        },
        i =  CryptoJS.AES.encrypt(o, r, u);
        return i.toString()
 }
//解密
function decrypt(str, key, iv) {
   var r = CryptoJS.enc.Utf8.parse(iv),
   var  n = CryptoJS.enc.Utf8.parse(key),
   var o = CryptoJS.AES.decrypt(e, n, {
        iv: r,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    return CryptoJS.enc.Utf8.stringify(o).toString()
}
Node.js中实现AES(CBC)加密和解密:
安装crypto:npm install crypto
//加密
function encrypt (data, key, iv) {
    iv = iv || "";
    var clearEncoding = 'utf8';
    var cipherEncoding = 'base64';
    var cipherChunks = [];
    var cipher = crypto.createCipheriv('aes-128-cbc', key, iv);
    cipher.setAutoPadding(true);
    cipherChunks.push(cipher.update(data, clearEncoding, cipherEncoding));
    cipherChunks.push(cipher.final(cipherEncoding));
    return cipherChunks.join('');
}
//解密
function decrypt (data, key, iv) {
    if (!data) {
        return "";
    }
    iv = iv || "";
    var clearEncoding = 'utf8';
    var cipherEncoding = 'base64';
    var cipherChunks = [];
    var decipher = crypto.createDecipheriv('aes-128-cbc', key, iv);
    decipher.setAutoPadding(true);
    cipherChunks.push(decipher.update(data, cipherEncoding, clearEncoding));
    cipherChunks.push(decipher.final(clearEncoding));
    return cipherChunks.join('');
}

相关文档:

Java和aes.js实现aes(CBC)加密与解密实现代码

Python、aes.js和node.js实现aes(Crypto)加密与解密实现代码

推荐文档