RSA加密-非对称加密(npm i jsencrypt)
import { JSEncrypt } from 'jsencrypt'
import config from './config.json';// 加密
export function handleEncrypt(txt) {const encryption = new JSEncrypt();console.log(encryption);encryption.setPublicKey(config.publicKey); // 设置公钥return encryption.encrypt(txt); // 对数据进行加密
}// 解密export function handleDecrypt(txt) {const encryption = new JSEncrypt();encryption.setPrivateKey(config.privateKey); // 设置私钥return encryption.decrypt(txt); // 对数据进行解密
}
当RSA加密返回false的时候注意一下--RSA加密的字符串长度是117位--超出就返回false
AES加密-对称加密(npm i crypto-js)
import CryptoJS from 'crypto-js';
import config from './config.json';
// 加密
export function handleEncrypt(plaintText) {const iv = CryptoJS.enc.Utf8.parse(config.ivSeed);const key = CryptoJS.enc.Utf8.parse(config.secretKey);const options: any = {iv, // 偏移量mode: CryptoJS.mode.CBC, // 模式 有五种值--百度看吧padding: CryptoJS.pad.Pkcs7,};const encryptedData = CryptoJS.AES.encrypt(plaintText, key, options);let encryptedBase64Str = encryptedData.toString().replace(/\//g, '_');encryptedBase64Str = encryptedBase64Str.replace(/\+/g, '-');return encryptedBase64Str;
}
//解密
export function handleDecrypt(encryptedBase64Str) {const iv = CryptoJS.enc.Utf8.parse(config.ivSeed);const key = CryptoJS.enc.Utf8.parse(config.secretKey);const values = encryptedBase64Str.replace(/\-/g, '+').replace(/_/g, '/');const options: any = {iv,mode: CryptoJS.mode.CBC,padding: CryptoJS.pad.Pkcs7,};const decryptedData = CryptoJS.AES.decrypt(values, key, options);const decryptedStr = CryptoJS.enc.Utf8.stringify(decryptedData);return decryptedStr;
}