vue2项目使用jsencrypt.js实现分段加密解密

安装:npm install jsencrypt

安装:npm install js-base64

组件:demo.vue

<template></template>
<script>
// 加密 解密
import { rsaEncryptSet, rsaDecryptSet } from "@/assets/des";
import testImportJson from '@/assets/data.json'
export default {
  data() {
    return {
      jsonData: testImportJson
    };
  },
  created() {
    let data = "测试传字符串"
    // let data = this.jsonData //测试json数据加密

    let jiami = rsaEncryptSet(data);
    console.log('加密:',jiami);
    let jiemi = rsaDecryptSet(jiami);
    console.log('解密:',jiemi);
  },
  methods: {}
};
</script>

 

des.js
import { JSEncrypt } from 'jsencrypt'
const Base64 = require("js-base64").Base64
// 公钥
var pubKey = "-----BEGIN PUBLIC KEY-----" + "您的公钥" + "-----END PUBLIC KEY-----";
// 私钥
var priKey = "-----BEGIN RSA PRIVATE KEY-----" + "您的私钥" + "-----END RSA PRIVATE KEY-----"
// 分段拼接符
const $splitStr = "[montage@]" 
// 实例化一个RSA对象
var encrypt = new JSEncrypt();
// 设置公钥和私钥
encrypt.setPublicKey(pubKey);
encrypt.setPrivateKey(priKey);
/**
 * [rsaEncryptSet 文本加密]
 * @param  {[type]} content 待加密文本
 * JSON转换 ——> Base64转换 ——> encrypt加密(分段加密)
 */
export const rsaEncryptSet = (content) => {
  if (content == undefined) return
  let jsonContent = JSON.stringify(content); // JSON转换
  let newText = Base64.encode(jsonContent); // Base64转换
  let textEncrypt = ''; //加密文本
  let maxLength = 100; //分段长度
  if(newText.length>maxLength){
    let newArr = newText.match(/.{1,100}/g); //文本分段 数组
    for (let i = 0; i < newArr.length; i++) {
      let encryptStr = encrypt.encrypt(newArr[i]); //分段 加密
      textEncrypt = textEncrypt ? textEncrypt +  $splitStr + encryptStr : encryptStr //拼接 加密字符串
    }
  }else{
    textEncrypt = encrypt.encrypt(newText);// 加密
  }
  // console.log('加密:',textEncrypt)
  return textEncrypt
}
/**
 * [rsaDecryptSet 文本解密]
 * @param  {[type]} content 待解密密文
 * encrypt解密(分段解密) ——> Base64转换 ——> JSON转换
 */
export const rsaDecryptSet = (content) => {
  if (content == undefined) return
  let contentDecrypt = ''
  if(content.includes($splitStr)){
    let newArr = content.split($splitStr) //文本分段 数组
    for (let i = 0; i < newArr.length; i++) {
      let decryptStr = encrypt.decrypt(newArr[i]); //分段 解密
      contentDecrypt += decryptStr //拼接 解密字符串
    }
  }else{
    contentDecrypt = encrypt.decrypt(content);//解密
  }
  let Base64Decrypt = Base64.decode(contentDecrypt); //Base64转换
  let decryptData = null //解密数据
  if (typeof(Base64Decrypt) === 'string') {
    try{
      decryptData = JSON.parse(Base64Decrypt)  // JSON转换
    }catch(error){
      decryptData = Base64Decrypt
    }
  }
  // console.log('解密:',decryptData)
  return decryptData
}

 

 
posted @ 2024-01-23 17:05  柠檬杨  阅读(694)  评论(0编辑  收藏  举报