一般在做系统时候对安全性要求比较高,现在通常选择https协议来进行数据传输。很多情况下一般的javaweb网站,如果安全要求不是很高的话,用https协议就可以了。在这种情况下,密码的明文传输显然是不合适的,因为请求如果在传输过程中被截了,就可以直接拿明文密码登录网站了。 为了传输数据的安全、今天就采用RSA加密方式来进行加密。
实现方式思路:
编写加解密公共方法类--公钥方法--前端在向后台发起登录请求之前,先请求后台获取公钥的方法,然后经过加密之后再发起登录请求--前端代码需引入jsencrypt.min.js文件--后端接收前端传输过来的密文进行解密--完成登录
完整代码实现:
后端首先引入加密jar包
<!--需要导入的依赖jar--><!-- https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk16 --><dependency><groupId>org.bouncycastle</groupId><artifactId>bcprov-jdk16</artifactId><version>1.46</version></dependency>
编写RSA加密工具类:
package com.railway.common.utils;
/*** Created by Administrator on 2022/2/8 0008.*/import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPublicKey;public class RSAUtil{private static final KeyPair keyPair = initKey();private static KeyPair initKey() {try {Provider provider =new BouncyCastleProvider();Security.addProvider(provider);SecureRandom random = new SecureRandom();KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", provider);generator.initialize(1024,random);return generator.generateKeyPair();} catch(Exception e) {throw new RuntimeException(e);}}private static byte[] decrypt(byte[] byteArray) {try {Provider provider = new org.bouncycastle.jce.provider.BouncyCastleProvider();Security.addProvider(provider);Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", provider);PrivateKey privateKey = keyPair.getPrivate();cipher.init(Cipher.DECRYPT_MODE, privateKey);byte[] plainText = cipher.doFinal(byteArray);return plainText;} catch(Exception e) {throw new RuntimeException(e);}}public static String decryptBase64(String string) {return new String(decrypt(Base64.decodeBase64(string.getBytes())));}public static String generateBase64PublicKey() {PublicKey publicKey = (RSAPublicKey)keyPair.getPublic();return new String(Base64.encodeBase64(publicKey.getEncoded()));}}
编写前端需要调用后端生成公钥方法接口:
// 后端登录生成公钥方法@RequestMapping(value = "/getPublicKey", method = RequestMethod.GET)public R RSAKey(){String publicKey = RSAUtil.generateBase64PublicKey();return R.ok().put("publicKey",publicKey);}
前端向后台发送登录请求前,先向后台请求获取公钥,加密后再发起登录请求。
需要提前引入 jsencrypt.min.js文件或npm安装就行
// 获取公钥
export function encryption(username, password) {return new Promise((resolve, reject) => {PublicKey().then((res) => {console.log(res);let encrypt = new JSEncrypt(); //创建加密实例let PublicKey = res.publicKey;encrypt.setPublicKey(PublicKey);username = encrypt.encrypt(username);password = encrypt.encrypt(password);resolve({username: username,password: password})})})
}
后端登录接收并解密:
后端登录接口实现:
/*** 登录*/@RequestMapping(value = "/sys/login",method = {RequestMethod.GET,RequestMethod.POST})public Map<String, Object> login(@RequestParam String username, @RequestParam String password)throws IOException {username=username.replaceAll(" ", "+");password=password.replaceAll(" ", "+");username = RSAUtil.decryptBase64(username.trim());password = RSAUtil.decryptBase64(password.trim());System.out.println(username+password);SysUserEntity user = sysUserService.queryByUserName(username);//账号不存在、密码错误if(user == null || !user.getPassword().equals(new Sha256Hash(password, user.getSalt()).toHex())) {return R.error("账号或密码不正确");}//账号锁定if(user.getStatus() == 0){return R.error("账号已被锁定,请联系管理员");}//生成token,并保存到数据库R r = sysUserTokenService.createToken(user.getUserId());r.put("user",user);return r;}
源码获取:
大家点赞、收藏、关注、评论啦 、查看👇🏻👇🏻👇🏻微信公众号获取联系方式👇🏻👇🏻👇🏻
打卡 文章 更新 192/ 365天
精彩专栏推荐订阅:在下方专栏👇🏻👇🏻👇🏻👇🏻
Java项目精品实战案例《100套》
web前端期末大作业网页实战《100套》