crypto(加密、签名)

哈希算法签名:(MD5或SHA1、sha256、sha512)

const crypto = require('crypto');

let hash = crypto.createHash('md5');   //创建hash对象

// 可任意多次调用update();
hash.update('abcd');    //添加数据
hash.update('efg');     //添加数据

console.log(hash.digest('hex')); //7ac66c0f148de9519b8bd264312c4d64

Hmac哈希算法签名:(不同的是,Hmac还需要一个密钥)

const crypto = require('crypto');

let hmac = crypto.createHmac('sha256', '我是密匙字符串');

hmac.update('abcd');  //添加数据
hmac.update('efg');   //添加数据

console.log(hmac.digest('hex')); 
//4132f9ccff8720f858a1a161f833e73e0f5440741a2e28eab1d2cd5a217a1cff

数据的加密和解密:(Cipher加密、Decipher解密)

const crypto = require('crypto');

function encrypt(data, key) {
    //用'aes192'算法和key密匙创建加密对象
    let cipher = crypto.createCipher('aes192', key); 

    let crypted = cipher.update(data, 'utf8', 'hex'); //添加数据
    crypted += cipher.final('hex');    //加密
    return crypted;
}

function decrypt(encrypted, key) {
    //用'aes192'算法和加密用的key密匙创建解密对象
    let decipher = crypto.createDecipher('aes192', key);  

    let decrypted = decipher.update(encrypted, 'hex', 'utf8');  //添加已加密的数据
    decrypted += decipher.final('utf8');  //解密
    return decrypted;
}

let data = 'abcdefg';
let key = '我是密匙字符串';
let encrypted = encrypt(data, key);
let decrypted = decrypt(encrypted, key);

console.log('加密前: ' + data);
console.log('加密后: ' + encrypted);
console.log('解密后: ' + decrypted);

 

你可能感兴趣的:(node)