公钥(publicKey)加密、私钥(privateKey)解密。不能逆向,私钥(privateKey)加密、公钥(publicKey)解密。说白了就是前后端都需要用公钥(publicKey)进行加密,用私钥(privateKey)进行解密。
引入前端 JS 库:jsencrypt.js
npm install jsencrypt
后端生成RSAUtil工具类
public class RSAUtil {
static {
Security.addProvider(new BouncyCastleProvider());
}
/**
* 随机生成密钥对
*
* @param filePath 密钥对要存储的路径
*/
public static void genKeyPair(String filePath) {
// KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
KeyPairGenerator keyPairGen = null;
try {
keyPairGen = KeyPairGenerator.getInstance("RSA");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 初始化密钥对生成器,密钥大小为96-1024位
keyPairGen.initialize(1024, new SecureRandom());
// 生成一个密钥对,保存在keyPair中
KeyPair keyPair = keyPairGen.generateKeyPair();
// 得到私钥
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
// 得到公钥
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
try {
// 得到公钥字符串
String publicKeyString = Base64.getEncoder().encodeToString(publicKey.getEncoded());
// 得到私钥字符串
String privateKeyString = Base64.getEncoder().encodeToString(privateKey.getEncoded());
// 将密钥对写入到文件
FileWriter pubfw = new FileWriter(filePath + "/publicKey.key");
FileWriter prifw = new FileWriter(filePath + "/privateKey.key");
BufferedWriter pubbw = new BufferedWriter(pubfw);
BufferedWriter pribw = new BufferedWriter(prifw);
pubbw.write(publicKeyString);
pribw.write(privateKeyString);
pubbw.flush();
pubbw.close();
pubfw.close();
pribw.flush();
pribw.close();
prifw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 去除密钥的多余信息
*
* @param key 公钥或私钥字符串
* @return Base64的密钥 base 64 key
*/
public static String getBase64Key(String key) {
key = key.replaceAll("-----BEGIN (.*)-----", "");
key = key.replaceAll("-----END (.*)----", "");
key = key.replaceAll("\r\n", "");
key = key.replaceAll("\n", "");
return key;
}
/**
* 从文件中加载密钥
*
* @param fileName 公钥或私钥的文件名
* @return 字符串形式的密钥 ,去除-----BEGIN (.*)-----等多余信息
*/
public static String loadKeyFromFile(String fileName) {
byte[] keyBytes = loadRawKeyFromFile(fileName);
// convert to der format
return getBase64Key(new String(keyBytes));
}
/**
* 从文件中加载密钥
*
* @param fileName 公钥或私钥的文件名
* @return 字符串形式的密钥 byte [ ]
*/
public static byte[] loadRawKeyFromFile(String fileName) {
InputStream resourceAsStream = RSAUtil.class.getClassLoader().getResourceAsStream(fileName);
DataInputStream dis = new DataInputStream(resourceAsStream);
byte[] keyBytes = null;
try {
keyBytes = new byte[resourceAsStream.available()];
dis.readFully(keyBytes);
dis.close();
} catch (IOException e) {
throw new SystemException("Failed to load public key from file '" + fileName + "'", e);
}
return keyBytes;
}
/**
* Load private key by str rsa private key.
* 加载秘钥
* @param privateKeyStr the private key str
* @return the rsa private key
*/
public static RSAPrivateKey loadPrivateKeyByStr(String privateKeyStr) {
try {
byte[] buffer = Base64.getDecoder().decode(privateKeyStr);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC"); // KeyFactory.getInstance("RSA");
return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
} catch (NoSuchAlgorithmException e) {
throw new SystemException("无此算法", e);
} catch (InvalidKeySpecException e) {
throw new SystemException("私钥非法", e);
} catch (NullPointerException e) {
throw new SystemException("私钥数据为空", e);
} catch (NoSuchProviderException e) {
throw new SystemException("no such provider: RSA, BC", e);
}
}
/**
* 公钥加密过程
*
* @param publicKey 公钥
* @param plainTextData 明文数据
* @return 密文 byte [ ]
*/
public static byte[] encrypt(RSAPublicKey publicKey, byte[] plainTextData) {
if (publicKey == null) {
throw new SystemException("加密公钥为空");
}
Cipher cipher = null;
try {
// 使用默认RSA
cipher = Cipher.getInstance("RSA");
// cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] output = cipher.doFinal(plainTextData);
return output;
} catch (NoSuchAlgorithmException e) {
throw new SystemException("无此加密算法", e);
} catch (NoSuchPaddingException e) {
throw new SystemException("无此加密算法", e);
} catch (InvalidKeyException e) {
throw new SystemException("加密公钥非法,请检查", e);
} catch (IllegalBlockSizeException e) {
throw new SystemException("明文长度非法", e);
} catch (BadPaddingException e) {
throw new SystemException("明文数据已损坏", e);
}
}
/**
* 私钥加密过程
*
* @param privateKey 私钥
* @param plainTextData 明文数据
* @return 密文 byte [ ]
* @throws Exception 加密过程中的异常信息
*/
public static byte[] encrypt(RSAPrivateKey privateKey, byte[] plainTextData) throws Exception {
if (privateKey == null) {
throw new SystemException("加密私钥为空");
}
Cipher cipher = null;
try {
// 使用默认RSA
cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");// Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] output = cipher.doFinal(plainTextData);
return output;
} catch (NoSuchAlgorithmException e) {
throw new SystemException("无此加密算法", e);
} catch (NoSuchPaddingException e) {
throw new SystemException("系统中无此填充机制", e);
} catch (InvalidKeyException e) {
throw new SystemException("加密私钥非法,请检查", e);
} catch (IllegalBlockSizeException e) {
throw new SystemException("明文长度非法", e);
} catch (BadPaddingException e) {
throw new SystemException("明文数据已损坏", e);
}
}
/**
* 私钥解密过程
*
* @param privateKey 私钥
* @param cipherData 密文数据
* @return 明文 byte [ ]
*/
public static byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData) {
if (privateKey == null) {
throw new SystemException("解密私钥为空");
}
Cipher cipher = null;
try {
// 使用默认RSA
cipher = Cipher.getInstance("RSA");
// cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] output = cipher.doFinal(cipherData);
return output;
} catch (NoSuchAlgorithmException e) {
throw new SystemException("无此解密算法", e);
} catch (NoSuchPaddingException e) {
throw new SystemException("系统中无此填充机制", e);
} catch (InvalidKeyException e) {
throw new SystemException("解密私钥非法", e);
} catch (IllegalBlockSizeException e) {
throw new SystemException("密文长度非法");
} catch (BadPaddingException e) {
throw new SystemException("密文数据已损坏", e);
}
}
/**
* 公钥解密过程
*
* @param publicKey 公钥
* @param cipherData 密文数据
* @return 明文 byte [ ]
* @throws Exception 解密过程中的异常信息
*/
public static byte[] decrypt(RSAPublicKey publicKey, byte[] cipherData) throws Exception {
if (publicKey == null) {
throw new SystemException("解密公钥为空");
}
Cipher cipher = null;
try {
// 使用默认RSA
cipher = Cipher.getInstance("RSA");
// cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
cipher.init(Cipher.DECRYPT_MODE, publicKey);
byte[] output = cipher.doFinal(cipherData);
return output;
} catch (NoSuchAlgorithmException e) {
throw new SystemException("无此解密算法", e);
} catch (NoSuchPaddingException e) {
throw new SystemException("系统中无此填充机制", e);
} catch (InvalidKeyException e) {
throw new SystemException("解密公钥非法", e);
} catch (IllegalBlockSizeException e) {
throw new SystemException("密文长度非法");
} catch (BadPaddingException e) {
throw new SystemException("密文数据已损坏");
}
}
前端加密
const JSEncrypt = window.JSEncrypt;
export function rsa(str) {
const jse = new JSEncrypt();
const { publicKey } = xxx;//从后端接口获取publicKey
jse.setPublicKey(publicKey);
return jse.encrypt(str)
}
export default function(str) {
return rsa(str)
}
export const decrypt = async str => {
return new Promise((resolve, reject) => {
后端解密接口(str)
.then(res => {
if (res.data.code === "success") {
resolve(res.data.data);
} else {
reject(res);
}
})
.catch(err => {
reject(err)
});
})
}
后端解密接口
//eg: 后端获取publicKey接口
@GetMapping("getRsaPublicKey")
public ResultResp getRsaPublicKey() {
String key = RSAUtil.loadKeyFromFile("rsaPublicKey.key");
return success(key);
}
//eg:后端解密接口
@GetMapping("getDecryptRsaPwd")
public Result
使用
import encrypt, { decrypt } from '@/utils/xxx;//引入上面写的前端前端文件
//加密密码
data.password = encrypt(data.password);
//解密
decrypt(this.password).then(clearText => {
this.model.password = clearText
})