utils.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package acme
  2. import (
  3. "crypto/x509"
  4. "encoding/pem"
  5. "errors"
  6. "fmt"
  7. "os"
  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 := os.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. // Check if exist incase some acme server didn't have org section
  49. if len(cert.Issuer.Organization) == 0 {
  50. return "", fmt.Errorf("cert didn't have org section exist")
  51. }
  52. // Extract the issuer name
  53. issuer := cert.Issuer.Organization[0]
  54. return issuer, nil
  55. }
  56. // Check if a cert is expired by public key
  57. func CertIsExpired(certBytes []byte) bool {
  58. block, _ := pem.Decode(certBytes)
  59. if block != nil {
  60. cert, err := x509.ParseCertificate(block.Bytes)
  61. if err == nil {
  62. elapsed := time.Since(cert.NotAfter)
  63. if elapsed > 0 {
  64. // if it is expired then add it in
  65. // make sure it's uniqueless
  66. return true
  67. }
  68. }
  69. }
  70. return false
  71. }
  72. // CertExpireSoon check if the given cert bytes will expires within the given number of days from now
  73. func CertExpireSoon(certBytes []byte, numberOfDays int) bool {
  74. block, _ := pem.Decode(certBytes)
  75. if block != nil {
  76. cert, err := x509.ParseCertificate(block.Bytes)
  77. if err == nil {
  78. expirationDate := cert.NotAfter
  79. threshold := time.Duration(numberOfDays) * 24 * time.Hour
  80. timeRemaining := time.Until(expirationDate)
  81. if timeRemaining <= threshold {
  82. return true
  83. }
  84. }
  85. }
  86. return false
  87. }