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();

 

你可能感兴趣的:(note.js)