使用 RSA 进行加解密
时间:2023-12-19 23:37:02
在某些业务中,为了保证数据传输的安全,我们可能需要加密和传输一些数据
我建议在这里使用RSA非对称加密可以存储在公钥中web端,私钥存储serve端
注意:使用RSA加密时要注意明文的长度,过长可能导致加密失败,可以增加RSA密文位数或分段加密的形式解决
- 前端加解密
<script src="https://cdn.bootcss.com/jsencrypt/3.0.0-beta.1/jsencrypt.min.js">//需要引入一个rsa算法script> <script> let encrypt = new JSEncrypt(); const public_key = `-----BEGIN PUBLIC KEY----- xxxxxx -----END PUBLIC KEY-----`; const private_key = `-----BEGIN RSA PRIVATE KEY----- xxxxxxx -----END RSA PRIVATE KEY-----`; encrypt.setPublicKey(public_key) const encryptKey = encrypt.encrypt('xxx'); ///用公钥加密,得到密文 encrypt.setPrivateKey(private_key) const decryptKey = encrypt.decrypt('xxx') ///用私钥解密,得到明文 console.log('encryptKey:', encryptKey) console.log('decryptKey:', decryptKey) script>
- nodejs
var NodeRSA = require("node-rsa"); const public_key = `-----BGIN PUBLIC KEY----- xxxxx -----END PUBLIC KEY-----`;
const private_key = `-----BEGIN RSA PRIVATE KEY----- xxxxx -----END RSA PRIVATE KEY-----`;
// 公钥加密
function encrypt(data) {
const nodersa = new NodeRSA(public_key);
nodersa.setOptions({
encryptionScheme: "pkcs1" }); // 需要设置格式,不设置可能会报错
const encrypted = nodersa.encrypt(data, "base64");
return encrypted;
}
// 私钥解密
function decrypt(data) {
const nodersa = new NodeRSA(private_key);
nodersa.setOptions({
encryptionScheme: "pkcs1" });
const decrypted = nodersa.decrypt(data, "utf8");
return decrypted;
}
const encryptKey = encrypt("Helasdjoasdji151561");
const decryptKey = decrypt(encryptKey);
console.log("encryptKey:", encryptKey);
console.log("decryptKey:", decryptKey);
- 使用 node-rsa 生成公私钥
const key = new NodeRSA({
b: 512 });
var publicDer = key.exportKey("public");
var privateDer = key.exportKey("private");
console.log('publicDer:', publicDer, 'privateDer:',privateDer);