下载
npm i jsencrypt
大家可以自己 在线生成密钥对 来试试
生成密钥对// JSEncrypt 随机生成 公钥、私钥
export function createKey() {
const crypt = new JSEncrypt({ default_key_size: 1024 });
const publicDer = crypt.getPublicKey(); //公钥
const privateDer = crypt.getPrivateKey(); //私钥
return { publicDer, privateDer };
}
加密
import { JSEncrypt } from 'jsencrypt'
// 公钥
const key = `xxxx`
// 加密
export function setEncrypt (msg) {
const jsencrypt = new JSEncrypt()
jsencrypt.setPublicKey(key)
return jsencrypt.encrypt(msg)
}
解密
// 私钥
const privateKey = `xxxx`
// 解密
export function decrypt (msg) {
let decrypt = new JSEncrypt()
decrypt.setPrivateKey(privateKey)
var decryptMsg = decrypt.decrypt(msg)
return decryptMsg
}
node-rsa 加密解密 非对称 可以动态生成密钥
下载
npm i node-rsa
const nodeRSA = require('node-rsa')
// 生成一个1024长度的密钥对
const key = new nodeRSA({ b: 1024 })
const publicKey = key.exportKey('pkcs8-public') // 公钥
const privateKey = key.exportKey('pkcs8-private') // 私钥
const txt = '123'
// 使用公钥加密
function encrypt(data) {
const pubKey = new nodeRSA(publicKey, 'pkcs8-public')
return pubKey.encrypt(Buffer.from(data), 'base64')
}
// 使用私钥解密
function decrypt(data) {
const priKey = new nodeRSA(privateKey, 'pkcs1-private')
return priKey.decrypt(Buffer.from(data, 'base64'), 'utf8')
}
const sign = encrypt(txt)
const _src = decrypt(sign)
console.log('加密:', sign)
console.log('解密:', _src)
/*
加密: fBaBFVPv+96I/r6a2tfPbYWa0yjgJKQ+K2/E9obGNo0dYBOSBzW2PgnPOHX+/pq0wUZPxJzcwt5YcMtOsUNuZAYpaPZJ9o6IOEKj823HBNbyerDMUfU3rINCk2FilRuxFpQPmBZTbSvSumKligdtsh1Vz02DwdRgbJHp5bm4Hjk=
解密: 123
*/
// 使用私钥对消息签名
function signRSA(data) {
const priKey = new nodeRSA(privateKey, 'pkcs8-private')
return priKey.sign(Buffer.from(data), 'hex')
}
// 使用公钥验证签名
function verifyRSA(decrypt, signs) {
const pubKey = new nodeRSA(publicKey, 'pkcs8-public')
return pubKey.verify(Buffer.from(decrypt), signs, 'utf8', 'hex')
}
const signature = signRSA(sign)
console.log('私钥签名:' + signature)
console.log('公钥验证:' + verifyRSA(sign, signature))
/*
私钥签名:873ae60fa3a5a89850185632b53e54b7c9919d146f2464a857f83679d9862e0612973c891994f6f576d4c04913a8b0a17b9b3adaa3577fcb81d637b2ede0c4a1cffadcaa99b81d09a7edfa69a813cd9f87fe52d96c371f6af533dd5577fdc0f6f7dc6857e1a78d425c0be71f7c440e44e8f932c4ed8890dba007721d10832e92
公钥验证:true
*/
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)