文章目录
- 概要
- Vue前端加密
- 后端进行解密
- 小结
概要
vue界面加密传输,后端获取进行解密,适用于登录时密码加密传输。
Vue前端加密
1.安装jsencrypt包:
npm install jsencrypt
安装完成后package.json会有jsencrypt依赖
2.引入jsencrypt.js到文件夹中:
import JSEncrypt from 'jsencrypt/bin/jsencrypt.min'
// 密钥对生成 http://web.chacuo.net/netrsakeypair
const publicKey = 'MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAMdWxcAuyJTg1bT9AMMaQDZmVbXoQbYuVHz0r+Kl4O3j1/Wa2IpCWDbBarAkZlUHVWsNA1+eBtdJ6mhj49jdwu8CAwEAAQ=='
const privateKey = 'MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAx1bFwC7IlODVtP0AwxpANmZVtehBti5UfPSv4qXg7ePX9ZrYikJYNsFqsCRmVQdVaw0DX54G10nqaGPj2N3C7wIDAQABAkEArwiId6ocwm1x+Yw2wRopzBqrpCEeoiOoWFhaoL9a9EaPxCPus/Mc4/bJh+pT0XlB7fnw1DjkDgpA2QNG0F5AUQIhAPmtAbNP/MkdcFvibn5DgegzVqdMOo22sFw3dVb7/6jAiEAzGNcyGmI3N+p/OYyRe9i+q2XnjnG8if0mMOLpRNAa0UCIn0aO3yUXzfTJyNQaSNIn/UlC8O7yVXfI9b5axdFwuLAiAiqS8Q5aTKIDwJoVghOAmHDW1K7e1pH5GBXpgN9IfWKQIhAK6BZCptpUWBvF9ZfZ3aHCkzQL8gyMDlKOHOvkvhhzO4'
// 加密
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) // 对数据进行解密
}
3.Vue页面引入jsencrypt.js调用加密方法:
后端进行解密
1.pom.xml引入hutool工具包依赖:
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.12</version>
</dependency>
2.引入解密文件:
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
public class PwdUtil {
private static final String privateKeyBase64="MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAx1bFwC7IlODVtP0AwxpANmZVtehBti5UfPSv4qXg7ePX9ZrYikJYNsFqsCRmVQdVaw0DX54G10nqaGPj2N3C7wIDAQABAkEArwiId6ocwm1x+Yw2wRopzBqrpCEeoiOoWFhaoL9a9EaPxCPus/Mc4/bJh+pT0XlB7fnw1DjkDgpA2QNG0F5AUQIhAPmtAbNP/MkdcFvibn5DgegzVqtdMOo22sFw3dVb7/6jAiEAzGNcyGmI3N+p/OYyRe9i+q2XnjnG8if0mMOLpRNAa0UCIAn0aO3yUXzfTJyNQaSNIn/UlC8O7yVXfI9b5axdFwuLAiAiqS8Q5aTKIDwJoVghOAmHDW1K7e1pH5GBXpgN9IfWKQIhAK6BZCptpUWBvF9ZfZ3aHCkzQL8gyMDlKOHOvkvhhzO4";
public static String rsa_decrypt(String ciphertext) {
RSA rsa1 = new RSA(privateKeyBase64, null);
String str = rsa1.decryptStr(ciphertext, KeyType.PrivateKey);
return str;
}
}
3.调用解密文件的解密方法即可:
@PostMapping("/login")
public AjaxResult login(@RequestBody LoginBody loginBody)
{
String user = userService.selectUserRoleGroup(loginBody.getUsername());
if(user.contains("管理员")) {
return AjaxResult.error("管理员请从管理员端口登录!");
}
AjaxResult ajax = AjaxResult.success();
//解密
String password = PwdUtil.rsa_decrypt(loginBody.getPassword());
// 生成令牌
String token = loginService.login(loginBody.getUsername(), password, loginBody.getCode(),
loginBody.getUuid());
ajax.put(Constants.TOKEN, token);
return ajax;
}
小结
提示:公钥加密,私钥解密,密钥对生成 http://web.chacuo.net/netrsakeypair