文章目录
- 一、`crypto `加解密
- 生成私密钥
- 公钥加密(也可私钥加密)
- 私钥解密(也可公钥解密)
- 二、`node-rsa`加解密
- 生成公私秘钥
- 使用公钥加密(也可私钥加密)
- 使用私钥解密(也可公钥解密)
- 三、前端项目使用`jsencrypt`加密
- 秘钥文件格式存放
- 文件
- 引入
- 总结
- `如有启发,可点赞收藏哟~`
一、crypto
加解密
crypto
是node
的内置模块无需另外安装
生成私密钥
import { generateKeyPairSync, publicEncrypt, privateDecrypt } from 'crypto'
const { publicKey, privateKey } = generateKeyPairSync('rsa', {
modulusLength: 1024,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem'
}
});
- 把生成的公私秘钥保存(
注意-------部分也是需要的,否则报错
)
// 公钥
export const PUBLIC_KEY = `
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC/NknF2LMwt77tg63x1KVXEz4Q
rKAGVhd9kUDxQaz6meP/Qy4OUDdDBGKanLkZ5n8e1YadxwHbR9XIUPohIvLNP3fm
tMGXO2oyq+TGQKmoAAuik4qtn7T3hwMAuKVClO3epgVmFMb9xbCufUE7N+xiKHa8
8z202y08jyQTVSdWHQIDAQAB
-----END PUBLIC KEY-----
`
// 私钥
export const PRIVATE_KEY = `
-----BEGIN PRIVATE KEY-----
MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAL82ScXYszC3vu2D
rfHUpVcTPhCsoAZWF32RQPFBrPqZ4/9DLg5QN0MEYpqcuRnmfx7Vhp3HAdtH1chQ
+iEi8s0/d+a0wZc7ajKr5MZAqagAC6KTiq2ftPeHAwC4pUKU7d6mBWYUxv3FsK59
QTs37GIodrzzPbTbLTyPJBNVJ1YdAgMBAAECgYEAnB2y9foLs4cSN9H/PycjJ4jq
b6rBrOq1myvxHglFNgZXhJ5RCBauR+VYrGuxJVhwCbjEhCVreqGYBkk3L77dBRRS
FwBqeZanUtTBKtZ06KKwAgRzPt/BOMNn+GDqt36U/2AyUXWg1qLe5r9hLWCEau5r
Yt8vYFrBKIaxu8YKIIECQQDxmpPEbyg9uors3yJ2qf0jv6cemMOsH3An4TdIiINx
7kFD/01otwOGFVUexPJgeCsi5zsnVK0AzdrqY6z4XBiVAkEAypsJGE/cDJb66qe3
PAA+8nRqgi6VGfQ3weCHlQhTO/ho5xPZIu63MVKyMZIPJ1MXQmMVRoz2lLmApZBL
wz79aQJBAONVUalJ9pFuz33mz2TcuoZCtZuCnst8oWnE7uHfId+4Ec1LkqjvW+90
by2On4nKSLyE2xI9CLRy/oQB2iWvcqkCQQCxAIcOlV4yJYjqjkF3iuNzYB9YwieC
uCgqGeV5Xv+QifHjxyRQ72peDdgdlHPmsCHG3tdMfoRB5FouyoRV++bZAkAso9+8
rTBM9sMow4Dw/lbeQGbvqz+w2ayfWbA4s7q8eSb25gnaAGZGAJ2Yx608DoGjIOZa
e2IyCqybjWEy7ycZ
-----END PRIVATE KEY-----
`
公钥加密(也可私钥加密)
publicKey
为上述生成的公钥
import { publicEncrypt } from 'crypto'
//需要加密的数据
const data = "data to crypto"
// 公钥加密过程
const encryptData = publicEncrypt(publicKey, Buffer.from(data)).toString('base64');
console.log('encode:', encryptData);
私钥解密(也可公钥解密)
PRIVATE_KEY
为上述生成的秘钥
encryptData
为上述加密的值
import { privateDecrypt } from 'crypto'
// 私钥解密
const decryptData = privateDecrypt(PRIVATE_KEY, Buffer.from(encryptData, 'base64'));
console.log('decode:', decryptData.toString());
二、node-rsa
加解密
生成公私秘钥
import NodeRSA from 'node-rsa'
let key = new NodeRSA({ b: 1024 })
key.setOptions({ encryptionScheme:'pkcs1'})
let pubkey = key.exportKey('public') //生成公钥,发给前端用于数据加密
let privkey = key.exportKey('private')//生成私钥,用于数据解密
console.log(pubkey)
console.log(privkey)
使用公钥加密(也可私钥加密)
需要把密码先转为base64
格式,并加上'base64', 'utf8'
两个传参,避免出现乱码情况
let encrypt = new NodeRSA(pubkey)
// encrypt.setOptions({ encryptionScheme: 'pkcs1' })
const pass_word = encrypt.encrypt(Buffer.from("123456"), 'base64', 'utf8')
console.log(pass_word)
使用私钥解密(也可公钥解密)
let decrypt= new NodeRSA(privkey)
// decrypt.setOptions({ encryptionScheme: 'pkcs1' })
const s = pass_word.replace(/\s+/g, '+')
const decryptPass = decrypt.decrypt(s, 'utf8')
console.log('decode:', decryptPass)
三、前端项目使用jsencrypt
加密
在前端项目使用前面两种加密会出现报错,发现并不支持前端项目
得使用jsencrypt
加密
import JSEncrypt from "jsencrypt";
const encrypt = new JSEncrypt();
encrypt.setPublicKey(PUBLIC_KEY);
console.log(encrypt.encrypt("123456"));
注意,后台解密的时候,需要确认秘钥生成格式
解密的时候需要设置对应格式,否则会出现解密失败的情况
decrypt.setOptions({ encryptionScheme: 'pkcs1' })
秘钥文件格式存放
文件
/src/const/secret-key/public.pem
(存放公钥数据)
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwLgQqalNF4ge6PuDxmvcJtnFm
djh4YgkmKeTwve1L5gJglp/e/uRXRsBQxw0Vv0tAAIQA0sN036j5JTxGmcuxnuZ6
5Zw75jeaBQfE6+kgMD88cUnRlje3X3lMT2kRZsja+IowEvrLiUWuhV9rBPkskhxj
vJQd1A2+KaQU09lYYwIDAQAB
-----END PUBLIC KEY-----
/src/const/secret-key/private.pem
(存放私钥数据)
-----BEGIN RSA PRIVATE KEY-----
MIICWwIBAAKBgQCwLgQqalNF4ge6PuDxmvcJtnFmdjh4YgkmKeTwve1L5gJglp/e
/uRXRsBQxw0Vv0tAAIQA0sN036j5JTxGmcuxnuZ65Zw75jeaBQfE6+kgMD88cUnR
lje3X3lMT2kRZsja+IowEvrLiUWuhV9rBPkskhxjvJQd1A2+KaQU09lYYwIDAQAB
AoGAaUemT55oErumeIJ4s4gyFcjDbUI6Lp4O75JbcA1fD1rsksGP2Zch5pGt/Ndm
F1fP5Pgp6cAI8v9wnynEIkBnesS0j+Ydu43b6f94CXW5BwvQjy3mmkMKDvE8MHcT
h/lEosAIFfbpHD+5Uhxu47ynQRXzP9OE5Rn//MjeAS94XtkCQQD6qOQ9r2r4SsOr
5Rqh0Fr6xZrPvV5tuO2fhe+WO1XeVXPe7Dizdlck/AyWn8fL2dUERn+KvBiUblOy
zuFbQv09AkEAs+7oaDT4pkkV1mLvb+VSIut2guzcGh5o7n3dkXEKnca9dACRMK5N
Vecp3dnbAtJJwpXMuP5eJJYEc74HH1ZGHwJAAZdQ25NhenH/C/hIUv6flTfr46Ww
E8I4v+p5utplkSO5uJCHS5xUsUdoTQx2mDSpxX0tEhRfk5GftmLZy1qBgQJAUJ/+
t6L0v94D0Pqn+2WwNkF36xajUXjK4AK6I4+ZiDUjczVF2aBguttIIUabIlqD/pMN
Ft+z44TtHcfKfTo1VQJAYcgb8uGXgZVz9fFZqAaE8I0W2JkGn4zsta+RjSwxTJj9
SHDuAXBVEeLpS4hM8CA4fHmti6A0ezqh9B3U750/DA==
-----END RSA PRIVATE KEY-----
引入
const fs = require('fs')
const path = require('path')
//读取私钥加密
const rsaS = fs.readFileSync(path.join(__dirname,'./const/secret-key/private.pem'));
console.log('rsaS_rsaS', rsaS.toString())