前端公鑰加密
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);