博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
前后端分离密码登陆加密RSA方案(java后端)
阅读量:6607 次
发布时间:2019-06-24

本文共 4255 字,大约阅读时间需要 14 分钟。

前言:密码加密有很多种方案,这里不做过多讨论,本篇文章是基于RSA加密实现。

首先在前端工程中需要引入加密js: "jsencrypt": "2.3.1",(注意单独导入可能报错,可以删除整个node_modules,然后重新npm install)

然后在登陆提交表单的地方代码修改如下:

// 引入jsimport {JSEncrypt} from 'jsencrypt' // 提交表单方法      dataFormSubmit () {        this.dataForm.password = this.passwordEncryption(this.dataForm.password + ',' + new Date().getTime())      this.$http({              url: this.$http.adornUrl('/sys/login'),              method: 'post',              data: this.$http.adornData({                'username': this.dataForm.userName,                'password': this.dataForm.password,                'uuid': this.dataForm.uuid,                'captcha': this.dataForm.captcha              })      },  //密码加密方法  passwordEncryption (passwordUser) {    console.log(this.rsaKey + ' ********后台获取公钥********** ')    let publicKey = this.rsaKey // 从后台获取公钥    let encryptor = new JSEncrypt()  // 新建JSEncrypt对象    encryptor.setPublicKey(publicKey)  // 设置公钥    let passwordEncryp = encryptor.encrypt(passwordUser)  // 对密码进行加密   console.log(passwordEncryp + ' ****************** ')    return passwordEncryp  },// 获取公钥的方法getRsaKey () {  this.$http({    url: this.$http.adornUrl('/sys/login/rsaKey'),    method: 'get'  }).then(({data}) => {    this.rsaKey = data  })}

  

 后端工程代码如下

 

 
//controller 密码加密后用密钥解密form.setPassword(AccountSecurityUtils.decrypt(form.getPassword())); //AccountSecurityUtils 工具类
public static final String PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCsD1gI70BxYujhNw8NpaVKRXkcRofoeUbN9Dj5m3i3h9XAIS6LkjI01L4ieRpTHnMEzoXUY8a2/svDf//xuHuDJlZBNtCXK4DPx5x4zHdUWDjFGpWlMQzhsqQlfs0tkN5gP095g27L0ki/NrRuBpgxP1q2dHKpL37sBF8XNRpedwIDAQAB"; private static final String PRIVATE_KEY = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKwPWAjvQHFi6OE3Dw2lpUpFeRxGh+h5Rs30OPmbeLeH1cAhLouSMjTUviJ5GlMecwTOhdRjxrb+y8N///G4e4MmVkE20JcrgM/HnHjMd1RYOMUalaUxDOGypCV+zS2Q3mA/T3mDbsvSSL82tG4GmDE/WrZ0cqkvfuwEXxc1Gl53AgMBAAECgYEAogyhgWi0bRYW92Z/yv6julvMQRE8l3sBcJ//uTbwbwqECrw1tkYu+wsTOCyO2pHnCjPoX6zJTziSeMJpMCPsToCm3+EO38Ki/12RSJ51DgSl7C4R8leoFMZAmExQO4L1rVae2dJS80dvfpLeNiquJw4y7xjXIBUYbQfu+mNKHoECQQDic2F3UMm05M1d/POQHqsuMohoDhwVM0N8/SdbA4fpYFFOahMWdmuFclYbkgTwfYBdGMH/UHLsCGWVv8z48jKHAkEAwoMID93DzTsZWqxAoyGDg7GGdNsMPvYErRxwcOVNpdQXv8F7IAXOslLTvJF542dplCCNzLgyupwxMPlMLuZAkQJANpcoHPJt3dz2oTzUnp62F6n49lTIclfsYhpJPYipYBpnH2c0+MpNe1sn5Peblzo6ErdgNSN4wOv5SVN2n2ELywJAGjyiccFwD9bQ7LIfZeG3Y6QmhsylMjjtGIylfhTwDFY3fd4TRZaC8vrJJL5aupnQW/KoLd0KurEm0XxPEmRsgQJARKNghvpoce39bD/BbC2AojY5Ea6afLzW+GllxHGNGkgGu+x3c4PIUDAt8f60021WoENtonEQpEjzbIU5XpefJA=="; /**  * 加密数据和秘钥的编码方式  */ public static final String UTF_8 = "UTF-8"; public static final String RSA_ALGORITHM_NO_PADDING = "RSA";
public static String decrypt(String password) {
try {
String getPass = decryptRSADefault(PRIVATE_KEY, password); String longtime = StringUtils.substringAfterLast(getPass, ","); if ((System.currentTimeMillis() - Long.valueOf(longtime) > 30 * 60 * 1000)) {
        //抛出自定义异常 throw new MYException("密码超时"); } return StringUtils.substringBeforeLast(getPass, ","); } catch (Exception e) {
if (e instanceof MYException) {
throw new MYException(e.getMessage()); } log.error("password is :" + password + " 密码解密异常:" + e.getMessage()); } return null; }
public static String decryptRSADefault(String privateKeyStr, String data) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM_NO_PADDING); byte[] privateKeyArray = privateKeyStr.getBytes(); byte[] dataArray = data.getBytes(); PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKeyArray)); PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec); Cipher cipher = Cipher.getInstance(RSA_ALGORITHM_NO_PADDING); cipher.init(Cipher.DECRYPT_MODE, privateKey); return new String(cipher.doFinal(Base64.decodeBase64(dataArray)), UTF_8); }
 

相关代码参考博客:https://blog.csdn.net/qq_37346607/article/details/85237368

转载于:https://www.cnblogs.com/liran123/p/10578239.html

你可能感兴趣的文章
数据结构Java实现05----栈:顺序栈和链式堆栈
查看>>
Codeforces Round #319 (Div. 1) C. Points on Plane 分块
查看>>
Redis源代码分析(二十七)--- rio制I/O包裹
查看>>
STM32电源管理
查看>>
Android音频输入通道的底层硬件和软件开发分析
查看>>
php中利用array_filter过滤数组为空值
查看>>
Linux1:Linux概述
查看>>
Promise 学习笔记 - 时间支配者
查看>>
Lintcode: Sqrt(X)
查看>>
Jmeter 新手
查看>>
iOS之UI--关于modal
查看>>
各种U启网启什么的都是浮云
查看>>
请问JDBC中IN语句怎么构建
查看>>
2015第52周六
查看>>
UIScrollView设置了contentSize后还是没办法滚动?
查看>>
POJ 1205 Water Treatment Plants(递推)
查看>>
国内外DNS服务器地址列表
查看>>
买电脑之受骗经历--与诸位共享,愿诸位多一个心眼
查看>>
Lind.DDD.Authorization用户授权介绍
查看>>
counting objects in class
查看>>