github.com/jasoet/gopki@v1.15.0/pkcs12/helpers.go (about) 1 package pkcs12 2 3 import ( 4 "crypto/ecdsa" 5 "crypto/ed25519" 6 "crypto/rsa" 7 "crypto/x509" 8 "fmt" 9 "time" 10 11 "github.com/jasoet/gopki/keypair" 12 ) 13 14 // validateCertificateChain validates that the certificate chain is properly ordered and valid 15 func validateCertificateChain(leafCert *x509.Certificate, caCerts []*x509.Certificate) error { 16 if leafCert == nil { 17 return fmt.Errorf("leaf certificate is required") 18 } 19 20 if len(caCerts) == 0 { 21 // No chain to validate 22 return nil 23 } 24 25 // Create certificate pool from CA certificates 26 pool := x509.NewCertPool() 27 for _, caCert := range caCerts { 28 pool.AddCert(caCert) 29 } 30 31 // Verify the certificate chain 32 opts := x509.VerifyOptions{ 33 Roots: pool, 34 } 35 36 _, err := leafCert.Verify(opts) 37 if err != nil { 38 return fmt.Errorf("certificate chain verification failed: %w", err) 39 } 40 41 return nil 42 } 43 44 // validateCertificateExpiration checks if the certificate is currently valid 45 func validateCertificateExpiration(cert *x509.Certificate) error { 46 if cert == nil { 47 return fmt.Errorf("certificate is required") 48 } 49 50 now := time.Now() 51 if now.Before(cert.NotBefore) { 52 return fmt.Errorf("certificate is not yet valid (valid from %s)", cert.NotBefore.Format(time.RFC3339)) 53 } 54 55 if now.After(cert.NotAfter) { 56 return fmt.Errorf("certificate has expired (expired on %s)", cert.NotAfter.Format(time.RFC3339)) 57 } 58 59 return nil 60 } 61 62 // validateKeyPairMatch validates that the private key matches the certificate's public key 63 func validateKeyPairMatch(privateKey keypair.GenericPrivateKey, publicKey keypair.GenericPublicKey) error { 64 switch priv := privateKey.(type) { 65 case *rsa.PrivateKey: 66 pub, ok := publicKey.(*rsa.PublicKey) 67 if !ok { 68 return fmt.Errorf("private key is RSA but public key is not") 69 } 70 if priv.PublicKey.N.Cmp(pub.N) != 0 || priv.PublicKey.E != pub.E { 71 return fmt.Errorf("RSA private key does not match public key") 72 } 73 74 case *ecdsa.PrivateKey: 75 pub, ok := publicKey.(*ecdsa.PublicKey) 76 if !ok { 77 return fmt.Errorf("private key is ECDSA but public key is not") 78 } 79 if priv.PublicKey.X.Cmp(pub.X) != 0 || priv.PublicKey.Y.Cmp(pub.Y) != 0 { 80 return fmt.Errorf("ECDSA private key does not match public key") 81 } 82 83 case ed25519.PrivateKey: 84 pub, ok := publicKey.(ed25519.PublicKey) 85 if !ok { 86 return fmt.Errorf("private key is Ed25519 but public key is not") 87 } 88 expectedPub := priv.Public().(ed25519.PublicKey) 89 if !expectedPub.Equal(pub) { 90 return fmt.Errorf("Ed25519 private key does not match public key") 91 } 92 93 default: 94 return fmt.Errorf("unsupported private key type: %T", privateKey) 95 } 96 97 return nil 98 } 99 100 // getPrivateKeyType returns a string description of the private key type 101 func getPrivateKeyType(privateKey keypair.GenericPrivateKey) string { 102 switch privateKey.(type) { 103 case *rsa.PrivateKey: 104 return "RSA" 105 case *ecdsa.PrivateKey: 106 return "ECDSA" 107 case ed25519.PrivateKey: 108 return "Ed25519" 109 default: 110 return fmt.Sprintf("Unknown (%T)", privateKey) 111 } 112 } 113 114 // createKeyPairFromPrivateKey is available in keypair/p12.go for GoPKI integration 115 116 // GetCertificateInfo extracts useful information from a certificate for display purposes 117 func GetCertificateInfo(cert *x509.Certificate) map[string]interface{} { 118 if cert == nil { 119 return nil 120 } 121 122 info := map[string]interface{}{ 123 "subject": cert.Subject.String(), 124 "issuer": cert.Issuer.String(), 125 "serial": cert.SerialNumber.String(), 126 "not_before": cert.NotBefore.Format(time.RFC3339), 127 "not_after": cert.NotAfter.Format(time.RFC3339), 128 "is_ca": cert.IsCA, 129 "key_usage": getKeyUsageStrings(cert.KeyUsage), 130 "ext_key_usage": getExtKeyUsageStrings(cert.ExtKeyUsage), 131 } 132 133 if len(cert.DNSNames) > 0 { 134 info["dns_names"] = cert.DNSNames 135 } 136 137 if len(cert.EmailAddresses) > 0 { 138 info["email_addresses"] = cert.EmailAddresses 139 } 140 141 if len(cert.IPAddresses) > 0 { 142 info["ip_addresses"] = cert.IPAddresses 143 } 144 145 return info 146 } 147 148 // getKeyUsageStrings converts key usage flags to human-readable strings 149 func getKeyUsageStrings(usage x509.KeyUsage) []string { 150 var usages []string 151 152 if usage&x509.KeyUsageDigitalSignature != 0 { 153 usages = append(usages, "Digital Signature") 154 } 155 if usage&x509.KeyUsageContentCommitment != 0 { 156 usages = append(usages, "Content Commitment") 157 } 158 if usage&x509.KeyUsageKeyEncipherment != 0 { 159 usages = append(usages, "Key Encipherment") 160 } 161 if usage&x509.KeyUsageDataEncipherment != 0 { 162 usages = append(usages, "Data Encipherment") 163 } 164 if usage&x509.KeyUsageKeyAgreement != 0 { 165 usages = append(usages, "Key Agreement") 166 } 167 if usage&x509.KeyUsageCertSign != 0 { 168 usages = append(usages, "Certificate Sign") 169 } 170 if usage&x509.KeyUsageCRLSign != 0 { 171 usages = append(usages, "CRL Sign") 172 } 173 if usage&x509.KeyUsageEncipherOnly != 0 { 174 usages = append(usages, "Encipher Only") 175 } 176 if usage&x509.KeyUsageDecipherOnly != 0 { 177 usages = append(usages, "Decipher Only") 178 } 179 180 return usages 181 } 182 183 // getExtKeyUsageStrings converts extended key usage values to human-readable strings 184 func getExtKeyUsageStrings(extUsage []x509.ExtKeyUsage) []string { 185 var usages []string 186 187 for _, usage := range extUsage { 188 switch usage { 189 case x509.ExtKeyUsageServerAuth: 190 usages = append(usages, "Server Authentication") 191 case x509.ExtKeyUsageClientAuth: 192 usages = append(usages, "Client Authentication") 193 case x509.ExtKeyUsageCodeSigning: 194 usages = append(usages, "Code Signing") 195 case x509.ExtKeyUsageEmailProtection: 196 usages = append(usages, "Email Protection") 197 case x509.ExtKeyUsageTimeStamping: 198 usages = append(usages, "Time Stamping") 199 case x509.ExtKeyUsageOCSPSigning: 200 usages = append(usages, "OCSP Signing") 201 default: 202 usages = append(usages, fmt.Sprintf("Unknown (%d)", int(usage))) 203 } 204 } 205 206 return usages 207 } 208 209 // ValidateP12File performs comprehensive validation on a P12 file 210 func ValidateP12File(filename, password string) error { 211 // Load the P12 file 212 container, err := LoadFromP12File(filename, LoadOptions{ 213 Password: password, 214 ValidateChain: true, 215 CheckExpiration: true, 216 }) 217 if err != nil { 218 return fmt.Errorf("failed to load P12 file: %w", err) 219 } 220 221 // Validate container contents 222 if err := container.Validate(); err != nil { 223 return fmt.Errorf("P12 container validation failed: %w", err) 224 } 225 226 return nil 227 } 228 229 // ConvertP12ToGoPKI is available in keypair/p12.go for GoPKI integration