前言:前端对用户输入的密码明文传输给后端是不安全的行为,所以要将明文密码转成密文。而相比md5、对称加密、base64来说,用 RSA 非对称加密是较安全的方式。
下面便是代码实现,拿来即用。
1.生成一对公私钥
public static void main(String[] args) {
KeyPairGenerator keyPairGenerator = null;
try {
keyPairGenerator = KeyPairGenerator.getInstance("RSA");
} catch (Exception e) {
}
// 初始化密钥对生成器
keyPairGenerator.initialize(1024, new SecureRandom());
// 生成一个密钥对,保存在keyPair中
KeyPair keyPair = keyPairGenerator.generateKeyPair();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
// 得到公钥字符串
String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
// 得到私钥字符串
String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));
System.out.println("publickey:" + publicKeyString);
System.out.println("privateKey:" + privateKeyString);
}
2.前端使用jsencrypt.js对数据进行公钥加密传输
// 1.安装jsencrypt
npm install jsencrypt --dep
// 2.使用
var encrypt = new JSEncrypt();
// 设置公钥
encrypt.setPublicKey(publicKey);
// 对明文密码进行加密
var data = encrypt.encrypt(password);
3.后端加解密
后端调用decrypt方法用私钥对秘文进行解密即可
public static String encrypt(String str, String publicKey) throws Exception {
//base64编码的公钥
byte[] decoded = Base64.decodeBase64(publicKey);
RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
//RSA加密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
return outStr;
}
public static String decrypt(String str, String privateKey) {
try {
// base64位解码加密后的字符串
byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
//base64编码的私钥
byte[] decoded = Base64.decodeBase64(privateKey);
RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
//RSA解密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, priKey);
String outStr = new String(cipher.doFinal(inputByte));
return outStr;
}catch (Exception e){
}
}