1、安装组件
npm install jsencrypt --dev
2、创建加密解密的方法文件
3、文件内容
import JSEncrypt from 'jsencrypt'
//去密钥生成网址去生成公钥和密钥 http://tools.jb51.net/password/rsa_encode
const publicKey = '生成的公钥'
// 前端不建议存放私钥 不建议解密数据 因为都是透明的意义不大
const privateKey ='生成的密钥'
/**
* 最长加密长度
*/
const MAX_ENCRYPT_BLOCK = 117
/**
* 最长解码长度
*/
const MAX_DECRYPT_BLOCK = 128
/**
* @description RSA加密(支持长字符加密)
*/
export async function encryptedData (data:any) {
//创建实例
const encrypt = new JSEncrypt()
// 设置公钥
encrypt.setPublicKey(
`-----BEGIN PUBLIC KEY-----${publicKey}-----END PUBLIC KEY-----`
)
let bufTmp = ''
let hexTmp:any = ''
let result = ''
const buffer = JSON.stringify(data)
let offSet = 0
const inputLen = buffer.length
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
bufTmp = buffer.slice(offSet, offSet + MAX_ENCRYPT_BLOCK)
} else {
bufTmp = buffer.slice(offSet, inputLen)
}
//对数据进行加密
hexTmp = encrypt.encrypt(bufTmp.toString())
result += hexTmp
offSet += MAX_ENCRYPT_BLOCK
}
//js可以使用Buffer.from() ts中使用Buffer.from(),运行后控制台会报错Buffer undefined所以使用替代方案node方法btoa再次加密
return btoa(result)
}
/**
* @description RSA解密(支持长字符解密)
* @param data
* @returns {PromiseLike<ArrayBuffer>}
*/
export function decryptedData (data) {
const decrypt = new JSEncrypt()
//设置私钥
decrypt.setPrivateKey(
`-----BEGIN RSA PRIVATE KEY-----${privateKey}-----END RSA PRIVATE KEY-----`
)
let bufTmp = ''
let hexTmp:any = ''
let result = ''
//通过使用atob解码数据 如果使用的Buffer.from()使用Buffer.from()解码数据
const buffer = atob(data)
let offSet = 0
const inputLen = buffer.length
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
bufTmp = buffer.slice(offSet, offSet + MAX_DECRYPT_BLOCK)
} else {
bufTmp = buffer.slice(offSet, inputLen)
}
//对数据解码
hexTmp = decrypt.decrypt(bufTmp)
result += hexTmp
offSet += MAX_DECRYPT_BLOCK
}
return JSON.parse(result)
}
// huozhe
// 加密
export const encrypt = (txt: string) => {
const encryptor = new JSEncrypt();
encryptor.setPublicKey(publicKey); // 设置公钥
return encryptor.encrypt(txt); // 对数据进行加密
};
// 解密
export const decrypt = (txt: string) => {
const encryptor = new JSEncrypt();
encryptor.setPrivateKey(privateKey); // 设置私钥
return encryptor.decrypt(txt); // 对数据进行解密
};
标签:加密,MAX,解密,前端开发,let,offSet,const,jsencrypt,BLOCK
From: https://www.cnblogs.com/baozhengrui/p/18527920