JSEncrypt 是一个用于在客户端进行加密的 JavaScript 库。它基于 RSA 加密算法,可以用于在浏览器中对数据进行加密和解密操作。
以下是使用 JSEncrypt 进行加密和解密的基本示例:
第一步:安装 JSEncrypt
首先,你需要引入 JSEncrypt 库。你可以在项目中添加 JSEncrypt 的脚本文件,或者使用 CDN:
<!-- 使用 CDN 引入 JSEncrypt 脚本 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jsencrypt/3.0.0/jsencrypt.min.js"></script>
or(或者)
npm install jsencrypt
第二步:枚举公/私钥
@src/config/map/index.js
// 设置公钥、私钥(通常从服务器获取,这里仅为示例)
const publicKey = 'MIGfMA0GCSqGSIb3DQEBCBiQKBgQCOvCfR4vqp1Nknj4PA3jZm9+Hq8tiH5tubX3UjKx5b71r+jRaSgLGd0ZA3ZK380EAXB99su0p62jfiAX7anOXRrBGqeXEhVCpNCRsUw/JwvjyEJ284FVXicNJNVVORnj+bOJx6Ue3iXFlkbQWocR8LXvjXFzftQIDAQAB';
const privateKey = 'MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAI68J9Hi+qlsbJxnLClhNfVzU2SePg8DeNmb34ery2Ifm25tfdSMrHlvvWv6NFpKAsZ3RkDdkrfzQQBcH32y7SnraN+IBftqc5dGsEap5cSFUKk0JGxTD8nC+PIQnbzgVVeJw0k1VU5GeP5s4+NcXN+1AgMBAAECgYBpz3PZdOELDbRqMVWci1Lb1RBRtsLfqGEGpCVKU+Lpxx+PlVWWP88gMUOFob+REyX+zcx8Chwy9o6mBXDvcaVbo8oLDnumqxTMQ7uRGIl92Nt5OvtVp/hImxBQgEdEw0PQ6jKUjTaoP3t9Z0iJVZGaRsGdQJBAP5Iz9iJ+sxCRFFknr075wk84N/3G7lD5NmX3y+ZN8XhyCfoCXhRgB9xELdqAjFWDx8CQQCPsq5CXe6WhEHAAr6MvG1W2YtIAfFFqaVbvbgy8SuTYAJYWSz+NTwDSQcQFcKGoUXsrtNZqaqM/uqv0HJB1HqrAkEA9yIwztUaKWtID0Assq+V+BqWmIt2vQnSeACAvo2Pd0zxiPoSubYgntGZmhshN3K+IvrC6WrcSLKMepXO18A6JQJAAYoKb8+NxLL5+VKOM/e4vBtscIME0Jg2mzr3BCStMNDwdX3PC5IKaIaZusRg5wxHMXfV77nvh78bSHLVJnteLQJBAN55a/qiELgCMN6ZOne6FageR5B3gMaVDNJsCOcBwJpFRcW8cxssv4TNUfqfn1VwBeqtO9zVDVLNZ+OxFJme3u4=';
export {
publicKey,
privateKey
};
第三步:封装加密解密方法
@src/config/utils/index.js
import { JSEncrypt } from 'jsencrypt';
import { publicKey, privateKey } from '@map/index.js';
// 加密
function encryptText(text) {
const instance = new JSEncrypt();
instance.setPublicKey(publicKey);
return instance.encrypt(text);
}
// 解密
function decryptText(text) {
const instance = new JSEncrypt();
instance.setPrivateKey(privateKey);
return instance.decrypt(text);
}
export {
encryptText,
decryptText,
}
第四步:组件中使用
<script setup>
import { ref } from 'vue';
import { encryptText, decryptText } from '@utils';
const loginForm = ref({});
const submit = () => {
let { password, username } = loginForm.value || {}
let resLoginInfo
resLoginInfo['password'] = encryptText(password)
resLoginInfo['username'] = encryptText(username)
/*
{
password:'O+dmiGTQLhvvIGPHZewL431msOIQvmt7M0L4jC9MyOEKRPvX5BNR8TWqPSb0dJoc=',
username:'WURTJuEE9S+v4gbEcQWH9VC14k7M0L4jC9MyOEKRPvX5BNR8TWnS5H7ycV8fMYng='
}
*/
}
</script>