Search code examples
javasecurityrsa

How can I construct a java.security.PublicKey object from a base64 encoded string?


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 the java.security.PublicKey interface. I am on Java 6 if that makes a difference.

The key is (probably) generated using standard java lib and not bouncy castle (its from a remote team so I am not sure). Their sample code says to use Security.generatePublicKey(base64EncodedPublicKey); but the Security object in standard java has no such method.


Solution

  • Ok for grins ... try this

    • base64 decode the key data to get a byte array (byte[])
    • Create a new X509EncodedKeySpec using the byte array
    • Get an instance of KeyFactory using KeyFactory.getInstance("RSA") assuming RSA here
    • call the method generatePublic(KeySpec) with the X509EncodedKeySpec
    • Result /should/ be a public key for your usage.