I have a bse64encoded string Public key from external source (Android Store) and I need to use it to verify signed content. How can I convert the string into an instance of
Code for the above answer
public static PublicKey getKey(String key){
try{
byte[] byteKey = Base64.decode(key.getBytes(), Base64.DEFAULT);
X509EncodedKeySpec X509publicKey = new X509EncodedKeySpec(byteKey);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(X509publicKey);
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
Using spongy castle
public static PublicKey getPublicKeyFromString(String key) throws Exception {
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
org.spongycastle.asn1.pkcs.RSAPublicKey pkcs1PublicKey
= org.spongycastle.asn1.pkcs.RSAPublicKey.getInstance(decodeB64(key));
RSAPublicKeySpec keySpec
= new RSAPublicKeySpec(pkcs1PublicKey.getModulus(), pkcs1PublicKey.getPublicExponent());
PublicKey publicKey = keyFactory.generatePublic(keySpec);
return publicKey;
}
you can try this solution:
add this dependency:
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpkix-jdk15on</artifactId>
<version>1.61</version>
and use this method:
private Key parsePublicKey(String publicKey) throws IOException {
PEMParser pemParser = new PEMParser(new StringReader(publicKey));
JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(pemParser.readObject());
return converter.getPublicKey(publicKeyInfo);
}
Ok for grins ... try this
Try this....
PublicKey getPublicKey(byte[] encodedKey) throws NoSuchAlgorithmException, InvalidKeySpecException
{
KeyFactory factory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec encodedKeySpec = new X509EncodedKeySpec(encodedKey);
return factory.generatePublic(encodedKeySpec);
}