I have the following string, which I understand to be an RSA public key:
JavaScript
x
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAi+VPTFioJ3Dv/D6aEMqkiESiRkKBnISe3+K7vJDMAMqkTCfGz0jKInS5BXQUW9jRqkgBpSKdwizIWhCBOT3wGmgnm+L3bVwtTML52drqePSmQgfHAiWfcLdZuFGULtpy5nhaOAR5nzuDmDR8L0vumNbhqK+o9jbwSTbm8cfUsf7xHc7RX+bJinu5s566NtxqJ0y8U764BVPg96QLKpOEiNJUELarkdnljjdb12Gvs+631YFKAnUt5V9oHowBS1JDerlbhHKH6kYKEuVZfm5ofvhGQiUU69i9q/hO5Pb0eIZsogazERJmEIIvre8sQLNE71ti0WD3i7QDGlnsoai6EwIDAQAB
I need to construct a java.security.interfaces.RSAPublicKey
from this string. First I tried calling RSAPublicKeyImpl.newKey(myString.getBytes(StandardCharsets.UTF_8))
, but that threw the following exception:
JavaScript
java.security.InvalidKeyException: invalid key format
"sun.security.x509.X509Key.decode(X509Key.java:387)"
"sun.security.x509.X509Key.decode(X509Key.java:402)"
"sun.security.rsa.RSAPublicKeyImpl.<init>(RSAPublicKeyImpl.java:122)"
"sun.security.rsa.RSAPublicKeyImpl.newKey(RSAPublicKeyImpl.java:72)"
"com.myApp.getPublicKeyRsa(KeyLoader.java:33)"
Then, following an online guide, I tried this code instead:
JavaScript
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(myString.getBytes(StandardCharsets.UTF_8));
keyFactory.generatePublic(pubSpec);
That threw a very similar exception, just wrapped in another one.
Am I missing something obvious here? How do I construct a RSAPublicKey
?
Advertisement
Answer
this method can help you
JavaScript
public static PublicKey stringToPublicKey(String publicKeyString)
throws NoSuchAlgorithmException,
NoSuchPaddingException,
InvalidKeyException,
IllegalBlockSizeException,
BadPaddingException {
try {
if (publicKeyString.contains("-----BEGIN PUBLIC KEY-----") || publicKeyString.contains("-----END PUBLIC KEY-----"))
publicKeyString = publicKeyString.replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", "");
byte[] keyBytes = Base64.decode(publicKeyString, Base64.DEFAULT);
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePublic(spec);
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
e.printStackTrace();
return null;
}
}