使用RSA实现前端公钥加密后端私钥解密

听说你还不会RSA算法实现前端加密后端解密???那就来看这里…

RSA前端加密后端解密避免出现明文密码传递 话不多说,直接开撸

前端JS
  • 项目中先添加rsa.js文件
    链接:https://pan.baidu.com/s/1r9930MkS4n8TR9IsOIXV-Q
    提取码:hd52
  • 添加完成之后在项目中引入rsa.js
<script src="js/rsa.js"></script> <!--根据自己的文件路径添加即可-->
  • 使用Vue,element ui实现
var encrypt = new JSEncrypt();
$.ajax({
    type: 'post',
     url: 'log/publicKey',
     data: '',
     dataType: 'json',
     success: function (data) {
         encrypt.setPublicKey(data.public_key)
         _this.password = encrypt.encrypt(_this.password)
         $.ajax({
             type: 'post',
             url: 'log/login',
             data: {
                 username: _this.username,
                 password: _this.password
             },
             dataType: 'json',
             success: function (data) {
                 if (data.code == 200) {
                 <!--成功之后的操作...-->
                 } else {
                     <!--失败操作-->
                 }
             }
         })
     }
 })
后端代码
  • Controller层
/**
 * 获取公钥
 */
@ResponseBody
 @PostMapping("publicKey")
 public Map<String, Object> public_key() {
     Map<String, Object> map = new HashMap<>();
     map.put("public_key", KeyManager.getPublic_key());
     return map;
 }
/**
  * 登录
  *
  * @param username 用户名
  * @param password 加密后的密码
  * @param session
  * @return
  * @throws Exception
  */
 @PostMapping("login")
 @ResponseBody
 public R login(String username, String password, HttpSession session, HttpServletRequest request) throws Exception {
     String pwd = MD5_u.md5s_32(adminUserService.encryptionResult(password));
     // 判断用户密码错误次数是否过多
     if (FrequencyUtil.checkFrequency(username, 5)) {
         logger.info("密码错误次数过多,当前管理员为:{}", username);
         return R.ok().put("msg", "登录错误次数过多");
     }
     String ip = IpUtil.getRemoteIp(request);
     // 判断同一ip错误次数是否过多
     if (FrequencyUtil.checkFrequency(ip, 10)) {
         logger.info("密码错误次数过多,当前管理员为:{}", username);
         return R.ok().put("msg", "登录错误次数过多");
     }
     AdminUser byUsernameAndPassword = adminUserService.findByUsernameAndPassword(username, pwd);
     if (byUsernameAndPassword == null) {
         logger.info("用户名或密码错误,当前管理员为:{}", username);
         return R.ok().put("msg", "用户名或密码错误");
     } else if (byUsernameAndPassword.getState().equals(0)) {
         return R.ok().put("msg", "账户已被冻结,请联系管理员");

     }
     session.setAttribute("user", byUsernameAndPassword.getUsername());
     logger.info("管理员登录成功.....当前登录的管理员为:{}", username);
     FrequencyUtil.removeFrequency(username);
     FrequencyUtil.removeFrequency(ip);
     return R.ok().put("code", "200");
 }
  • 工具类
public class KeyManager {
    //公钥
    private static String public_key;
    //私钥
    private static String private_key;
    
    public static String getPublic_key() {
        return public_key;
    }
    public static void setPublic_key(String public_key) {
        KeyManager.public_key = public_key;
    }
    public static String getPrivate_key() {
        return private_key;
    }
    public static void setPrivate_key(String private_key) {
        KeyManager.private_key = private_key;
    }
    
}
public class RSAUtil {
	//生成秘钥对
	public static KeyPair getKeyPair() throws Exception {
		KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
		keyPairGenerator.initialize(1024);
		KeyPair keyPair = keyPairGenerator.generateKeyPair();
		return keyPair;
	}

	//获取公钥(Base64编码)
	public static String getPublicKey(KeyPair keyPair){
		PublicKey publicKey = keyPair.getPublic();
		byte[] bytes = publicKey.getEncoded();
		return byte2Base64(bytes);
	}

	//获取私钥(Base64编码)
	public static String getPrivateKey(KeyPair keyPair){
		PrivateKey privateKey = keyPair.getPrivate();
		byte[] bytes = privateKey.getEncoded();
		return byte2Base64(bytes);
	}

	//将Base64编码后的公钥转换成PublicKey对象
	public static PublicKey string2PublicKey(String pubStr) throws Exception{
		byte[] keyBytes = base642Byte(pubStr);
		X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		PublicKey publicKey = keyFactory.generatePublic(keySpec);
		return publicKey;
	}

	//将Base64编码后的私钥转换成PrivateKey对象
	public static PrivateKey string2PrivateKey(String priStr) throws Exception{
		byte[] keyBytes = base642Byte(priStr);
		PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
		return privateKey;
	}

	//公钥加密
	public static byte[] publicEncrypt(byte[] content, PublicKey publicKey) throws Exception{
		Cipher cipher = Cipher.getInstance("RSA");
		cipher.init(Cipher.ENCRYPT_MODE, publicKey);
		byte[] bytes = cipher.doFinal(content);
		return bytes;
	}

	//私钥解密
	public static byte[] privateDecrypt(byte[] content, PrivateKey privateKey) throws Exception{
		Cipher cipher = Cipher.getInstance("RSA");
		cipher.init(Cipher.DECRYPT_MODE, privateKey);
		byte[] bytes = cipher.doFinal(content);
		return bytes;
	}

	//字节数组转Base64编码
	public static String byte2Base64(byte[] bytes){
		BASE64Encoder encoder = new BASE64Encoder();
		return encoder.encode(bytes);
	}

	//Base64编码转字节数组
	public static byte[] base642Byte(String base64Key) throws IOException{
		BASE64Decoder decoder = new BASE64Decoder();
		return decoder.decodeBuffer(base64Key);
	}
}
  • Service层
public interface AdminUserService {
    String encryptionResult(String password) throws Exception;
}
  • impl实现层
/**
  * rsa算法解密
  *
  * @param password
  * @return
  * @throws Exception
  */
 @Override
 public String encryptionResult(String password) throws Exception {
     // 将Base64编码后的私钥转换成PrivateKey对象
     PrivateKey privateKey = RSAUtil.string2PrivateKey(KeyManager.getPrivate_key());
     // 加密后的内容Base64解码
     byte[] base642Byte = RSAUtil.base642Byte(password);
     // 用私钥解密
     byte[] privateDecrypt = RSAUtil.privateDecrypt(base642Byte, privateKey);
     return new String(privateDecrypt);
 }
  • 登录界面
    使用RSA实现前端公钥加密后端私钥解密_第1张图片
  • 前端加密后的密码
    IvY24AmBOh2ihwDL4yalYzB58/EEUw4ELzkp4e6hxZJPdm5XQ3K40DzZlUAcLZ3azXBIz72o8d+8niP0siqHvNIF03Bf9xlW3OeeOm71KfUwO1FcCrQMtLuqecfufalm6EXX4po5o25w04zXoJ5Nbm14p4uPjZ/I4u//PSog+e0=
  • 后端解密后的密码
    Sjfh@123

主:以上所有代码复制即用,详细的登录逻辑需要自己实现…

至此:简单的rsa前端加密后端解密功能就实现了

q:2414701902

如果有什么问题,欢迎大家指导。并相互联系,希望能够通过文章互相学习。

你可能感兴趣的:(springboot,rsa加密,spring,vue.js,前端)