cert.go 949 B

12345678910111213141516171819202122232425262728293031323334
  1. package cert
  2. import (
  3. "crypto/tls"
  4. "crypto/x509"
  5. "encoding/pem"
  6. "github.com/pkg/errors"
  7. )
  8. // GetCertSnFromConfig return SerialNumber by tls.Config
  9. func GetCertSnFromConfig(config *tls.Config) (string, error) {
  10. if len(config.Certificates) == 0 || len(config.Certificates[0].Certificate) == 0 {
  11. return "", errors.New("certificates is empty")
  12. }
  13. return GetCertSnFromBlock(config.Certificates[0].Certificate[0])
  14. }
  15. // GetCertSnFromEncode return SerialNumber by encoded cert
  16. func GetCertSnFromEncode(b []byte) (string, error) {
  17. block, _ := pem.Decode(b)
  18. if block == nil {
  19. return "", errors.New("block is not a cert encoded")
  20. }
  21. return GetCertSnFromBlock(block.Bytes)
  22. }
  23. // GetCertSnFromBlock return SerialNumber by decode block
  24. func GetCertSnFromBlock(block []byte) (string, error) {
  25. cert, err := x509.ParseCertificate(block)
  26. if err != nil {
  27. return "", errors.Wrap(err, "ParseCertificate")
  28. }
  29. return cert.SerialNumber.String(), nil
  30. }