Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

js aes加密算法

作者:ˉ吻干迩的'泪   发布日期:2025-11-08   浏览:57

// 引入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);

解释说明:

  1. 引入CryptoJS库:可以通过CDN或npm安装的方式引入CryptoJS库。
  2. 定义要加密的文本和密钥plaintext是要加密的明文,secretKey是用于加密和解密的密钥。
  3. AES加密函数encrypt函数使用CryptoJS的AES.encrypt方法对明文进行加密,并返回Base64编码的密文。
  4. AES解密函数decrypt函数使用CryptoJS的AES.decrypt方法对密文进行解密,并返回原始的明文。
  5. 示例使用:演示了如何使用encryptdecrypt函数进行加密和解密操作。

上一篇:js 字符串排序

下一篇:js aes 加密

大家都在看

js 数组对象排序

js 数组删掉第一个值

js fill

js 数组连接

js json数组

js 数组复制

js 复制数组

js 数组拷贝

js 对象数组合并

js 对象转数组

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站