// 引入crypto-js库,这是一个常用的加密库,支持AES加密算法
// 可以通过CDN引入或npm安装
// 通过CDN引入
// <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>
// npm安装
// npm install crypto-js
const CryptoJS = require("crypto-js");
// 定义要加密的文本和密钥
const plaintext = "This is a secret message";
const secretKey = "my-secret-key-123";
// AES加密
function encrypt(plaintext, secretKey) {
// 使用CryptoJS.AES.encrypt方法进行加密,返回值是一个Base64编码的字符串
const ciphertext = CryptoJS.AES.encrypt(plaintext, secretKey).toString();
return ciphertext;
}
// AES解密
function decrypt(ciphertext, secretKey) {
// 使用CryptoJS.AES.decrypt方法进行解密,返回值是一个CipherParams对象
// 需要调用toString(CryptoJS.enc.Utf8)将其转换为原始字符串
const bytes = CryptoJS.AES.decrypt(ciphertext, secretKey);
const plaintext = bytes.toString(CryptoJS.enc.Utf8);
return plaintext;
}
// 示例使用
const encrypted = encrypt(plaintext, secretKey);
console.log("Encrypted:", encrypted);
const decrypted = decrypt(encrypted, secretKey);
console.log("Decrypted:", decrypted);
plaintext是要加密的明文,secretKey是用于加密和解密的密钥。encrypt函数使用CryptoJS的AES.encrypt方法对明文进行加密,并返回Base64编码的密文。decrypt函数使用CryptoJS的AES.decrypt方法对密文进行解密,并返回原始的明文。encrypt和decrypt函数进行加密和解密操作。上一篇:js 字符串排序
下一篇:js aes 加密
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站