RSA加解密——前端js加密,后台解密
公司最近安全测试,前端要求密码 前端 js 加密 后端 java解密. 并只能做对称加密. 因为是老系统 原有的登陆逻辑不能破坏. 本文抄自 https://blog.csdn.net/danshangu/article/details/81129228 感谢博主的分享.
首先整理下思路:
需求是要将登陆 密码加密传输并每次加密公钥不能相同.
- 登陆操作: 前端输入账号密码后,点击登陆按钮. 登陆前先从后端获取公钥,获取公钥同时将本次登陆请求的公钥和秘钥存入秘钥队列();
- 通过rsa.js 使用公钥给密码加密.
- Post请求登陆
- 后端从秘钥队列中获取公钥和秘钥
- 使用获取到的公钥和秘钥解密
- 将解密后的密码传给原有登陆逻辑走后面的流程
需要用到的素材:
Barrett.js
BigInt.js
RSA.js
可以从链接: rsa-js. 下载
可能需要用到的依赖:
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-ext-jdk14</artifactId>
<version>1.60</version>
</dependency>
代码片段:
RSAUtils.java工具类
package com.utils;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
/**
* rsa工具类
*
* @author naruto
* @version 1.0
* @date 2019-4-8
*/
public class RSAUtils {
public static final String CHARSET = "UTF-8";
public static final String RSA_ALGORITHM = "RSA";
public static Map<String, String> createKeys(int keySize) {
//为RSA算法创建一个KeyPairGenerator对象
KeyPairGenerator kpg;
try {
kpg = KeyPairGenerator.getInstance(RSA_ALGORITHM);
} catch (NoSuchAlgorithmException e) {
throw new IllegalArgumentException("No such algorithm-->[" + RSA_ALGORITHM + "]");
}
//初始化KeyPairGenerator对象,密钥长度
kpg.initialize(keySize);
//生成密匙对
KeyPair keyPair = kpg.generateKeyPair();
//得到公钥
Key publicKey = keyPair.getPublic();
String publicKeyStr = Base64.encodeBase64URLSafeString(publicKey.getEncoded());
//得到私钥
Key privateKey = keyPair.getPrivate();
String privateKeyStr = Base64.encodeBase64URLSafeString(privateKey.getEncoded());
Map<String, String> keyPairMap = new HashMap<String, String>();
keyPairMap.put("publicKey", publicKeyStr);
keyPairMap.put("privateKey", privateKeyStr);
return keyPairMap;
}
/**
* 得到公钥
*
* @param publicKey 密钥字符串(经过base64编码)
* @throws Exception
*/
public static RSAPublicKey getPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
//通过X509编码的Key指令获得公钥对象
KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
RSAPublicKey key = (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);
return key;
}
/**
* 得到私钥
*
* @param privateKey 密钥字符串(经过base64编码)
* @throws Exception
*/
public static RSAPrivateKey getPrivateKey(String privateKey)
throws NoSuchAlgorithmException, InvalidKeySpecException {
//通过PKCS#8编码的Key指令获得私钥对象
KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
RSAPrivateKey key = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec);
return key;
}
/**
* 公钥加密
*
* @param data
* @param publicKey
* @return
*/
public static String publicEncrypt(String data, RSAPublicKey publicKey) {
try {
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] bs = rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET),
publicKey.getModulus().bitLength());
return Base64.encodeBase64URLSafeString(bs);
} catch (Exception e) {
throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
}
}
/**
* 私钥解密
*
* @param data
* @param privateKey
* @return
*/
public static String privateDecrypt(String data, RSAPrivateKey privateKey) {
try {
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] bs = Base64.decodeBase64(data);
return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, bs, privateKey.getModulus().bitLength()),
CHARSET);
} catch (Exception e) {
throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);
}
}
public static String privateDecrypt(byte[] data, RSAPrivateKey privateKey) {
try {
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, data, privateKey.getModulus().bitLength()),
CHARSET);
} catch (Exception e) {
throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);
}
}
/**
* 私钥加密
*
* @param data
* @param privateKey
* @return
*/
public static String privateEncrypt(String data, RSAPrivateKey privateKey) {
try {
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
return Base64.encodeBase64URLSafeString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET),
privateKey.getModulus().bitLength()));
} catch (Exception e) {
throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
}
}
/**
* 公钥解密
*
* @param data
* @param publicKey
* @return
*/
public static String publicDecrypt(String data, RSAPublicKey publicKey) {
try {
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, publicKey);
return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data),
publicKey.getModulus().bitLength()), CHARSET);
} catch (Exception e) {
throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);
}
}
private static byte[] rsaSplitCodec(Cipher cipher, int opmode, byte[] datas, int keySize) {
int maxBlock = 0;
if (opmode == Cipher.DECRYPT_MODE) {
maxBlock = keySize / 8;
} else {
maxBlock = keySize / 8 - 11;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] buff;
int i = 0;
try {
while (datas.length > offSet) {
if (datas.length - offSet > maxBlock) {
buff = cipher.doFinal(datas, offSet, maxBlock);
} else {
buff = cipher.doFinal(datas, offSet, datas.length - offSet);
}
out.write(buff, 0, buff.length);
i++;
offSet = i * maxBlock;
}
} catch (Exception e) {
throw new RuntimeException("加解密阀值为[" + maxBlock + "]的数据时发生异常", e);
}
byte[] resultDatas = out.toByteArray();
IOUtils.closeQuietly(out);
return resultDatas;
}
public static byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.equals("")) {
return null;
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
private static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
/**
* * 解密 *
*
* @param pk 解密的密钥 *
* @param raw 已经加密的数据 *
* @return 解密后的明文 *
* @throws Exception
*/
public static byte[] decrypt(PrivateKey pk, byte[] raw) throws Exception {
try {
Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
cipher.init(cipher.DECRYPT_MODE, pk);
int blockSize = cipher.getBlockSize();
ByteArrayOutputStream bout = new ByteArrayOutputStream(64);
int j = 0;
while (raw.length - j * blockSize > 0) {
bout.write(cipher.doFinal(raw, j * blockSize, blockSize));
j++;
}
return bout.toByteArray();
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}
public static void main(String[] args) throws Exception {
Map<String, String> keyMap = RSAUtils.createKeys(1024);
String publicKey = keyMap.get("publicKey");
String privateKey = keyMap.get("privateKey");
System.out.println("公钥: \n\r" + publicKey);
System.out.println("私钥: \n\r" + privateKey);
System.out.println("公钥加密——私钥解密");
RSAPublicKey rsaPublicKey = RSAUtils.getPublicKey(publicKey);
RSAPrivateKey rsaPrivateKey = RSAUtils.getPrivateKey(privateKey);
System.out.println(rsaPublicKey.getPublicExponent());
String modulus = rsaPublicKey.getModulus().toString();
System.out.println(modulus);
String str = "321";
System.out.println("\r明文:\r\n" + str);
System.out.println("\r明文大小:\r\n" + str.getBytes().length);
String encodedData = RSAUtils.publicEncrypt(str, RSAUtils.getPublicKey(publicKey));
System.out.println("密文:\r\n" + encodedData);
String decodedData = RSAUtils.privateDecrypt(encodedData, RSAUtils.getPrivateKey(privateKey));
System.out.println("解密后文字: \r\n" + decodedData);
}
}
登陆controller 中的代码
/**
* 获取登陆秘钥
* @return
* @throws InvalidKeySpecException
* @throws NoSuchAlgorithmException
*/
@RequestMapping(value = "getkey",method = RequestMethod.POST)
@ResponseBody
public String getkey() throws InvalidKeySpecException, NoSuchAlgorithmException {
Map<String, String> keyMap = RSAUtils.createKeys(1024);
String publicKeyString = keyMap.get("publicKey");
String privateKeyString = keyMap.get("privateKey");
RSAPublicKey rsaPublicKey=RSAUtils.getPublicKey(publicKeyString);
PrivateKey privateKey=RSAUtils.getPrivateKey(privateKeyString);
String Modulus=rsaPublicKey.getModulus().toString(16);
String Exponent=rsaPublicKey.getPublicExponent().toString(16);
//将公钥私钥存入 队列
Subject currentUser = SecurityUtils.getSubject();
Session session = currentUser.getSession();
session.setAttribute(Modulus, privateKey);
return Modulus;
}
解密操作
/**
* 解密password
* @param password
* @param publicKey
* @return
* @throws Exception
*/
private String checkPasRsa(String password,String publicKey) throws Exception {
Subject currentUser = SecurityUtils.getSubject();
Session session = currentUser.getSession();
Object attribute = session.getAttribute(publicKey);
if(attribute ==null || !(attribute instanceof PrivateKey)){
log.error("session中私钥失效.publickey={},password={}",publicKey,password);
return null;
}
session.removeAttribute(publicKey);
PrivateKey privateKey = (PrivateKey) attribute;
byte[] en_result = RSAUtils.hexStringToBytes(password);
byte[] de_result = RSAUtils.decrypt(privateKey, en_result);
StringBuffer sb = new StringBuffer();
sb.append(new String(de_result));
return sb.reverse().toString();
}
Jsp 中 请求片段 – 获取本次登陆公钥
function getPublicKey() {
var publickey = "";
$.ajax({
type: "post",
async: false,
url: '${ctx}/login/getkey?'+new Date(),
dataType: 'text',
success: function (data) {
publickey = data;
}
});
return publickey;
}
Jsp 中 请求片段 – 用获取到的公钥给密码加密
Jsp 中 请求片段 – 用获取到的公钥给密码加密
这里需要引入上面说的三个js了
<script src="${res.url}/static/plugins/security/Barrett.js"></script>
<script src="${res.url}/static/plugins/security/BigInt.js"></script>
<script src="${res.url}/static/plugins/security/RSA.js"></script>
var loginname = $("#loginname").val();
var password = $("#password").val();
setMaxDigits(130);
var publicKey = getPublicKey();
var key = new RSAKeyPair("10001","",publicKey);
password = encryptedString(key, encodeURIComponent(password));
//这里的password就是加密后的结果了.
setMaxDigits(),要注意里面的参数,1024位对应130(RSAUtils.createKeys(1024)),2048位对应260
一个更加值得注意的问题是 秘钥队列: 如果应用服务器有多个的话 不能简单的存在 内存(map),需要存放到session(需要实现session共享)或者redis 队列,并且注意一定要设定一个超时时间.避免无限增量消耗内存