使用 RSA 进行加解密

400 阅读1分钟

在某些业务中我们可能为了要保证数据传输的安全性,需要对一些数据进行加密传输 在这里我建议使用RSA非对称加密进行加密,可以将公钥存储在web端,私钥存储在serve端

  • 前端加解密
<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 = `-----BEGIN 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);