前端公钥加密
1、引入jsencrypt.min.js
2、公钥我这边是从后端传给前端的,用一个input放着,按下面的方式就可以获得加密后的密码
var encrypt=new JSEncrypt(); encrypt.setPublicKey($("#publicKey").val()); var password=encrypt.encrypt($("#password").val());
后端私钥解密
1、建一个RSAUtils类
public class RSAUtils {
/** *//** * RSA最大解密密文大小 */ private static final int MAX_DECRYPT_BLOCK = 128;
/** *//** * <P> * 私钥解密 * </p> * * @param encryptedData 已加密数据 * @param privateKey 私钥(BASE64编码) * @return * @throws Exception */ public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey) throws Exception { byte[] keyBytes = Base64Utils.decode(privateKey); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key privateK = keyFactory.generatePrivate(pkcs8KeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, privateK); int inputLen = encryptedData.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; // 对数据分段解密 while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_DECRYPT_BLOCK) { cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK); } else { cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_DECRYPT_BLOCK; } byte[] decryptedData = out.toByteArray(); out.close(); return decryptedData; }
}
2、
public class Base64Utils {
/** *//** * <p> * BASE64字符串解码为二进制数据 * </p> * * @param base64 * @return * @throws Exception */ public static byte[] decode(String base64) throws Exception { return Base64.decodeBase64(base64.getBytes()); }
}
3、调用 (privateKey私密密钥,可从文件里获取)
byte[] decryptByPrivateKey = RSAUtils.decryptByPrivateKey(Base64Utils.decode(password), privateKey); //解密后的密码 String password = new String(decryptByPrivateKey);