基于Node.js的AES加密

文本加密

const crypto = require('crypto');
function aesEncrypt(data,key,iv){
    let cipher = crypto.createCipheriv('aes-128-cbc', key, iv);
  return cipher.update(data, 'utf8', 'hex')+cipher.final('hex');
}
function aesDecrypt(crypted,key,iv){
    let decipher = crypto.createDecipheriv('aes-128-cbc', key, iv);
  return decipher.update(crypted, 'hex', 'utf8')+decipher.final('utf8');
}
let key = '1234567891234567';
let iv = '1234567891234567';
let text = 'hello world';
let enc = aesEncrypt(text,key,iv);
console.log(aesDecrypt(enc,key,iv));

文件加密

const crypto = require('crypto');
const fs = require('fs');
let key = '1234567891234567';
let iv = '1234567891234567';
let path = __dirname+'/files/blockchain-cat.pdf';
let enPath = __dirname+'/encrypt/blockchain-cat.pdf';
let dePath = __dirname+'/decrypt/blockchain-cat.pdf';

function aesEncryptNew(buff,key,iv){
  let cipher = crypto.createCipheriv('aes-128-cbc', key, iv);
  return cipher.update(buff,'','hex')+cipher.final('hex');
}
function aesDecryptNew(buff,key,iv){
  let decipher = crypto.createDecipheriv('aes-128-cbc', key, iv);
  return decipher.update(buff,'','hex')+decipher.final('hex');
}

let buff = fs.readFileSync(path);
let buffEnc = aesEncryptNew(buff,key,iv);
fs.writeFileSync(enPath,new Buffer(buffEnc,'hex'));

hexContent = fs.readFileSync(enPath);
let deHex = aesDecryptNew(hexContent,key,iv);
fs.writeFileSync(dePath,new Buffer(deHex,'hex'));

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