加密分类
可逆加密和不可逆加密
- 不可逆加密: 加密后不可解密,只能通过碰撞密文以极小的概率解密;
- 可逆加密: 加密后可以解密;包括对称加密与非对称加密;
- 对称加密双方采用共同密钥;
- 非对称加密: 这种加密方式存在两个密钥,密钥-- 一种是公钥,一种是密钥。使用公钥加密,则只能使用密钥解密,使用密钥加密,则只能使用公钥解密;
不可逆加密
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作为密码进行加密
let data2 = crypto.createHmac('md5', password).update(str).digest('hex');
console.log(data2);
可逆加密
对称加解密
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);
非对称加解密(基于公钥密钥)
-
生成公钥密钥
openssl genrsa -out server.key openssl req -new -key server.key -out server.csr openssl x509 -req -in server.csr -signkey server.key -out server.crt
-
验证证书功能
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())