nodejs加解密
加密分類
可逆加密和不可逆加密
不可逆加密
const crypto = require('crypto');let str = 'abcd';let password = 'hello';// 不可逆加密// 支持md5/sha1/sha256等加密let data1 = crypto.createHash('md5').update(str).digest('hex');console.log(data1);// 以指定key作為密碼進(jìn)行加密let data2 = crypto.createHmac('md5', password).update(str).digest('hex');console.log(data2);可逆加密
對(duì)稱加解密
const crypto = require('crypto');let str = 'abcd';const password = 'FnJL7EDzjqWjcaY9';const iv = 'FnJL7EDzjqWjcaY9';// 加密const cipher = crypto.createCipheriv('aes-128-cbc', password, iv);cipher.update(str,'utf8', 'hex')let data3 = cipher.final('hex');console.log(data3);// 解密const decipher = crypto.createDecipheriv('aes-128-cbc', password, iv);decipher.update(data3, 'hex', 'utf8')let data4 = decipher.final().toString();console.log(data4);非對(duì)稱加解密(基于公鑰密鑰)
生成公鑰密鑰
openssl genrsa -out server.keyopenssl req -new -key server.key -out server.csropenssl x509 -req -in server.csr -signkey server.key -out server.crt驗(yàn)證證書功能
const crypto = require('crypto');const fs = require('fs');const sign = crypto.createSign('RSA-SHA256');const verify = crypto.createVerify('RSA-SHA256');const privateKey = fs.readFileSync('./server.key').toString(); //rsa私鑰const publicKey = fs.readFileSync('./server.crt').toString();const str = 'abcd';sign.update(str);verify.update(str);let signture = sign.sign(privateKey);let result = verify.verify(publicKey, signture);console.log(result); // true/false公鑰密鑰加解密
const crypto = require('crypto');const fs = require('fs');const privateKey = fs.readFileSync('./server.key').toString(); //rsa私鑰const publicKey = fs.readFileSync('./server.crt').toString();const str = 'abcd';// 公鑰加密,密鑰解密const publicEncodeData = crypto.publicEncrypt(publicKey, Buffer.from(str)).toString('base64');console.log("encode: ", publicEncodeData);const privateDecodeData = crypto.privateDecrypt(privateKey, Buffer.from(publicEncodeData.toString('base64'), 'base64'));console.log("decode: ", privateDecodeData.toString())// 密鑰加密,公鑰解密const privateEncodeData = crypto.privateEncrypt(privateKey, Buffer.from(str)).toString('base64');console.log("encode: ", privateEncodeData);const publicDecodeData = crypto.publicDecrypt(privateKey, Buffer.from(privateEncodeData.toString('base64'), 'base64'));console.log("decode: ", publicDecodeData.toString())轉(zhuǎn)載于:https://www.cnblogs.com/zhaowinter/p/10825565.html
總結(jié)
- 上一篇: Nginx配置同时适配电脑和移动端设备
- 下一篇: vue基础知识(一)