1. Introduction
1.aes encryption, in simple terms, also known as Rijndael encryption in cryptography, is a block encryption standard adopted by the U.S. federal government. This standard is used to replace the original DES. It has been analyzed by many parties and is widely used around the world. Advanced Encryption Standard has become one of the most popular algorithms for symmetric key encryption.
2. The block length of AES is fixed at 128 bits, and the key length can be 128, 192 or 256 bits; while the key and block length used by Rijndael can be an integer multiple of 32 bits. 128 bits is the lower limit and 256 bits is the upper limit. Including AES-ECB, AES-CBC, AES-CTR, AES-OFB, AES-CFB.
3. Here we only accept the commonly used ECB method + pkcs7padding (the same value as pkcs5padding) padding encryption.
2. Application
1.Use of aes in nodejs
var crypto = require('crypto'); var aesutil = module.exports = {}; /** * aes加密 * @param data 待加密内容 * @param key 必须为32位私钥 * @returns {string} */ aesutil.encryption = function (data, key, iv) { iv = iv || ""; var clearEncoding = 'utf8'; var cipherEncoding = 'base64'; var cipherChunks = []; var cipher = crypto.createCipheriv('aes-256-ecb', key, iv); cipher.setAutoPadding(true); cipherChunks.push(cipher.update(data, clearEncoding, cipherEncoding)); cipherChunks.push(cipher.final(cipherEncoding)); return cipherChunks.join(''); } /** * aes解密 * @param data 待解密内容 * @param key 必须为32位私钥 * @returns {string} */ aesutil.decryption = function (data, key, iv) { if (!data) { return ""; } iv = iv || ""; var clearEncoding = 'utf8'; var cipherEncoding = 'base64'; var cipherChunks = []; var decipher = crypto.createDecipheriv('aes-256-ecb', key, iv); decipher.setAutoPadding(true); cipherChunks.push(decipher.update(data, cipherEncoding, clearEncoding)); cipherChunks.push(decipher.final(clearEncoding)); return cipherChunks.join(''); }
2.Use of aes in javascript
Download the third-party library Crypto-js. js git address: https://github.com/brix/crypto-js
Introduce crypto-js.js under src, the encryption code is as follows:
var key = "12345678" //秘钥必须为:8/16/32位 var message = "123456"; //加密 var encrypt = CryptoJS.AES.encrypt(message, CryptoJS.enc.Utf8.parse(key), { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 }); console.log("value: "+encrypt); //解密 var decrypt = CryptoJS.AES.decrypt(encrypt, CryptoJS.enc.Utf8.parse(key), { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 }); console.log("value: "+decrypt.toString(CryptoJS.enc.Utf8));
The above is the entire content of this article , I hope it will be helpful to everyone’s study.
For more detailed articles related to aes encryption in nodejs and javascript, please pay attention to the PHP Chinese website!