从 PKCS1 密钥获取 RSA public 密钥
Getting RSA public key from PKCS1 key
我得到以下格式的 public 密钥,我需要使用 java 使用此密钥加密一些数据
-----BEGIN RSA PUBLIC KEY-----
MIGJAoGBAKDZp/3e4w1nJA/ImDMgaGowWfTnhlFkrvS86LBc6wh1/zBRt51/2F/o/ZzaA5mZ
nx5YMlhDOf3vHyzyO4KzYlG8md3RQU7eKQQDxgRfW1v0f7WVQoC2Dxbupyz0JVV4jQStYUYW
ifGsh76wI3rkzlq3F2Ea/+jqMxX/AZOO30tBAgMBAAE=
-----END RSA PUBLIC KEY-----
您可以使用 BouncyCastle
库来实现此目的。您的密钥在 PEM fromat 中。要阅读它,您可以使用 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
and bcprov-jdk15on
。
我得到以下格式的 public 密钥,我需要使用 java 使用此密钥加密一些数据
-----BEGIN RSA PUBLIC KEY----- MIGJAoGBAKDZp/3e4w1nJA/ImDMgaGowWfTnhlFkrvS86LBc6wh1/zBRt51/2F/o/ZzaA5mZ nx5YMlhDOf3vHyzyO4KzYlG8md3RQU7eKQQDxgRfW1v0f7WVQoC2Dxbupyz0JVV4jQStYUYW ifGsh76wI3rkzlq3F2Ea/+jqMxX/AZOO30tBAgMBAAE= -----END RSA PUBLIC KEY-----
您可以使用 BouncyCastle
库来实现此目的。您的密钥在 PEM fromat 中。要阅读它,您可以使用 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
and bcprov-jdk15on
。