nodejs实现des,3des,aes等加密算法的数据加密

前言

nodejs提供了crypto这个npm包,常用的加密算法都可以由crypto包提供的接口实现

各种加密算法实现

const assert = require('assert');
const crypto = require('crypto');
const key = 'dvyYRQlnPRCMdQSe';

/*
 * @brief 加密数据
 * @param[in] encodeParam<obj> 加密相关参数
 * @return 密文
 */
function crypto_encode(encodeParam) {
    try {
        let plain = encodeParam.plaintext.toString();
        //encrypt
        const iv = new Buffer(encodeParam.iv ? encodeParam.iv : 0);
        const cipher = crypto.createCipheriv(encodeParam.algorithm, encodeParam.key, iv);
        cipher.setAutoPadding(encodeParam.autoPadding)  //default true
        let ciphertext = cipher.update(plain, 'utf8', 'base64');
        ciphertext += cipher.final('base64');
        console.log("crypto data success: algorithm(%s),plaintext(%s),ciphertext(%s)",
                    encodeParam.algorithm, plain, ciphertext);
        return ciphertext;
    } catch (err) {
        console.log("crypto data failed: " + err);
        return null;
    }
}

/*
 * @brief 解密数据
 * @param[in] decodeParam<obj> 解密相关参数
 */
function decrypt_decode(decodeParam) {
    try {
        let ciphertext = decodeParam.ciphertext.toString();
        //decrypt
        const iv = new Buffer(decodeParam.iv ? decodeParam.iv : 0);
        const decipher = crypto.createDecipheriv(decodeParam.algorithm, decodeParam.key, iv);
        decipher.setAutoPadding(decodeParam.autoPadding);  //default true
        let plaintext = decipher.update(ciphertext, 'base64', 'utf8');
        plaintext += decipher.final('utf8');
        console.log("decrypt data success: algorithm(%s),plaintext(%s),ciphertext(%s)",
                    decodeParam.algorithm, plaintext, ciphertext);
        return plaintext;
    } catch (err) {
        console.log("decrypto data failed: " + err);
        return null;
    }
}


//aes-128-cbc,zeroPadding
let encodeParam = {
    algorithm : 'aes-128-cbc',
    iv : 'face0123456789ai',
    autoPadding : false,
    key : 'dvyYRQlnPRCMdQSe'
}
let plaintext = '1234qwerASDF!';       //加密后67JJSiiX5/PrNDFFO/2vxw==
let buffer_length = plaintext.length + key.length - (plaintext.length % key.length);
encodeParam.plaintext = new Buffer(buffer_length);
encodeParam.plaintext.write(plaintext);
let ciphertext = crypto_encode(encodeParam);

//3des-ecb
crypto_encode({
    algorithm : 'des-ede3',    //3des-ecb
    autoPadding : true,
    key : 'gxmy_201906110102sangfor',
    plaintext : 'zhangsan',
    iv : null
})

//des-ecb
crypto_encode({
    algorithm : 'des-ecb',
    autoPadding : true,
    key : '01234567',
    plaintext : '1234567812345678',
    iv : null
})
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值