Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extraction of sha1 from X.509 openssl certificate in Java

I must write a Java implementation of an X.509 openssl certificate parser, but I have a problem: I do not know how to get the sha1 for the validation of certificates. Can anyone help me to understand what I should do? I know that there is a method getTBSCertificate() in Java, but I have to rewrite it for my purpose.

like image 862
4nf3rt Avatar asked Nov 16 '25 20:11

4nf3rt


1 Answers

Assuming you mean the sha1 which is commonly shown as the 'fingerprint' in the browsers and OS tools -- you need 1) the raw cert as DER; and then 2) sha1 it and 3) translate that to the usual double-digit-hex/colon separated string.

As to 1; getEncoded() from java.security.cert.Certificate gets you that.

As to 2: MessageDigest has that function.

As to 3: I'll leave that to you :)

... someFoo(X509Certificate cert) {
    MessageDigest sha1 = MessageDigest.getInstance("SHA1");
    System.out.println("  Subject " + cert.getSubjectDN());
    System.out.println("   Issuer  " + cert.getIssuerDN());
    sha1.update(cert.getEncoded());
    System.out.println("   sha1    " + toHexString(sha1.digest()));
    System.out.println();
  }

should do the trick. This output matches that of the java keytool.

Dw.

like image 106
Dirk-Willem van Gulik Avatar answered Nov 18 '25 11:11

Dirk-Willem van Gulik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!