js/node aes128cbc加解密

1.安装 crypto 模块
npm i crypto --save 
2. 封装AES128加解密工具类 aes-util.js
import crypto from 'crypto';

const KEY = '21c081ba60f49b07';
const IV = 'c4c64d8a21c081ba';

/**
 * 加密方法
 * @param data     需要加密的数据
 * @param key 加密key
 * @param iv       向量
 * @returns string
 */
const encrypt = (data, key = KEY, iv = IV) => {
    let crypted = null;
    try {
        const cipher = crypto.createCipheriv('aes-128-cbc', key, iv);
        crypted = cipher.update(data, 'utf8', 'binary');
        crypted += cipher.final('binary');
        crypted = Buffer.from(crypted, 'binary').toString('base64');
    } catch (error) {
        console.error(error);
    }
    return crypted;
};

/**
 * 解密方法
 * @param crypted  密文
 * @param key      解密的key
 * @param iv       向量
 * @returns string
 */
const decrypt = (crypted, key = KEY, iv = IV) => {
    let decoded = null;
    try {
        const cd = Buffer.from(crypted, 'base64').toString('binary');
        const decipher = crypto.createDecipheriv('aes-128-cbc', key, iv);
        decoded = decipher.update(cd, 'binary', 'utf8');
        decoded += decipher.final('utf8');
    } catch (error) {
        console.error(error);
    }
    return decoded;
};

export default { encrypt, decrypt };

3.使用AESUtil工具

//test.js

import AESUtil from './aes-util';

const data = AESUtil.encrypt(`123`);
const aesdata = data;
console.log(`加密的:`,aesdata);
console.log(`解密的:`,AESUtil.decrypt(aesdata ));
4. 输出结果

js/node aes128cbc加解密_第1张图片
在这里插入图片描述

你可能感兴趣的:(好玩的JavaScript,nodejs,javascript)