我以以下格式获取了公共密钥,我需要使用Java来使用此密钥加密某些数据
----- BEGIN RSA公钥-----
MIGJAoGBAKDZp / 3e4w1nJA / ImDMgaGowWfTnhlFkrvS86LBc6wh1 / zBRt51 / 2F / o / ZzaA5mZ
nx5YMlhDOf3vHyzyO4KzYlG8md3RQU7eKQQDxgRfW1v0f7WVQoC2Dxbupyz0JVV4jQStYUYW
ifGsh76wI3rkzlq3F2Ea / + jqMxX / AZOO30tBAgMBAAE =
-----结束RSA公钥-----
最佳答案
您可以使用BouncyCastle
库来实现此目的。您的密钥为PEM格式。要阅读它,您可以使用PEMParser
:
private static PublicKey readPublicKey(String path) throws InvalidKeySpecException, NoSuchAlgorithmException, IOException {
PEMParser pemParser = new PEMParser(new FileReader(path));
Object object = pemParser.readObject();
SubjectPublicKeyInfo subjectPublicKeyInfo = (SubjectPublicKeyInfo) object;
RSAKeyParameters rsa = (RSAKeyParameters) PublicKeyFactory.createKey(subjectPublicKeyInfo);
RSAPublicKeySpec rsaSpec = new RSAPublicKeySpec(rsa.getModulus(), rsa.getExponent());
KeyFactory kf = KeyFactory.getInstance("RSA", new BouncyCastleProvider());
return kf.generatePublic(rsaSpec);
}
然后使用此密钥进行加密:
PublicKey publicKey = readPublicKey("src/main/resources/key.pem");
String dataToEncrypt = "myMessage";
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", new BouncyCastleProvider());
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encrypted = cipher.doFinal(dataToEncrypt.getBytes(StandardCharsets.UTF_8));
经过以下版本测试:
bcpkix-jdk15on
和bcprov-jdk15on
。