Load public key data from file

后端 未结 1 1598
逝去的感伤
逝去的感伤 2021-02-04 16:54

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 Unk

相关标签:
1条回答
  • 2021-02-04 17:46

    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:

    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(data);
    

    to:

    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(data);
    
    0 讨论(0)
提交回复
热议问题