美文网首页
jsencrypt.js 加密解密

jsencrypt.js 加密解密

作者: 你这个锤子 | 来源:发表于2023-12-11 11:23 被阅读0次

jsencrypt.js 插件用于:加解密字符串,公钥加密,私钥解密。

使用例子:
import JSEncrypt from 'jsencrypt/bin/jsencrypt.min'

const publicKey = "" // 公钥
const privateKey= "" // 私钥
// 加密
export function encrypt(txt) {
  const encryptor = new JSEncrypt()
  encryptor.setPublicKey(publicKey) // 设置公钥
  return encryptor.encrypt(txt) // 对数据进行加密
}
// 解密
export function decrypt(txt) {
  const encryptor = new JSEncrypt()
  encryptor.setPrivateKey(privateKey) // 设置私钥
  return encryptor.decrypt(txt) // 对数据进行解密
}
如果加密数据过长,还可以分段解密
import { b64tohex} from "jsencrypt/lib/lib/jsbn/base64";
export const decryptLong = (content:string) => {
  const enc = new JSEncrypt({});
  enc.setPrivateKey(LICENSE_KEY);  // 私钥
  let k = enc.getKey();  
  let maxLength = 128;
  try {
    let hexStr = b64tohex(content);
    if (hexStr.length > maxLength * 2) {
      let hexStrArr = hexStr.match(/.{1,256}/g);  // 128位解密。取256位
      const ct = hexStrArr.map(entry => k.decrypt(entry)).join('');
      return ct;
    } else {
      return k.decrypt(hexStr);
    }
  } catch (ex) {
    return false;
  }
};

源码地址
一个密钥对生成地址

相关文章

网友评论

      本文标题:jsencrypt.js 加密解密

      本文链接:https://www.haomeiwen.com/subject/gzdtirtx.html