node.js 文件加密解密、buffer加密解密及密码哈希加密

由 夕空 撰写于  2020年4月16日

文件加密解密

$ npm i file-encryptor

var encryptor = require('file-encryptor');

var key = 'SUPER-SECRET-KEY';
var options = { algorithm: 'aes256' };

encryptor.encryptFile('myVideo.mp4', 'encrypted.dat', key, options, function(err) {
// Decryption complete
});

//...

encryptor.decryptFile('encrypted.dat', 'outputfile.mp4', key, options, function(err) {
// Encryption complete
});


buffer加密解密

// Part of https://github.com/chris-rock/node-crypto-examples

var crypto = require('crypto'),
algorithm = 'aes-256-ctr',
password = 'd6F3Efeq';

function encrypt(buffer){
var cipher = crypto.createCipher(algorithm,password)
var crypted = Buffer.concat([cipher.update(buffer),cipher.final()]);
return crypted;
}

function decrypt(buffer){
var decipher = crypto.createDecipher(algorithm,password)
var dec = Buffer.concat([decipher.update(buffer) , decipher.final()]);
return dec;
}

var hw = encrypt(new Buffer("hello world", "utf8"))
// outputs hello world
console.log(decrypt(hw).toString('utf8'));

文本加密解密

// Part of https://github.com/chris-rock/node-crypto-examples

var crypto = require('crypto'),
algorithm = 'aes-256-ctr',
password = 'd6F3Efeq';

function encrypt(text){
var cipher = crypto.createCipher(algorithm,password)
var crypted = cipher.update(text,'utf8','hex')
crypted += cipher.final('hex');
return crypted;
}

function decrypt(text){
var decipher = crypto.createDecipher(algorithm,password)
var dec = decipher.update(text,'hex','utf8')
dec += decipher.final('utf8');
return dec;
}

var hw = encrypt("hello world")
// outputs hello world
console.log(decrypt(hw));


密码哈希加密

// generate a hash from string
var crypto = require('crypto'),
text = 'hello bob',
key = 'mysecret key'

// create hash
var hash = crypto.createHmac('sha512', key)
hash.update(text)
var value = hash.digest('hex')

// print result
console.log(value);



声明:星耀夕空|版权所有,违者必究|如未注明,均为原创|本网站采用BY-NC-SA协议进行授权

转载:转载请注明原文链接 - node.js 文件加密解密、buffer加密解密及密码哈希加密


欢迎光顾我的小站!