VerifactuMidAPI/internal/cert/validator.go

83 lines
1.9 KiB
Go
Raw Permalink Normal View History

package cert
import (
"encoding/base64"
"time"
"golang.org/x/crypto/pkcs12"
)
type ValidationResult struct {
Valid bool `json:"valid"`
CertInfo *CertInfo `json:"cert_info,omitempty"`
Warnings []string `json:"warnings,omitempty"`
Error string `json:"error,omitempty"`
}
type CertInfo struct {
Subject string `json:"subject"`
Issuer string `json:"issuer"`
NotBefore string `json:"not_before"`
NotAfter string `json:"not_after"`
Expired bool `json:"expired"`
ExpiringSoon bool `json:"expiring_soon"`
DaysUntilExpiry int `json:"days_until_expiry"`
}
const WarningDaysThreshold = 30
func ValidateP12(base64Content, password string) *ValidationResult {
result := &ValidationResult{Valid: true}
der, err := base64.StdEncoding.DecodeString(base64Content)
if err != nil {
result.Valid = false
result.Error = "invalid_base64"
return result
}
_, cert, err := pkcs12.Decode(der, password)
if err != nil {
result.Valid = false
result.Error = "invalid_password_or_format"
return result
}
if cert == nil {
result.Valid = false
result.Error = "no_certificate_found"
return result
}
now := time.Now()
if now.Before(cert.NotBefore) {
result.Valid = false
result.Error = "certificate_not_yet_valid"
return result
}
if now.After(cert.NotAfter) {
result.Valid = false
result.Error = "certificate_expired"
result.CertInfo = &CertInfo{Expired: true}
return result
}
daysUntilExpiry := int(cert.NotAfter.Sub(now).Hours() / 24)
result.CertInfo = &CertInfo{
Subject: cert.Subject.String(),
Issuer: cert.Issuer.String(),
NotBefore: cert.NotBefore.Format("2006-01-02"),
NotAfter: cert.NotAfter.Format("2006-01-02"),
DaysUntilExpiry: daysUntilExpiry,
}
if daysUntilExpiry <= WarningDaysThreshold {
result.Warnings = append(result.Warnings, "certificate_expiring_soon")
result.CertInfo.ExpiringSoon = true
}
return result
}