I have the following RSA public key as ASN1 sequence:
SEQUENCE(2 elem)
INTEGER (1024 bit) 14832…
INTEGER 65537
How can I import this sequence as RSA public key in Java? The implemented KeySpec
s (such as PKCS8EncodedKeySpec
) do not work (obviously).
In addition I tried to use BouncyCastle and manually decode the sequence and initialize java.security.spec.RSAPublicKeySpec
myself. However this approach seems rather clumsy.
Is there an easier way?
ASN.1 parsing with BouncyCastle is not that clumsy.
Another option is to build up your sequence up to X509 public key format and then use
X509EncodedKeySpec
. You will need to place encoded key as bit sequence together with algorithm identifier into ASN.1 sequence. However, this will result in approximately the same amount of code and is slower as there is more to parse. This answer has format nicely explained.You can use the Bouncycastle library as in the following code fragment:
Or, as a less attractive alternative, you can roll you own ASN.1 decoder as in this example from one of my answers. But beware, ASN.1 decoding can be very tricky -- this very simple two element sequence is about the most complicated ASN.1 structure I would ever attempt to parse with my own code.