fingerprint.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Copyright 2015 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package x509
  5. import (
  6. "bytes"
  7. "crypto/md5"
  8. "crypto/sha1"
  9. "crypto/sha256"
  10. "crypto/sha512"
  11. "encoding/hex"
  12. "encoding/json"
  13. )
  14. // CertificateFingerprint represents a digest/fingerprint of some data. It can
  15. // easily be encoded to hex and JSON (as a hex string).
  16. type CertificateFingerprint []byte
  17. // MD5Fingerprint creates a fingerprint of data using the MD5 hash algorithm.
  18. func MD5Fingerprint(data []byte) CertificateFingerprint {
  19. sum := md5.Sum(data)
  20. return sum[:]
  21. }
  22. // SHA1Fingerprint creates a fingerprint of data using the SHA1 hash algorithm.
  23. func SHA1Fingerprint(data []byte) CertificateFingerprint {
  24. sum := sha1.Sum(data)
  25. return sum[:]
  26. }
  27. // SHA256Fingerprint creates a fingerprint of data using the SHA256 hash
  28. // algorithm.
  29. func SHA256Fingerprint(data []byte) CertificateFingerprint {
  30. sum := sha256.Sum256(data)
  31. return sum[:]
  32. }
  33. // SHA512Fingerprint creates a fingerprint of data using the SHA256 hash
  34. // algorithm.
  35. func SHA512Fingerprint(data []byte) CertificateFingerprint {
  36. sum := sha512.Sum512(data)
  37. return sum[:]
  38. }
  39. // Equal returns true if the fingerprints are bytewise-equal.
  40. func (f CertificateFingerprint) Equal(other CertificateFingerprint) bool {
  41. return bytes.Equal(f, other)
  42. }
  43. // Hex returns the given fingerprint encoded as a hex string.
  44. func (f CertificateFingerprint) Hex() string {
  45. return hex.EncodeToString(f)
  46. }
  47. // MarshalJSON implements the json.Marshaler interface, and marshals the
  48. // fingerprint as a hex string.
  49. func (f *CertificateFingerprint) MarshalJSON() ([]byte, error) {
  50. return json.Marshal(f.Hex())
  51. }