Preface
CryptoJS is a JavaScript encryption algorithm library used to perform encryption and decryption operations in client browsers. It provides a series of common encryption algorithms, such as AES, DES, Triple DES, Rabbit, RC4, MD5, SHA-1, and so on.
AES
How it works
AES (Advanced Encryption Standard) is a symmetric encryption algorithm, that is, encryption and decryption use the same key. It can encrypt blocks of data of lengths of 128, 192 and 256 bits and encrypt them using a 128 bit key. The AES algorithm uses fixed block length and key length, and is widely used in many security protocols and standards, such as SSL/TLS, SSH, IPSec, etc.
In AES encryption, the plaintext is divided into 128-bit blocks, each block encrypted with the same key. The encryption process includes the following steps:
Key extension: Expand the key into a wheel key required by the encryption algorithm.
Initial wheel: divide the plain text into blocks and perform an exclusive OR with the first round key.
Multi-round encryption: The results generated by the initial wheel are repeatedly encrypted for multiple rounds, and each round is encrypted using a different wheel key.
Final round: In the last round of encryption, the block is encrypted, but the next round of encryption is no longer performed, but the ciphertext is output directly.
The decryption process is similar to the encryption process, except that the steps in the encryption process are reversed. It should be noted that the same key and wheel key are used during the decryption process. Since AES is a block encryption algorithm, during the encryption process, data needs to be filled to ensure that the data block size is 128 bits.
Advantages of AES algorithm
High security: AES algorithm is a reliable encryption algorithm, which has a wide range of applications in the fields of data transmission, file encryption and network security.
High efficiency: The AES algorithm uses symmetric encryption algorithm for encryption and decryption, and uses the same key for encryption and decryption. Symmetric encryption algorithms are more efficient than asymmetric encryption algorithms, so the AES algorithm has higher efficiency.
Widely used: AES algorithm has a wide range of applications in the fields of data transmission, file encryption and network security. During data transmission, the AES algorithm can encrypt the data to protect the security of the data. During the file encryption process, the AES algorithm can encrypt the file to protect the security of the file. In the field of network security, AES algorithms can encrypt network data and protect network security.
github address:/brix/crypto-js
cryptojs documentation:/docs/#encoders
Online AES encryption and decryption tool:/cryptaes
Install
script tag embedding
<script src="/ajax/libs/crypto-js/4.1.1/"></script>
npm or yarn installation
npm install crypto-js yarn add crypto-js
CommonJS
const CryptoJS = require('crypto-js');
ES module:
import CryptoJS from 'crypto-js';
Encapsulation encryption and decryption
import CryptoJS from 'crypto-js' // ------------AES------------- function getAesString(data, key, iv) { //encryption let keys = .(key) let vis = .(iv) let encrypt = (data, keys, { iv: vis, //iv offset CBC needs to add offset mode: , //CBC mode // mode: , //ECB mode padding: .Pkcs7 //padding processing }); // debugger return (); //After the encryption is completed, it is converted into a string } function getDAesString(encrypted, key, iv) { // Decrypt var key = .(key); var iv = .(iv); var decrypted =(encrypted,key,{ iv:iv, mode:, padding:.Pkcs7 }); return (.Utf8); } // AES symmetric key encryption const aes = { en: (data, key) => getAesString(data, , ), de: (data, key) => getDAesString(data, , ) }; // BASE64 const base64 = { en: (data) => .(.(data)), de: (data) => .(data).toString(.Utf8) }; // SHA256 const sha256 = (data) => { return CryptoJS.SHA256(data).toString(); }; // MD5 const md5 = (data) => { return CryptoJS.MD5(data).toString(); }; export { aes, md5, sha256, base64 };
Generate a key using JSEncrypt
JSEncrypt is an RSA encryption library based on JavaScript, allowing encryption and decryption operations using RSA algorithms on the browser side. It provides an easy-to-use API, simplifying the process of encryption on the client.
JSEncrypt supports the following operations:
Generate key pairs: You can use JSEncrypt to generate RSA key pairs, including public and private keys.
Encryption: Use a public key to encrypt data to ensure that only servers with private keys can decrypt.
Decryption: Use the private key to decrypt data encrypted by the public key.
Key format: JSEncrypt supports a variety of key formats, including PEM format (based on Base64 encoding).
The basic steps for RSA encryption using JSEncrypt are as follows:
Introduce the JSEncrypt library: Introduce the script file of the JSEncrypt library in the HTML page.
Create a JSEncrypt object: Use the JSEncrypt constructor to create a new JSEncrypt object.
Generate key pair: Encapsulate the getKey() method to generate an RSA key pair, and encrypt the generated private key and pass it to the backend.
Encrypt data: Use the (plainText) method to encrypt plaintext data.
Decrypt data: Use the private key to decrypt it on the server side to obtain the original data.
It should be noted that since JSEncrypt is executed on the client, there may be security risks in the key during transmission. In order to ensure the security of the data, it is recommended to use a secure communication protocol between the client and the server for data transmission, and further security verification and processing are carried out on the server side.
import JSEncrypt from 'jsencrypt' const encrypt = new JSEncrypt(); let publicKey = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCeCDcnFrS7DIRbvZLHreVUzaMbAFy2DYmioxBK606urY4rVR8IgLgUhnyw2/GQ99pyr8lGtqPeOoapantw1XwEVyi74MDxs4UDL8j4OZR1Es7HVGOB0GwKWobdU9cm/1iDwGyouSmijxKyAePg6KsLNgbjDPYZRS11bYEuZ8/RLQIDAQAB'; ('-----BEGIN PUBLIC KEY-----' + publicKey + '-----END PUBLIC KEY-----') const random = (length) => { var str = ().toString(36).substr(2); if (>=length) { return (0, length); } str += random(); return str; } export const rsaEncode = (src)=>{ let data = (src); // Encryption return data }; export const getKey = ()=>{ let key = { key: random(16), iv: random(16) }; // Generate key let code = rsaEncode( + ',' + ) // Encrypt the key, and pass the encrypted key to the backend = || {} codeArr[code] = key return { key, code } }; export const getAesKey = (aes)=>{ let key = ((codeArr[aes])) delete codeArr[aes] return key }; = getKey = rsaEncode
publicKey can be returned by sending requests, or it can be defined by itself, requiring the front and back end to be consistent
Encapsulate axios interceptor for encryption and decryption
/** * * http configuration * */ // Introduce loading and message components in axios and element uiimport { aes } from "@/util/"; import { getKey, getAesKey } from "@/config/"; import axios from "axios"; import store from "../store"; import router from "../router/router"; import { Loading, Message } from "element-ui"; import { getSessStore, setSessStore } from "@/util/store"; // Timeout timeif () = 20000; else = 0; //Cross-domain request, allowing cookies to be saved = true; // Unified encryption and decryptionconst Unify = { // Unified encryption method en(data, key) { // Encryption let aesStr = ((data), key); return aesStr; }, // Unified decryption de(aesStr, key) { // Decrypt let dataStr = (aesStr, key); // 3. Transform json object let data = (dataStr); return data; }, }; let loadinginstace; let cfg, msg; msg = "The server is gone, please try again later"; function ens(data) { // debugger let src = [...data]; src = (src); let dataJm = (src); return dataJm; } function des(data) { // debugger let src = [...data]; let dataJm = (src); dataJm = (dataJm); return dataJm; } const cancelToken = const source = () //HTTPrequest intercept( function (config) { (, "Introduce the parameter before encryption ---"); = ; // Add cancelToken globally loadinginstace = ({ fullscreen: true, }); if () { let info = getSessStore("token"); // ("info", info); ["Authorization"] = "Bearer " + info; // Let each request carry token-- ['X-Token'] as a custom key Please modify it yourself according to the actual situation } const contenttype = ["Accept"]; let types = ("application/json"); let key = getKey(); // Get the key ["aes"] = ; // Set the code of aes to the request header and pass it to the backend to decrypt ["name"] = "send"; if (types) { if ( == "post" || == "put") { if () { ["crypto"] = true; ["content-type"] = "application/json"; let data = { body: , }; let dataJm = (data, ); // Encrypt post request parameters = dataJm; } } } return config; }, (error) => { return (error); } ); //HTTPresponse Intercept( (response) => { (); let res = || {}; if (["date"]) { ("setServiceTime", ); } if () { try { let key = getAesKey(); /// Get the public key encryption string if (!key) { message("Get key exception", "error"); return (res); } // debugger res = (, key); = res; } catch (err) { message("System Exception:" + , "error"); return (err); } } // debugger if ( === 1) { message(, "error"); return (res); } (response, "Decrypted response"); return response; }, (error) => { ("error message", error); (); const res = || {}; if ( === 478 || === 403 || === 401) { let resMsg = ? : if ( === 403) { message('Service authorization failed, please contact management to add permissions! ', "error"); } else { message(resMsg, "error"); } let flg = ('The current login status has expired') if ( === 478 && flg) { //Token invalid ('Login information has expired'); // Cancel other ongoing requests ("FedLogOut").then(() => { ("/login"); ///test }); } } else if ( === 400) { message(.error_description, "error"); } else if ( === 202) { //The three parties are not bound this.$({ path: "/", }); } else if ( === 503 || === 504) { //Exception of service message(, "error"); } else if ( ( === 401 && == "Unauthorized") || == "invalid_token" || == "unauthorized" ) { //Token invalid ("FedLogOut").then(() => { ("/login"); ///test }); } else { message(, "error"); } return (error); } ); export function message(text, type) { let t = text ? text : "Service or network exception!" Message({ message: t, type: type, duration: 30 * 1000, center: true, showClose: true }); } export default axios;
Summarize
Encryption: Use JSEncrypt to generate a private keykey
And put the keykey
Encryptedcode
, use()
and key encrypt the request data, and the encryptedcode
Set in the request header and after the backend obtains encryptioncode
Decrypt the private keykey
, then decrypt the requested data to obtain the original data
Decryption: The front-end obtains the key of the response header and obtains the private key through decryption by decrypting JSEncrypt.key
, use()
The method decrypts the response data to obtain the original data
This is the article about the encryption and decryption of front-end using crypto-js library aes. For more related contents of front-end crypto-js library aes, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!