x509util.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. /*
  2. * Public Domain Software
  3. *
  4. * I (Matthias Ladkau) am the author of the source code in this file.
  5. * I have placed the source code in this file in the public domain.
  6. *
  7. * For further information see: http://creativecommons.org/publicdomain/zero/1.0/
  8. */
  9. package cryptutil
  10. import (
  11. "bytes"
  12. "crypto/md5"
  13. "crypto/sha1"
  14. "crypto/sha256"
  15. "crypto/x509"
  16. "encoding/pem"
  17. "errors"
  18. "fmt"
  19. "io/ioutil"
  20. "os"
  21. )
  22. /*
  23. ReadX509CertsFromFile reads a list of pem encoded certificates from a given file.
  24. */
  25. func ReadX509CertsFromFile(filename string) ([]*x509.Certificate, error) {
  26. var err error
  27. var certs []*x509.Certificate
  28. file, err := os.OpenFile(filename, os.O_RDONLY, 0660)
  29. if err != nil {
  30. return nil, err
  31. }
  32. defer file.Close()
  33. certsString, err := ioutil.ReadAll(file)
  34. if err == nil {
  35. certs, err = ReadX509Certs(certsString)
  36. }
  37. return certs, err
  38. }
  39. /*
  40. ReadX509Certs reads a list of pem encoded certificates from a byte array.
  41. */
  42. func ReadX509Certs(certs []byte) ([]*x509.Certificate, error) {
  43. var blocks []byte
  44. for {
  45. var block *pem.Block
  46. block, certs = pem.Decode(certs)
  47. if block == nil {
  48. return nil, errors.New("PEM not parsed")
  49. }
  50. blocks = append(blocks, block.Bytes...)
  51. if len(certs) == 0 {
  52. break
  53. }
  54. }
  55. c, err := x509.ParseCertificates(blocks)
  56. if err != nil {
  57. return nil, err
  58. }
  59. return c, nil
  60. }
  61. /*
  62. Sha1CertFingerprint computes a sha1 fingerprint for a certificate.
  63. */
  64. func Sha1CertFingerprint(cert *x509.Certificate) string {
  65. return formatFingerprint(fmt.Sprintf("%x", sha1.Sum(cert.Raw)))
  66. }
  67. /*
  68. Sha256CertFingerprint computes a sha256 fingerprint for a certificate.
  69. */
  70. func Sha256CertFingerprint(cert *x509.Certificate) string {
  71. return formatFingerprint(fmt.Sprintf("%x", sha256.Sum256(cert.Raw)))
  72. }
  73. /*
  74. Md5CertFingerprint computes a md5 fingerprint for a certificate.
  75. */
  76. func Md5CertFingerprint(cert *x509.Certificate) string {
  77. return formatFingerprint(fmt.Sprintf("%x", md5.Sum(cert.Raw)))
  78. }
  79. /*
  80. Format a given fingerprint string.
  81. */
  82. func formatFingerprint(raw string) string {
  83. var buf bytes.Buffer
  84. for i, c := range raw {
  85. buf.WriteByte(byte(c))
  86. if (i+1)%2 == 0 && i != len(raw)-1 {
  87. buf.WriteByte(byte(':'))
  88. }
  89. }
  90. return buf.String()
  91. }