1
0

utils.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package acme
  2. import (
  3. "crypto/x509"
  4. "encoding/pem"
  5. "errors"
  6. "fmt"
  7. "io/ioutil"
  8. "time"
  9. )
  10. // Get the issuer name from pem file
  11. func ExtractIssuerNameFromPEM(pemFilePath string) (string, error) {
  12. // Read the PEM file
  13. pemData, err := ioutil.ReadFile(pemFilePath)
  14. if err != nil {
  15. return "", err
  16. }
  17. return ExtractIssuerName(pemData)
  18. }
  19. // Get the DNSName in the cert
  20. func ExtractDomains(certBytes []byte) ([]string, error) {
  21. domains := []string{}
  22. block, _ := pem.Decode(certBytes)
  23. if block != nil {
  24. cert, err := x509.ParseCertificate(block.Bytes)
  25. if err != nil {
  26. return []string{}, err
  27. }
  28. for _, dnsName := range cert.DNSNames {
  29. if !contains(domains, dnsName) {
  30. domains = append(domains, dnsName)
  31. }
  32. }
  33. return domains, nil
  34. }
  35. return []string{}, errors.New("decode cert bytes failed")
  36. }
  37. func ExtractIssuerName(certBytes []byte) (string, error) {
  38. // Parse the PEM block
  39. block, _ := pem.Decode(certBytes)
  40. if block == nil || block.Type != "CERTIFICATE" {
  41. return "", fmt.Errorf("failed to decode PEM block containing certificate")
  42. }
  43. // Parse the certificate
  44. cert, err := x509.ParseCertificate(block.Bytes)
  45. if err != nil {
  46. return "", fmt.Errorf("failed to parse certificate: %v", err)
  47. }
  48. // Extract the issuer name
  49. issuer := cert.Issuer.Organization[0]
  50. return issuer, nil
  51. }
  52. // Check if a cert is expired by public key
  53. func CertIsExpired(certBytes []byte) bool {
  54. block, _ := pem.Decode(certBytes)
  55. if block != nil {
  56. cert, err := x509.ParseCertificate(block.Bytes)
  57. if err == nil {
  58. elapsed := time.Since(cert.NotAfter)
  59. if elapsed > 0 {
  60. // if it is expired then add it in
  61. // make sure it's uniqueless
  62. return true
  63. }
  64. }
  65. }
  66. return false
  67. }
  68. func CertExpireSoon(certBytes []byte) bool {
  69. block, _ := pem.Decode(certBytes)
  70. if block != nil {
  71. cert, err := x509.ParseCertificate(block.Bytes)
  72. if err == nil {
  73. expirationDate := cert.NotAfter
  74. threshold := 14 * 24 * time.Hour // 14 days
  75. timeRemaining := time.Until(expirationDate)
  76. if timeRemaining <= threshold {
  77. return true
  78. }
  79. }
  80. }
  81. return false
  82. }