github.com/jasoet/gopki@v1.15.0/cert/certificate.go (about) 1 package cert 2 3 import ( 4 "crypto" 5 "crypto/rand" 6 "crypto/x509" 7 "crypto/x509/pkix" 8 "encoding/pem" 9 "fmt" 10 "github.com/jasoet/gopki/keypair" 11 "github.com/jasoet/gopki/keypair/algo" 12 "math/big" 13 "net" 14 "os" 15 "time" 16 ) 17 18 // Certificate represents an X.509 certificate with support for both PEM and DER formats. 19 // It contains the parsed certificate and the raw data in both text (PEM) and binary (DER) formats. 20 type Certificate struct { 21 Certificate *x509.Certificate // The parsed X.509 certificate 22 PEMData []byte // PEM-encoded certificate data (Base64 text format) 23 DERData []byte // DER-encoded certificate data (binary format) 24 } 25 26 // CertificateRequest contains the parameters for creating a new X.509 certificate. 27 // It supports both end-entity and CA certificates with configurable extensions and constraints. 28 type CertificateRequest struct { 29 Subject pkix.Name // Certificate subject information (CN, O, OU, etc.) 30 DNSNames []string // Subject Alternative Names - DNS names 31 IPAddresses []net.IP // Subject Alternative Names - IP addresses 32 EmailAddress []string // Subject Alternative Names - email addresses 33 ValidFrom time.Time // Certificate validity start time (defaults to now) 34 ValidFor time.Duration // Certificate validity duration (e.g., 365*24*time.Hour for 1 year) 35 36 // CA-specific fields (optional) 37 IsCA bool // Set to true to create a CA certificate 38 MaxPathLen int // Maximum depth of intermediate CAs (0 = can only sign end-entity certs, -1 = no limit) 39 MaxPathLenZero bool // Set to true to explicitly set MaxPathLen to 0 40 41 // Advanced certificate usage fields (optional) 42 KeyUsage x509.KeyUsage // Custom key usage flags (if not set, defaults based on IsCA) 43 ExtKeyUsage []x509.ExtKeyUsage // Custom extended key usage (if not set, defaults based on IsCA) 44 } 45 46 // CreateSelfSignedCertificate creates a new self-signed X.509 certificate using the provided key pair. 47 // The certificate is signed by its own private key, making it suitable for testing, development, 48 // or as a root CA certificate. 49 // 50 // Type parameter T must be one of: *algo.RSAKeyPair, *algo.ECDSAKeyPair, or *algo.Ed25519KeyPair. 51 // 52 // The returned Certificate contains both PEM and DER encoded data and can be saved in either format. 53 // 54 // Example: 55 // 56 // keyPair, _ := keypair.GenerateKeyPair[algo.KeySize, *algo.RSAKeyPair](2048) 57 // cert, err := CreateSelfSignedCertificate(keyPair, CertificateRequest{ 58 // Subject: pkix.Name{CommonName: "example.com"}, 59 // DNSNames: []string{"example.com", "www.example.com"}, 60 // ValidFor: 365 * 24 * time.Hour, 61 // }) 62 func CreateSelfSignedCertificate[T keypair.KeyPair](keyPair T, request CertificateRequest) (*Certificate, error) { 63 var privateKey crypto.PrivateKey 64 var publicKey crypto.PublicKey 65 66 switch kp := any(keyPair).(type) { 67 case *algo.RSAKeyPair: 68 privateKey = kp.PrivateKey 69 publicKey = kp.PublicKey 70 case *algo.ECDSAKeyPair: 71 privateKey = kp.PrivateKey 72 publicKey = kp.PublicKey 73 case *algo.Ed25519KeyPair: 74 privateKey = kp.PrivateKey 75 publicKey = kp.PublicKey 76 default: 77 return nil, fmt.Errorf("unsupported key pair type") 78 } 79 80 serialNumber, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128)) 81 if err != nil { 82 return nil, fmt.Errorf("failed to generate serial number: %v", err) 83 } 84 85 if request.ValidFrom.IsZero() { 86 request.ValidFrom = time.Now() 87 } 88 89 if request.ValidFor == 0 { 90 request.ValidFor = 365 * 24 * time.Hour // Default 1 year 91 } 92 93 // Determine key usage 94 var keyUsage x509.KeyUsage 95 var extKeyUsage []x509.ExtKeyUsage 96 97 // Check if custom key usage is provided 98 if request.KeyUsage != 0 { 99 keyUsage = request.KeyUsage 100 } else if request.IsCA { 101 // CA certificate 102 keyUsage = x509.KeyUsageCertSign | x509.KeyUsageCRLSign | x509.KeyUsageDigitalSignature 103 } else { 104 // End-entity certificate 105 keyUsage = x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature 106 } 107 108 // Check if custom extended key usage is provided 109 if request.ExtKeyUsage != nil { 110 extKeyUsage = request.ExtKeyUsage 111 } else if request.IsCA { 112 // CAs typically don't need extended key usage 113 extKeyUsage = nil 114 } else { 115 // End-entity certificate - for TLS/authentication 116 extKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth} 117 } 118 119 template := x509.Certificate{ 120 SerialNumber: serialNumber, 121 Subject: request.Subject, 122 NotBefore: request.ValidFrom, 123 NotAfter: request.ValidFrom.Add(request.ValidFor), 124 KeyUsage: keyUsage, 125 ExtKeyUsage: extKeyUsage, 126 BasicConstraintsValid: true, 127 IsCA: request.IsCA, 128 DNSNames: request.DNSNames, 129 IPAddresses: request.IPAddresses, 130 EmailAddresses: request.EmailAddress, 131 } 132 133 // Set MaxPathLen for CA certificates 134 if request.IsCA { 135 if request.MaxPathLenZero { 136 template.MaxPathLen = 0 137 template.MaxPathLenZero = true 138 } else if request.MaxPathLen >= 0 { 139 template.MaxPathLen = request.MaxPathLen 140 } 141 // If MaxPathLen is -1, we don't set it (no limit) 142 } 143 144 certDER, err := x509.CreateCertificate(rand.Reader, &template, &template, publicKey, privateKey) 145 if err != nil { 146 return nil, fmt.Errorf("failed to create certificate: %v", err) 147 } 148 149 cert, err := x509.ParseCertificate(certDER) 150 if err != nil { 151 return nil, fmt.Errorf("failed to parse created certificate: %v", err) 152 } 153 154 certPEM := pem.EncodeToMemory(&pem.Block{ 155 Type: "CERTIFICATE", 156 Bytes: certDER, 157 }) 158 159 return &Certificate{ 160 Certificate: cert, 161 PEMData: certPEM, 162 DERData: certDER, 163 }, nil 164 } 165 166 // CreateCACertificate creates a new Certificate Authority (CA) certificate. 167 // The certificate is configured with CA-specific extensions and can be used to sign other certificates. 168 // 169 // The certificate will have: 170 // - BasicConstraints extension with CA=true 171 // - KeyUsage extension with CertSign and CRLSign 172 // - Configurable path length constraints for intermediate CAs 173 // 174 // Type parameter T must be one of: *algo.RSAKeyPair, *algo.ECDSAKeyPair, or *algo.Ed25519KeyPair. 175 // 176 // Example: 177 // 178 // keyPair, _ := keypair.GenerateKeyPair[algo.KeySize, *algo.RSAKeyPair](4096) 179 // caCert, err := CreateCACertificate(keyPair, CertificateRequest{ 180 // Subject: pkix.Name{CommonName: "My Root CA"}, 181 // ValidFor: 10 * 365 * 24 * time.Hour, // 10 years 182 // IsCA: true, 183 // MaxPathLen: 2, // Allow 2 levels of intermediate CAs 184 // }) 185 func CreateCACertificate[T keypair.KeyPair](keyPair T, request CertificateRequest) (*Certificate, error) { 186 var privateKey crypto.PrivateKey 187 var publicKey crypto.PublicKey 188 189 switch kp := any(keyPair).(type) { 190 case *algo.RSAKeyPair: 191 privateKey = kp.PrivateKey 192 publicKey = kp.PublicKey 193 case *algo.ECDSAKeyPair: 194 privateKey = kp.PrivateKey 195 publicKey = kp.PublicKey 196 case *algo.Ed25519KeyPair: 197 privateKey = kp.PrivateKey 198 publicKey = kp.PublicKey 199 default: 200 return nil, fmt.Errorf("unsupported key pair type") 201 } 202 203 serialNumber, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128)) 204 if err != nil { 205 return nil, fmt.Errorf("failed to generate serial number: %v", err) 206 } 207 208 if request.ValidFrom.IsZero() { 209 request.ValidFrom = time.Now() 210 } 211 212 if request.ValidFor == 0 { 213 request.ValidFor = 10 * 365 * 24 * time.Hour // Default 10 years for CA 214 } 215 216 // Set MaxPathLen based on request or use default 217 maxPathLen := 0 218 maxPathLenZero := true 219 220 if request.MaxPathLen > 0 { 221 maxPathLen = request.MaxPathLen 222 maxPathLenZero = false 223 } else if request.MaxPathLen == -1 { 224 // -1 means no limit, don't set MaxPathLen 225 maxPathLenZero = false 226 } 227 228 template := x509.Certificate{ 229 SerialNumber: serialNumber, 230 Subject: request.Subject, 231 NotBefore: request.ValidFrom, 232 NotAfter: request.ValidFrom.Add(request.ValidFor), 233 KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign | x509.KeyUsageDigitalSignature, 234 BasicConstraintsValid: true, 235 IsCA: true, 236 MaxPathLen: maxPathLen, 237 MaxPathLenZero: maxPathLenZero, 238 } 239 240 certDER, err := x509.CreateCertificate(rand.Reader, &template, &template, publicKey, privateKey) 241 if err != nil { 242 return nil, fmt.Errorf("failed to create CA certificate: %v", err) 243 } 244 245 cert, err := x509.ParseCertificate(certDER) 246 if err != nil { 247 return nil, fmt.Errorf("failed to parse created certificate: %v", err) 248 } 249 250 certPEM := pem.EncodeToMemory(&pem.Block{ 251 Type: "CERTIFICATE", 252 Bytes: certDER, 253 }) 254 255 return &Certificate{ 256 Certificate: cert, 257 PEMData: certPEM, 258 DERData: certDER, 259 }, nil 260 } 261 262 // SignCertificate creates a new certificate signed by a Certificate Authority (CA). 263 // This function creates an end-entity or intermediate CA certificate using the provided CA certificate 264 // and private key to sign the new certificate. 265 // 266 // Parameters: 267 // - caCert: The CA certificate used to sign the new certificate 268 // - caKeyPair: The CA's private key pair for signing 269 // - request: Certificate request containing subject info and extensions 270 // - subjectPublicKey: The public key to be certified (from the entity requesting the certificate) 271 // 272 // The resulting certificate will be signed by the CA and contain the subject's public key. 273 // 274 // Example: 275 // 276 // // Create CA certificate first 277 // caCert, _ := CreateCACertificate(caKeyPair, caRequest) 278 // 279 // // Create end-entity certificate signed by CA 280 // entityKeyPair, _ := keypair.GenerateKeyPair[algo.KeySize, *algo.RSAKeyPair](2048) 281 // cert, err := SignCertificate(caCert, caKeyPair, CertificateRequest{ 282 // Subject: pkix.Name{CommonName: "server.example.com"}, 283 // DNSNames: []string{"server.example.com"}, 284 // ValidFor: 365 * 24 * time.Hour, 285 // }, entityKeyPair.PublicKey) 286 func SignCertificate[T keypair.KeyPair](caCert *Certificate, caKeyPair T, request CertificateRequest, subjectPublicKey crypto.PublicKey) (*Certificate, error) { 287 var caPrivateKey crypto.PrivateKey 288 289 switch kp := any(caKeyPair).(type) { 290 case *algo.RSAKeyPair: 291 caPrivateKey = kp.PrivateKey 292 case *algo.ECDSAKeyPair: 293 caPrivateKey = kp.PrivateKey 294 case *algo.Ed25519KeyPair: 295 caPrivateKey = kp.PrivateKey 296 default: 297 return nil, fmt.Errorf("unsupported CA key pair type") 298 } 299 300 serialNumber, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128)) 301 if err != nil { 302 return nil, fmt.Errorf("failed to generate serial number: %v", err) 303 } 304 305 if request.ValidFrom.IsZero() { 306 request.ValidFrom = time.Now() 307 } 308 309 if request.ValidFor == 0 { 310 if request.IsCA { 311 request.ValidFor = 5 * 365 * 24 * time.Hour // Default 5 years for intermediate CA 312 } else { 313 request.ValidFor = 365 * 24 * time.Hour // Default 1 year for end-entity 314 } 315 } 316 317 // Determine key usage based on whether this is a CA certificate 318 var keyUsage x509.KeyUsage 319 var extKeyUsage []x509.ExtKeyUsage 320 321 // Check if custom key usage is provided 322 if request.KeyUsage != 0 { 323 keyUsage = request.KeyUsage 324 } else if request.IsCA { 325 // CA certificate - can sign other certificates 326 keyUsage = x509.KeyUsageCertSign | x509.KeyUsageCRLSign | x509.KeyUsageDigitalSignature 327 } else { 328 // End-entity certificate - for TLS/authentication 329 keyUsage = x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature 330 } 331 332 // Check if custom extended key usage is provided 333 if request.ExtKeyUsage != nil { 334 extKeyUsage = request.ExtKeyUsage 335 } else if request.IsCA { 336 // CAs typically don't need extended key usage 337 extKeyUsage = nil 338 } else { 339 // End-entity certificate - for TLS/authentication 340 extKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth} 341 } 342 343 template := x509.Certificate{ 344 SerialNumber: serialNumber, 345 Subject: request.Subject, 346 NotBefore: request.ValidFrom, 347 NotAfter: request.ValidFrom.Add(request.ValidFor), 348 KeyUsage: keyUsage, 349 ExtKeyUsage: extKeyUsage, 350 BasicConstraintsValid: true, 351 IsCA: request.IsCA, 352 DNSNames: request.DNSNames, 353 IPAddresses: request.IPAddresses, 354 EmailAddresses: request.EmailAddress, 355 } 356 357 // Set MaxPathLen for CA certificates 358 if request.IsCA { 359 if request.MaxPathLenZero { 360 template.MaxPathLen = 0 361 template.MaxPathLenZero = true 362 } else if request.MaxPathLen >= 0 { 363 template.MaxPathLen = request.MaxPathLen 364 } 365 // If MaxPathLen is -1, we don't set it (no limit) 366 } 367 368 certDER, err := x509.CreateCertificate(rand.Reader, &template, caCert.Certificate, subjectPublicKey, caPrivateKey) 369 if err != nil { 370 return nil, fmt.Errorf("failed to sign certificate: %v", err) 371 } 372 373 cert, err := x509.ParseCertificate(certDER) 374 if err != nil { 375 return nil, fmt.Errorf("failed to parse signed certificate: %v", err) 376 } 377 378 certPEM := pem.EncodeToMemory(&pem.Block{ 379 Type: "CERTIFICATE", 380 Bytes: certDER, 381 }) 382 383 return &Certificate{ 384 Certificate: cert, 385 PEMData: certPEM, 386 DERData: certDER, 387 }, nil 388 } 389 390 // SaveToFile saves the certificate to a file in PEM format. 391 // The file will be created with 0600 permissions (readable/writable by owner only). 392 // 393 // Example: 394 // 395 // err := certificate.SaveToFile("certificate.pem") 396 func (c *Certificate) SaveToFile(filename string) error { 397 return os.WriteFile(filename, c.PEMData, 0600) 398 } 399 400 // LoadCertificateFromFile loads a certificate from a PEM-formatted file. 401 // The function reads the file and parses the PEM data to create a Certificate object 402 // with both PEM and DER data populated. 403 // 404 // Example: 405 // 406 // certificate, err := LoadCertificateFromFile("certificate.pem") 407 func LoadCertificateFromFile(filename string) (*Certificate, error) { 408 pemData, err := os.ReadFile(filename) 409 if err != nil { 410 return nil, fmt.Errorf("failed to load PEM data: %v", err) 411 } 412 413 return ParseCertificateFromPEM(pemData) 414 } 415 416 // ParseCertificateFromPEM parses a certificate from PEM-encoded data. 417 // The function decodes the PEM block and creates a Certificate object with both 418 // PEM and DER data populated. 419 // 420 // The PEM data should contain a "CERTIFICATE" block: 421 // 422 // -----BEGIN CERTIFICATE----- 423 // ...base64 encoded certificate data... 424 // -----END CERTIFICATE----- 425 // 426 // Example: 427 // 428 // certificate, err := ParseCertificateFromPEM(pemBytes) 429 func ParseCertificateFromPEM(pemData []byte) (*Certificate, error) { 430 block, _ := pem.Decode(pemData) 431 if block == nil { 432 return nil, fmt.Errorf("failed to decode PEM block") 433 } 434 435 if block.Type != "CERTIFICATE" { 436 return nil, fmt.Errorf("invalid PEM block type: %s, expected CERTIFICATE", block.Type) 437 } 438 439 cert, err := x509.ParseCertificate(block.Bytes) 440 if err != nil { 441 return nil, fmt.Errorf("failed to parse certificate: %v", err) 442 } 443 444 return &Certificate{ 445 Certificate: cert, 446 PEMData: pemData, 447 DERData: block.Bytes, // DER data is in the PEM block's Bytes 448 }, nil 449 } 450 451 // VerifyCertificate verifies that a certificate was signed by a Certificate Authority (CA). 452 // It checks the certificate's signature against the provided CA certificate and validates 453 // the certificate chain. 454 // 455 // The function performs the following verifications: 456 // - Signature verification using the CA's public key 457 // - Certificate validity period (not expired) 458 // - Certificate chain validation 459 // 460 // Example: 461 // 462 // err := VerifyCertificate(serverCert, caCert) 463 // if err != nil { 464 // log.Printf("Certificate verification failed: %v", err) 465 // } 466 func VerifyCertificate(cert *Certificate, caCert *Certificate) error { 467 roots := x509.NewCertPool() 468 roots.AddCert(caCert.Certificate) 469 470 opts := x509.VerifyOptions{ 471 Roots: roots, 472 } 473 474 _, err := cert.Certificate.Verify(opts) 475 if err != nil { 476 return fmt.Errorf("certificate verification failed: %v", err) 477 } 478 479 return nil 480 } 481 482 // DER Format Support Functions 483 484 // SaveToDERFile saves the certificate to a file in DER (binary) format. 485 // The file will be created with 0600 permissions (readable/writable by owner only). 486 // DER format is more compact than PEM (typically 30% smaller) and faster to parse. 487 // 488 // Example: 489 // 490 // err := certificate.SaveToDERFile("certificate.der") 491 func (c *Certificate) SaveToDERFile(filename string) error { 492 return os.WriteFile(filename, c.DERData, 0600) 493 } 494 495 // LoadCertificateFromDERFile loads a certificate from a DER-formatted file. 496 // The function reads the binary DER file and creates a Certificate object with both 497 // PEM and DER data populated. 498 // 499 // Example: 500 // 501 // certificate, err := LoadCertificateFromDERFile("certificate.der") 502 func LoadCertificateFromDERFile(filename string) (*Certificate, error) { 503 derData, err := os.ReadFile(filename) 504 if err != nil { 505 return nil, fmt.Errorf("failed to load DER data: %v", err) 506 } 507 508 return ParseCertificateFromDER(derData) 509 } 510 511 // ParseCertificateFromDER parses a certificate from DER-encoded (binary) data. 512 // The function parses the binary ASN.1 data and creates a Certificate object with both 513 // PEM and DER data populated. 514 // 515 // Example: 516 // 517 // certificate, err := ParseCertificateFromDER(derBytes) 518 func ParseCertificateFromDER(derData []byte) (*Certificate, error) { 519 cert, err := x509.ParseCertificate(derData) 520 if err != nil { 521 return nil, fmt.Errorf("failed to parse DER certificate: %v", err) 522 } 523 524 // Convert DER to PEM for consistency 525 certPEM := pem.EncodeToMemory(&pem.Block{ 526 Type: "CERTIFICATE", 527 Bytes: derData, 528 }) 529 530 return &Certificate{ 531 Certificate: cert, 532 PEMData: certPEM, 533 DERData: derData, 534 }, nil 535 } 536 537 // ToDER returns the DER-encoded (binary) certificate data. 538 // DER format is more compact than PEM and suitable for binary storage or transmission. 539 // 540 // Example: 541 // 542 // derData := certificate.ToDER() 543 // fmt.Printf("Certificate size: %d bytes\n", len(derData)) 544 func (c *Certificate) ToDER() []byte { 545 return c.DERData 546 } 547 548 // ToPEM returns the PEM-encoded (Base64 text) certificate data. 549 // PEM format is human-readable and widely supported by certificate management tools. 550 // The returned data includes the "-----BEGIN CERTIFICATE-----" and "-----END CERTIFICATE-----" headers. 551 // 552 // Example: 553 // 554 // pemData := certificate.ToPEM() 555 // fmt.Printf("Certificate in PEM format:\n%s", pemData) 556 func (c *Certificate) ToPEM() []byte { 557 return c.PEMData 558 } 559 560 // ConvertPEMToDER converts PEM-encoded certificate data to DER (binary) format. 561 // This function extracts the Base64-decoded certificate data from PEM format, 562 // removing the headers and returning the raw binary DER data. 563 // 564 // The conversion results in a smaller file size (typically 30% reduction) and 565 // faster parsing compared to PEM format. 566 // 567 // Example: 568 // 569 // derData, err := ConvertPEMToDER(pemBytes) 570 // if err != nil { 571 // log.Fatal("Conversion failed:", err) 572 // } 573 func ConvertPEMToDER(pemData []byte) ([]byte, error) { 574 block, _ := pem.Decode(pemData) 575 if block == nil { 576 return nil, fmt.Errorf("failed to decode PEM block") 577 } 578 579 if block.Type != "CERTIFICATE" { 580 return nil, fmt.Errorf("invalid PEM block type: %s, expected CERTIFICATE", block.Type) 581 } 582 583 return block.Bytes, nil 584 } 585 586 // ConvertDERToPEM converts DER-encoded (binary) certificate data to PEM format. 587 // This function validates the DER certificate data and wraps it in PEM headers 588 // with Base64 encoding for text-based storage and transmission. 589 // 590 // The resulting PEM format is human-readable and compatible with most certificate 591 // management tools and applications. 592 // 593 // Example: 594 // 595 // pemData, err := ConvertDERToPEM(derBytes) 596 // if err != nil { 597 // log.Fatal("Conversion failed:", err) 598 // } 599 // fmt.Printf("Certificate in PEM format:\n%s", pemData) 600 func ConvertDERToPEM(derData []byte) ([]byte, error) { 601 // Validate that this is a valid certificate 602 _, err := x509.ParseCertificate(derData) 603 if err != nil { 604 return nil, fmt.Errorf("invalid DER certificate data: %v", err) 605 } 606 607 certPEM := pem.EncodeToMemory(&pem.Block{ 608 Type: "CERTIFICATE", 609 Bytes: derData, 610 }) 611 612 return certPEM, nil 613 }