note.js加解密(包含AES和RSA)

const crypto = require('crypto');
const fs = require('fs')

function encryption(plaintext, key, iv) {
    var cipherEncoding = 'base64';
    var clearEncoding = 'utf8'
    

    const cipher = crypto.createCipheriv('aes128', key, nonce);
    cipher.setAutoPadding(true);
    

    var cipherChunks = [];
    cipherChunks.push(cipher.update(plaintext, clearEncoding, cipherEncoding));
    cipherChunks.push(cipher.final(cipherEncoding));
    //console.log(cipherEncoding + ' ciphertext: ' + cipherChunks.join(''));
    var strcipherChunks = cipherChunks.join('')
    //console.log("strcipherChunks=", strcipherChunks);
    return strcipherChunks;
}


function decryption(strcipherChunks, key, iv) {
    var cipherEncoding = 'base64';
    var clearEncoding = 'utf8'
    const decipher = crypto.createDecipheriv('aes128', key, nonce);
    decipher.setAutoPadding(true);



    var plainChunks = [];
    //for (var i = 0; i < cipherChunks.length; i++) {
    //    plainChunks.push(decipher.update(cipherChunks[i], cipherEncoding, clearEncoding));
    //}
    plainChunks.push(decipher.update(strcipherChunks, cipherEncoding, clearEncoding));
    plainChunks.push(decipher.final(clearEncoding));
    //console.log("UTF8 plaintext deciphered: " + plainChunks.join(''));
    return plainChunks.join('');
}

function RSA() {
    

    const publicKey = fs.readFileSync('public.pem').toString('ascii');
    const privateKey = fs.readFileSync('private.pem').toString('ascii');
    console.log(publicKey)
    console.log(privateKey)

    const data = "0123456789abcdef";        //要加密的明文
    console.log("content: ", data)
    //公钥加密
    const encodeData = crypto.publicEncrypt({
        key: publicKey,
        padding: crypto.constants.RSA_PKCS1_PADDING
    }, Buffer.from(data.toString('utf8'))).toString('base64');
    console.log("encode: ", encodeData)
    //私钥解密
    const decodeData = crypto.privateDecrypt({
            key: privateKey,
            padding: crypto.constants.RSA_PKCS1_PADDING
        },
        Buffer.from(encodeData, 'base64'));
    console.log("decode: ", decodeData.toString())
}


//测试AES
const key = new Buffer('0123456789abcdef');
const nonce = new Buffer('0000000000000010');//crypto.randomBytes(12);
const plaintext = 'Here is some data to encrypt!';
console.log("plaintext=", plaintext);

var ciperText = encryption(plaintext, key, nonce);
console.log("ciperText=", ciperText);
var newPlain = decryption(ciperText, key, nonce);
console.log("newPlain=", newPlain);

//测试RSA
RSA();

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值