File: FingerprintHelper.java

package info (click to toggle)
voms-api-java 3.3.5-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 1,164 kB
  • sloc: java: 7,524; xml: 358; sh: 61; makefile: 2
file content (70 lines) | stat: -rw-r--r-- 2,179 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// SPDX-FileCopyrightText: 2006 Istituto Nazionale di Fisica Nucleare
//
// SPDX-License-Identifier: Apache-2.0

package org.italiangrid.voms.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;

/**
 * A utility class for computing fingerprints of X.509 certificates.
 * <p>
 * This class provides methods to generate a cryptographic fingerprint (hash) of an X.509
 * certificate using a specified digest algorithm.
 * </p>
 *
 * <p>
 * The default digest algorithm used is SHA-1.
 * </p>
 *
 */
public class FingerprintHelper {

  /** The default message digest algorithm used for computing fingerprints. */
  public static final String DEFAULT_DIGEST_ALGORITHM = "SHA-1";

  /**
   * Converts a byte array to a hexadecimal string representation.
   *
   * @param bytes the byte array to convert
   * @return a string containing the hexadecimal representation of the byte array
   */
  private static String hexify(byte[] bytes) {

    char[] hexDigits =
        {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    StringBuffer buf = new StringBuffer(bytes.length * 2);

    for (int i = 0; i < bytes.length; ++i) {
      buf.append(hexDigits[(bytes[i] & 0xf0) >> 4]);
      buf.append(hexDigits[bytes[i] & 0x0f]);
    }

    return buf.toString();
  }

  /**
   * Computes the fingerprint of an X.509 certificate using the default digest algorithm.
   *
   * @param cert the X.509 certificate for which to compute the fingerprint
   * @return the fingerprint of the certificate as a hexadecimal string
   * @throws NoSuchAlgorithmException if the specified digest algorithm is not available
   * @throws CertificateEncodingException if encoding the certificate fails
   */
  public static String getFingerprint(X509Certificate cert)
      throws NoSuchAlgorithmException, CertificateEncodingException {

    MessageDigest md = MessageDigest.getInstance(DEFAULT_DIGEST_ALGORITHM);
    byte[] der = cert.getEncoded();

    md.update(der);
    byte[] digest = md.digest();

    return hexify(digest);
  }

}