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

前端 未结 2 2146
萌比男神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();
    
    
        }
    

提交回复
热议问题