PEM to PublicKey in Android

This doesn't answer the question, but I find the content relevant. Posting as an answer because it doesn't fit as a comment.

PEM vs DER

  • PEM basically encapsulates a DER-encoded certificate or key.
  • DER is binary, PEM is text; so PEM can easily be copy-pasted to an email, for example.
  • What PEM does is:
    1. Encode the DER certificate or key using Base64, and
    2. Delimit the result with -----BEGIN <something>----- and -----END <something>-----.
  • The key or certificate is the same, just represented in a different format.

Mostly paraphrasing from ASN.1(wiki).

DER to Android/Java public key

The following is an example of how to use a key factory in order to instantiate a DSA public key from its encoding. Assume Alice has received a digital signature from Bob. Bob also sent her his public key (in encoded format) to verify his signature. Alice then performs the following actions:

X509EncodedKeySpec bobPubKeySpec = new X509EncodedKeySpec(bobEncodedPubKey);
KeyFactory keyFactory = KeyFactory.getInstance("DSA");
PublicKey bobPubKey = keyFactory.generatePublic(bobPubKeySpec);

...

Note that bobEncodedPubKey is DER-encoded in this sample.

https://developer.android.com/reference/java/security/KeyFactory

PEM to Android/Java public key

Similar to what is done for DER, but do the following beforehand:

  1. Remove the BEGIN/END delimitation, and
  2. Decode the content in Base64 to obtain the original DER.

(The question already shows code on how to do this.)


To answer my own question...The first output is in hex and the second output is in base 64. Just change the return statement to return new String(Base64.encode(encryptedBytes)); and you'll be good!