PEM to PublicKey in Android

后端 未结 2 1509
误落风尘
误落风尘 2021-02-04 15:57

I\'ve seen a number of similar questions, but nothing has quite worked for me. I am simply trying to convert an RSA public key that\'s in PEM format that I\'ve retrieved from a

相关标签:
2条回答
  • 2021-02-04 16:38

    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.)

    0 讨论(0)
  • 2021-02-04 16:51

    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!

    0 讨论(0)
提交回复
热议问题