user443180
user443180

Reputation: 231

how to convert public key of an x509 certificate in JAVA to hex

We have requirement to get the "public key of an x509 certificate" in out project. We are using x509Certificate.getPublicKey() API to get the byte[] and then calculating the hexadecimal form of it. For example public key in hexadecimal form of a certificate calculated in java is following

30820122300d06092a864886f70d01010105000382010f003082010a0282010100af240808297a359e600caae74b3b4edc7cbc3c451cbb2be0fe2902f95708a364851527f5f1adc831895d22e82aaaa642b38ff8b955b7b1b74bb3fe8f7e0757ecef43db66621561cf600da4d8def8e0c362083d5413eb49ca59548526e52b8f1b9febf5a191c23349d843636a524bd28fe870514dd189697bc770f6b3dc1274db7b5d4b56d396bf1577a1b0f4a225f2af1c926718e5f40604ef90b9e400e4dd3ab519ff02baf43ceee08beb378becf4d7acf2f6f03dafdd759133191d1c40cb7424192193d914feac2a52c78fd50449e48d6347883c6983cbfe47bd2b7e4fc595ae0e9dd4d143c06773e314087ee53f9f73b8330acf5d3f3487968aee53e825150203010001

But when we double click the certificate and see value of public key in details tab, it is following:

3082010a0282010100af240808297a359e600caae74b3b4edc7cbc3c451cbb2be0fe2902f95708a364851527f5f1adc831895d22e82aaaa642b38ff8b955b7b1b74bb3fe8f7e0757ecef43db66621561cf600da4d8def8e0c362083d5413eb49ca59548526e52b8f1b9febf5a191c23349d843636a524bd28fe870514dd189697bc770f6b3dc1274db7b5d4b56d396bf1577a1b0f4a225f2af1c926718e5f40604ef90b9e400e4dd3ab519ff02baf43ceee08beb378becf4d7acf2f6f03dafdd759133191d1c40cb7424192193d914feac2a52c78fd50449e48d6347883c6983cbfe47bd2b7e4fc595ae0e9dd4d143c06773e314087ee53f9f73b8330acf5d3f3487968aee53e825150203010001

What we have found is that the value calculated by JAVA api has extra 44 characters in the begining and the from the 45th character the data is same as value calculated by windows.

can any body please help me to identify how to calculated the public key of a certificate which same as calculated by windows.

Thank You.

Upvotes: 2

Views: 4974

Answers (1)

Jcs
Jcs

Reputation: 13749

In a X509 certificate the public key is encoded into an ASN.1 structure called SubjectPublicKeyInfo which looks like this:

SubjectPublicKeyInfo  ::=  SEQUENCE  {
     algorithm            AlgorithmIdentifier,
     subjectPublicKey     BIT STRING  }

The algorithm field identifies the kind of key (RSA, DSA, Diffie Hellman...) and the bit string contains the public key data encoded into a structure which depends on the key type.

In your case the first byte[] contains all data of the SubjectPublicKeyInfo including the top level SEQUENCE tag, the length and the algorithm field and the subjectPublicKey field.

The second byte[] only contains the second field (i.e the BIT STRING). In your example this is a RSA public key encoded with this structure:

RSAPublicKey ::= SEQUENCE {
   modulus            INTEGER,    -- n
   publicExponent     INTEGER  }  -- e

Upvotes: 4

Related Questions