Skip to content Skip to sidebar Skip to footer

Load Public Key Data From File

In my App I generate a public/private key pair and store them for later usage on disk. Loading and re-initialising the private key works fine but for the private key I get a Unknow

Solution 1:

Public and Private keys are encoded differently. Whilst private keys are encoded in PKCS #8, public keys are not. They are instead encoded in X.509 according to the ASN.1 specifications.

Description from the Key.getFormat() method:

Returns the name of the primary encoding format of this key, or null if this key does not support encoding. The primary encoding format is named in terms of the appropriate ASN.1 data format, if an ASN.1 specification for this key exists. For example, the name of the ASN.1 data format for public keys is SubjectPublicKeyInfo, as defined by the X.509 standard; in this case, the returned format is "X.509". Similarly, the name of the ASN.1 data format for private keys is PrivateKeyInfo, as defined by the PKCS #8 standard; in this case, the returned format is "PKCS#8".

According to this, instead of reading public keys as PKCS #8, you should read it as X.509.

Consider changing your public key reading code from:

PKCS8EncodedKeySpeckeySpec=newPKCS8EncodedKeySpec(data);

to:

X509EncodedKeySpeckeySpec=newX509EncodedKeySpec(data);

Post a Comment for "Load Public Key Data From File"