How to calculate X.509 certificate's SHA-1 fingerprint?

前端 未结 2 2147
萌比男神i
萌比男神i 2021-02-07 05:44

I\'m trying to implement an X.509 certificate generator from scratch (I know about the existing ones, but I need yet another one). What I cannot understand is how to calculate t

相关标签:
2条回答
  • 2021-02-07 06:17

    The finger print is similar to term "Thumbprint" in .net. Below code snippet should help you to compute finger print :

        public String generateFingerPrint(X509Certificate cert) throws CertificateEncodingException,NoSuchAlgorithmException {
    
    MessageDigest digest = MessageDigest.getInstance("SHA-1");
    byte[] hash = digest.digest(cert.getEncoded[]);
    
    final char delimiter = ':';
    // Calculate the number of characters in our fingerprint
          // ('# of bytes' * 2) chars + ('# of bytes' - 1) chars for delimiters
          final int len = hash.length * 2 + hash.length - 1;
          // Typically SHA-1 algorithm produces 20 bytes, i.e. len should be 59
          StringBuilder fingerprint = new StringBuilder(len);
    
          for (int i = 0; i < hash.length; i++) {
             // Step 1: unsigned byte
             hash[i] &= 0xff;
    
             // Steps 2 & 3: byte to hex in two chars
             // Lower cased 'x' at '%02x' enforces lower cased char for hex value!
             fingerprint.append(String.format("%02x", hash[i]));
    
             // Step 4: put delimiter
             if (i < hash.length - 1) {
                fingerprint.append(delimiter);
             }
          }
    
          return fingerprint.toString();
    
    
        }
    
    0 讨论(0)
  • 2021-02-07 06:24

    Ok, so it turned out that the fingerprint calculated by OpenSSL is simply a hash over the whole certificate (in its DER binary encoding, not the ASCII PEM one!), not only the TBS part, as I thought.

    For anyone who cares about calculating certificate's digest, it is done in a different way: the hash is calculated over the DER-encoded (again, not the PEM string) TBS part only, including its ASN.1 header (the ID 0x30 == ASN1_SEQUENCE | ASN1_CONSTRUCTED and the length field). Please note that the certificate's ASN.1 header is not taken into account.

    0 讨论(0)
提交回复
热议问题