前端使用js实现Rsa的加密和解密

  • Post author:
  • Post category:其他


感谢原创!!!

原文链接:

https://blog.csdn.net/XKFC1/article/details/125220301

1.先安装jsencrypt

npm install jsencrypt

2.封装

公钥私钥可以通过命令行生成

import JSEncrypt from 'jsencrypt'

let priKey = '-----BEGIN RSA PRIVATE KEY-----MIICXQIBAAKBgQDvupVIIoSGBwdLXqP/ox0YYr1pj7ZmadC7i0mujqzIjpBh/NCJmZWtb4rmZyN18PPcctxIbyndJQ//BrUnFc4v0F4fjciHBuwSBAtaMBjoyj2CBiijHK6H96+cHv+AiudD0Vf3Ij0T7BaLZJZ/Ss3M25mRuT5cYN09M8Bt34Dv2wIDAQABAoGAVJQNqx+Shf7g0fSYA882qq3biezMO6HFpQVlf5KS30d9JTUfFgz7w+8AoH1vA2N5hiN4GI4vxPgYhq+FJj8JOSKAcmaGYnPKUd41yI/07tHMxNuXngJW0AyjhFFloEwp620VZGMzdPqkUMG5JvIViYoXc5yb1bE55l0TOUHUK/ECQQD9BYx4KqlNs9VKdrBla79iqjlgAff8nK542g/pIeKTcin/ARQRxVue/ABHyNnaJY+Ji7fpRACg3u2ECklur1DlAkEA8oz6X2l2xt+lK2bXCJhQ8dI68DGAQZBIwAHNQfTkppZXuTg/EErPo6XgXT3cletQ6+rvF3Dd2lk8loRQ5JzxvwJAdUIxCy+aLqx82HmQ3i/FDlCdLmU7LBLguJk2bnCJtJNf6xHw3xt7jn5zEtF+RJ7Lmo7puG0PbX5izKKHzYfqEQJBALTZGuHDQBW+sWewEUtOTqRP7TQkpI2+KBBKB6JTF52CYbwvzQ23yiQpzSWYt31s7HRLQqRGupRQjxVnaO1ce/8CQQCy65L/c+kqTF3zqrnoaKlScz6D877fsR1MQO3OJdCPkJdKTaGVrtKMazBBp0CN9Z98SJxvqIFizpesQnb+Daq2-----END RSA PRIVATE KEY-----'

let pubKey = '-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDvupVIIoSGBwdLXqP/ox0YYr1pj7ZmadC7i0mujqzIjpBh/NCJmZWtb4rmZyN18PPcctxIbyndJQ//BrUnFc4v0F4fjciHBuwSBAtaMBjoyj2CBiijHK6H96+cHv+AiudD0Vf3Ij0T7BaLZJZ/Ss3M25mRuT5cYN09M8Bt34Dv2wIDAQAB-----END PUBLIC KEY-----'
let RSA = {
    //使用公钥加密

    jiami(str) {
        let encrypt = new JSEncrypt();
        encrypt.setPublicKey(pubKey);
        let encrypted = encrypt.encrypt(str);
        return encrypted
        console.log('加密后数据:%o', encrypted);

    },
    jiemi(str) {
        //使用私钥解密
        let decrypt = new JSEncrypt();
        decrypt.setPrivateKey(priKey);
        let uncrypted = decrypt.decrypt(str);
        return uncrypted;
        console.log('解密后数据:%o', uncrypted); // 张三

    }
}
export default RSA;

3.引入使用

import Rsa from '@/utils/rsa.js';

let message = '要加密的内容';
let str=Rsa.jiami(message);
console.log(str)
console.log(str,Rsa.jiemi(str));