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:
- Encode the DER certificate or key using Base64, and
- 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:
- Remove the
BEGIN
/END
delimitation, and - 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!