nodejs aes 加解密代码分享,有需要自取
晚上睡不着,实在是没啥好水的,整个aes加密代码分享给大家吧,理论上适用于所有基于nodejs的环境,目前只测试了nodejs后端,前端未测试,但大概率肯定能用~
效果图展示
目录结构分享
项目分享
package.json
{
"name": "nodejs-aes",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "ts-node test.ts"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@types/crypto-js": "^4.1.1",
"@types/node": "^18.11.18",
"crypto": "^1.0.1",
"crypto-js": "^4.1.1",
"ts-node": "^10.9.1",
"typescript": "^4.9.5"
}
}
aes.ts
import * as CryptoJS from 'crypto-js'
const {Hex, Utf8, Base64} = CryptoJS.enc;
const mode = CryptoJS.mode.ECB;
const padding = CryptoJS.pad.Pkcs7;
// 私钥(key)和偏移量(iv)都是16位字符
const key = Utf8.parse('Tj6MQNCcpObW2A99')
const iv = Utf8.parse('Tj6MQNCcpObW2A99')
/**
* 将明文进行加密
* @param plaintext 待加密的明文
*/
export function encrypt(plaintext: string): string {
const encrypted = CryptoJS.AES.encrypt(Utf8.parse(plaintext), key, {iv, mode, padding})
return encrypted.ciphertext.toString().toUpperCase();
}
/**
* 对密文进行解密
* @param ciphertext 密文
*/
export function decrypt(ciphertext: string): string {
const hex = Hex.parse(ciphertext);
const base64 = Base64.stringify(hex);
const decrypt = CryptoJS.AES.decrypt(base64, key, {iv, mode, padding})
return decrypt.toString(Utf8);
}
test.ts
// 调用加解密函数
import {decrypt, encrypt} from "./aes";
// 原文
const text = "Hello World!";
// 密文
const ciphertext = encrypt(text);
// 明文
const plaintext = decrypt(ciphertext);
console.log({
text, // 原文
ciphertext, // 密文
plaintext // 明文
})