当前位置:主页 > 网页前端 > vue >

Vue中使用jsencrypt进行RSA非对称加密的操作方法

时间:2023-03-07 09:34:31 | 栏目:vue | 点击:

在线生成生成RSA密钥对:http://web.chacuo.net/netrsakeypair

下载jsencrypt

cnpm i -S jsencrypt

引入

import { JSEncrypt } from "jsencrypt";

基本使用

注意:要加密的数据必须是字符串!!

提示:给公钥直接用双引号“”引起来后可能要手动删掉每行末尾多余的空格,有点麻烦,此时可以直接用``来引。只是这样可能排版显示不太好看

    testRSA() {
      let publicKey =
        "-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC4aWAgASppilGGGPv6wdCp4AqTRbQPEMxU1mNwBXmP6v0hp2eHo8LMhjjM4IwzdzOnwyTR6v5YlznBb90cWKsr/DP1IdSI9ox7M7FCHGfURfLp/mGRvNLnJ5ds7YD+35rP0wLMZhNbkXHs3HMYOY96XnSE7bfcWkLiRrwiCrqLdQIDAQAB-----END PUBLIC KEY-----"; // 从后台获取公钥
      let data = JSON.stringify({ username: "zhangsan", password: 123 });
      // let data = "hello world";
      // let data = 123 + "";//必须传字符串
 
      console.log("加密前:", data);
      let encryptor = new JSEncrypt(); 
      encryptor.setPublicKey(publicKey); 
      let data_encrypted = encryptor.encrypt(data);
      console.log("加密后:", data_encrypted);
 
      let privateKey =
        "-----BEGIN PRIVATE KEY-----MIICeQIBADANBgkqhkiG9w0BAQEFAASCAmMwggJfAgEAAoGBALhpYCABKmmKUYYY+/rB0KngCpNFtA8QzFTWY3AFeY/q/SGnZ4ejwsyGOMzgjDN3M6fDJNHq/liXOcFv3RxYqyv8M/Uh1Ij2jHszsUIcZ9RF8un+YZG80ucnl2ztgP7fms/TAsxmE1uRcezccxg5j3pedITtt9xaQuJGvCIKuot1AgMBAAECgYEAti7cWSHtrZCJk6oRHhzlsT12FSKSjSOyScn3OM8f1i933gyNOjJtmzKq4LShraKAtKcUNBItLoZP96s0zPFIQCGjON0d3XyRxoGK2h3nEZT8NTqEcQVI2sbOy5PvJHAKT/Vrcqdkt/U9YteLWAKGZ5A8Ie8NZEjh0botUwIrOIECQQDd+Qv8IYiDSugZcOPEz/ijCR4Jg011X9/bqXVIEiqkIZ+8QToKCBuGt0EejhAzs0acni1XLPwBeDmAsmg8MmpVAkEA1K5NL3ZwuLjz4vs8EfF3BfscPTQZ9PRBhzGC9iqP7TyzMRyZjGpWfycOjki8isRzR3iNoFPIyLZfe5Wf4vL8oQJBALHia6BanzPYS7hXp7CJmg/NtqyY9PIjKxq16q8fH9z4tTIAc6qmZKjJIv6Biqpj+Sp5+IvsGOh0mGBymOXk4SECQQDDxSYbeGTORMGKwERNJ/2trbYSyHDUQDpJXdP1ELynXeZ8YJ0e2YuBQ8xsQJv9CFQtB9UmLbl2uBkwQ0yHta/BAkEAoKN1vdqkDTwAkSRpvFUOHkc7E6nEYdXwM+hhKnmQLCQb2aP8zW9GI2Q7EWPDEwN92TK30k1VSzpquSU7SUA32g==-----END PRIVATE KEY-----";
      let decryptor = new JSEncrypt();
      decryptor.setPrivateKey(privateKey);
      console.log("解密后:", decryptor.decrypt(data_encrypted));
    }

您可能感兴趣的文章:

相关文章