小码哥的IT人生

首页 > JS > nodejs

node.js实例:使用crypto进行加密【MD5、SHA1、HMAC、AES】

nodejs 2023-08-24 16:30:15小码哥的IT人生shichen

crypto 是Nodejs的内置模块,提供了加密功能,包括对 OpenSSL 的哈希、HMAC、加密、解密、签名、以及验证功能的一整套封装。

MD5加密

const crypto = require('crypto');
const md5 = crypto.createHash('md5');
var cryptostr = md5.update('phpcodeweb.com!').digest('hex');
console.log(cryptostr);

运行结果:

cdd7fe5d95a6b581b8f7198aab4f3b79

SHA1加密

const crypto = require('crypto');
const sha1 = crypto.createHash('sha1');
var cryptostr = sha1.update('phpcodeweb.com!').digest('hex');
console.log(cryptostr);

运行结果:

ec166e42c06a7a0cc66ff357dd67e9430ba213fc

HMAC加密

HMAC算法也是一种哈希算法,它可以利用MD5或SHA1等哈希算法,需要配置密钥。

const crypto = require('crypto');
const hmac = crypto.createHmac('sha256', 'phpcodeweb-key');
var cryptostr = hmac.update('phpcodeweb.com!').digest('hex');
console.log(cryptostr);

运行结果:

e89d3d7a59fd74866a5275416b189479111fc39e284057d9e697a75bc4d01749

AES加密解密

const crypto = require('crypto');

// function encrypt(text, key, iv) {
//     let cipher = crypto.createCipheriv('aes-128-cbc', key, iv);
//     let encrypted = cipher.update(text, 'utf8', 'base64');
//     encrypted += cipher.final('base64'); return encrypted;
// }
// let plaintext = '要加密的明文';
// let key = '0123456789012345';
// let iv = '0123456789012345';
// console.log(encrypt(plaintext, key, iv));

const key = crypto.randomBytes(192 / 8)
const iv = crypto.randomBytes(128 / 8)
const algorithm = 'aes192'
const encoding = 'hex'

const encrypt = (text) => {
    const cipher = crypto.createCipheriv(algorithm, key, iv)
    cipher.update(text)
    return cipher.final(encoding)
}

const decrypt = (encrypted) => {
    const decipher = crypto.createDecipheriv(algorithm, key, iv)
    decipher.update(encrypted, encoding)
    return decipher.final('utf8')
}

const content = 'phpcodeweb.com'
//加密
const crypted = encrypt(content)
console.log(crypted)
//解密
const decrypted = decrypt(crypted)
console.log(decrypted)

运行结果:

00acf27df94b727a867707c79f66d622
phpcodeweb.com

版权所有 © 小码哥的IT人生
Copyright © phpcodeweb All Rights Reserved
ICP备案号:苏ICP备17019232号-2  

苏公网安备 32030202000762号

© 2021-2024