github.com/jasoet/gopki@v1.15.0/examples/certificates/doc.md (about)

     1  # Certificate Module Documentation
     2  
     3  Complete documentation for the GoPKI Certificate module, demonstrating X.509 certificate creation, management, and PKI operations.
     4  
     5  ## Table of Contents
     6  - [Overview](#overview)
     7  - [Core Certificate Operations](#core-certificate-operations)
     8  - [Advanced CA Hierarchies](#advanced-ca-hierarchies)
     9  - [Multi-Algorithm Support](#multi-algorithm-support)
    10  - [Subject Alternative Names (SAN)](#subject-alternative-names-san)
    11  - [Format Operations](#format-operations)
    12  - [PKCS#12 Integration](#pkcs12-integration)
    13  - [Certificate Validation](#certificate-validation)
    14  - [Integration & Best Practices](#integration--best-practices)
    15  
    16  ## Overview
    17  
    18  The Certificate module provides comprehensive X.509 certificate creation and management capabilities with type-safe integration across all supported cryptographic algorithms. It supports the complete PKI lifecycle from root CA creation to end-entity certificate validation.
    19  
    20  ### Key Design Principles
    21  - **Type Safety**: Seamless integration with keypair module's generic constraints
    22  - **PKI Hierarchy Support**: Root CA → Intermediate CA → End-entity chains
    23  - **Algorithm Agnostic**: Works with RSA, ECDSA, and Ed25519 keys
    24  - **Format Flexibility**: PEM and DER formats with conversion capabilities
    25  - **Enterprise Ready**: PKCS#12 integration, path length constraints, comprehensive SAN support
    26  
    27  ## Core Certificate Operations
    28  
    29  ### 1. Self-Signed Certificates
    30  Self-signed certificates are certificates signed by their own private key, typically used for testing, development, or root CA certificates.
    31  
    32  ```go
    33  import (
    34      "github.com/jasoet/gopki/cert"
    35      "github.com/jasoet/gopki/keypair/algo"
    36  )
    37  
    38  // Generate key pair
    39  keyPair, err := algo.GenerateRSAKeyPair(algo.KeySize2048)
    40  
    41  // Create certificate request
    42  request := cert.CertificateRequest{
    43      Subject: pkix.Name{
    44          Country:            []string{"US"},
    45          Organization:       []string{"GoPKI Examples Inc"},
    46          OrganizationalUnit: []string{"IT Department"},
    47          CommonName:         "GoPKI Self-Signed Certificate",
    48      },
    49      DNSNames:    []string{"localhost", "example.com"},
    50      IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1)},
    51      ValidFrom:   time.Now(),
    52      ValidFor:    365 * 24 * time.Hour, // 1 year
    53  }
    54  
    55  // Create self-signed certificate
    56  certificate, err := cert.CreateSelfSignedCertificate(keyPair, request)
    57  
    58  // Save certificate
    59  err = certificate.SaveToFile("self_signed.pem")
    60  ```
    61  
    62  **Features:**
    63  - Generic support for all key algorithms (RSA, ECDSA, Ed25519)
    64  - Full Subject Alternative Name (SAN) support
    65  - Customizable validity periods
    66  - Automatic key usage assignment (KeyEncipherment + DigitalSignature)
    67  
    68  ### 2. Certificate Authority (CA) Certificates
    69  CA certificates can sign other certificates and are essential for PKI hierarchies.
    70  
    71  ```go
    72  // Create CA certificate request
    73  caRequest := cert.CertificateRequest{
    74      Subject: pkix.Name{
    75          Country:      []string{"US"},
    76          Organization: []string{"GoPKI Root CA"},
    77          CommonName:   "GoPKI Root Certificate Authority",
    78      },
    79      IsCA:       true,
    80      MaxPathLen: 2, // Allow up to 2 intermediate CAs
    81      ValidFrom:  time.Now(),
    82      ValidFor:   10 * 365 * 24 * time.Hour, // 10 years
    83  }
    84  
    85  // Create CA certificate
    86  caCert, err := cert.CreateCACertificate(caKeyPair, caRequest)
    87  ```
    88  
    89  **CA-Specific Features:**
    90  - **Path Length Constraints**: Control intermediate CA depth
    91    - `MaxPathLen > 0`: Allow N intermediate CA levels
    92    - `MaxPathLen = 0`: Can only sign end-entity certificates
    93    - `MaxPathLen = -1`: No path length limit
    94  - **Key Usage**: Automatic CertSign + CRLSign + DigitalSignature
    95  - **BasicConstraints**: CA=true extension added automatically
    96  
    97  ### 3. Certificate Signing
    98  Sign certificates using a CA certificate and private key.
    99  
   100  ```go
   101  // Create server certificate request
   102  serverRequest := cert.CertificateRequest{
   103      Subject: pkix.Name{
   104          Country:      []string{"US"},
   105          Organization: []string{"GoPKI Web Services"},
   106          CommonName:   "api.gopki.example.com",
   107      },
   108      DNSNames:     []string{"api.gopki.example.com", "www.gopki.example.com"},
   109      IPAddresses:  []net.IP{net.IPv4(192, 168, 1, 100)},
   110      EmailAddress: []string{"admin@gopki.example.com"},
   111      ValidFrom:    time.Now(),
   112      ValidFor:     365 * 24 * time.Hour, // 1 year
   113  }
   114  
   115  // Sign certificate with CA
   116  serverCert, err := cert.SignCertificate(caCert, caKeyPair, serverRequest, &serverKeyPair.PrivateKey.PublicKey)
   117  ```
   118  
   119  **Signing Features:**
   120  - Supports signing both end-entity and intermediate CA certificates
   121  - Automatic key usage determination based on `IsCA` flag
   122  - Certificate chain validation during signing
   123  - Full SAN support for server certificates
   124  
   125  ## Advanced CA Hierarchies
   126  
   127  ### Multi-Level Certificate Chains
   128  Create sophisticated PKI hierarchies with proper path length constraint enforcement.
   129  
   130  ```go
   131  // Root CA (MaxPathLen=2)
   132  rootCA := createRootCA(MaxPathLen: 2)
   133  
   134  // Intermediate CA (MaxPathLen=0 - can only sign end-entity certs)
   135  intermediateRequest := cert.CertificateRequest{
   136      Subject: pkix.Name{
   137          CommonName: "GoPKI Intermediate Certificate Authority",
   138      },
   139      IsCA:       true,
   140      MaxPathLen: 0, // Can only sign end-entity certificates
   141      ValidFor:   5 * 365 * 24 * time.Hour, // 5 years
   142  }
   143  
   144  intermediateCert, err := cert.SignCertificate(rootCA, rootCAKey, intermediateRequest, &intermediateKeyPair.PrivateKey.PublicKey)
   145  
   146  // End-entity certificate signed by intermediate CA
   147  endEntityCert, err := cert.SignCertificate(intermediateCert, intermediateKeyPair, endEntityRequest, endEntityKeyPair.PublicKey)
   148  ```
   149  
   150  ### Path Length Constraint Enforcement
   151  The module automatically enforces path length constraints:
   152  
   153  ```go
   154  // This will FAIL - intermediate CA with MaxPathLen=0 cannot sign another CA
   155  anotherIntermediateRequest := cert.CertificateRequest{
   156      Subject: pkix.Name{CommonName: "Another Intermediate CA"},
   157      IsCA:    true,
   158  }
   159  
   160  // Results in error: "path length constraint violated"
   161  _, err := cert.SignCertificate(intermediateCert, intermediateKeyPair, anotherIntermediateRequest, &anotherKeyPair.PrivateKey.PublicKey)
   162  ```
   163  
   164  **Certificate Chain Structure:**
   165  ```
   166  Root CA (MaxPathLen=2)
   167  ├── Intermediate CA (MaxPathLen=0)
   168  │   ├── End-Entity Certificate
   169  │   └── End-Entity Certificate
   170  └── Another Intermediate CA (MaxPathLen=0)
   171      ├── End-Entity Certificate
   172      └── End-Entity Certificate
   173  ```
   174  
   175  ## Multi-Algorithm Support
   176  
   177  ### RSA Certificate Variants
   178  Support for multiple RSA key sizes with security recommendations.
   179  
   180  ```go
   181  // RSA 2048-bit (minimum recommended)
   182  rsa2048Keys, _ := algo.GenerateRSAKeyPair(algo.KeySize2048)
   183  rsa2048Cert, _ := cert.CreateSelfSignedCertificate(rsa2048Keys, request)
   184  
   185  // RSA 3072-bit (recommended for high security)
   186  rsa3072Keys, _ := algo.GenerateRSAKeyPair(algo.KeySize3072)
   187  rsa3072Cert, _ := cert.CreateSelfSignedCertificate(rsa3072Keys, request)
   188  
   189  // RSA 4096-bit (maximum security)
   190  rsa4096Keys, _ := algo.GenerateRSAKeyPair(algo.KeySize4096)
   191  rsa4096Cert, _ := cert.CreateSelfSignedCertificate(rsa4096Keys, request)
   192  ```
   193  
   194  ### ECDSA Certificate Variants
   195  Support for all NIST P-curves with different security levels.
   196  
   197  ```go
   198  // ECDSA P-224 (224-bit, ~2048-bit RSA equivalent)
   199  p224Keys, _ := algo.GenerateECDSAKeyPair(algo.P224)
   200  p224Cert, _ := cert.CreateSelfSignedCertificate(p224Keys, request)
   201  
   202  // ECDSA P-256 (256-bit, ~3072-bit RSA equivalent) - RECOMMENDED
   203  p256Keys, _ := algo.GenerateECDSAKeyPair(algo.P256)
   204  p256Cert, _ := cert.CreateSelfSignedCertificate(p256Keys, request)
   205  
   206  // ECDSA P-384 (384-bit, ~7680-bit RSA equivalent)
   207  p384Keys, _ := algo.GenerateECDSAKeyPair(algo.P384)
   208  p384Cert, _ := cert.CreateSelfSignedCertificate(p384Keys, request)
   209  
   210  // ECDSA P-521 (521-bit, ~15360-bit RSA equivalent)
   211  p521Keys, _ := algo.GenerateECDSAKeyPair(algo.P521)
   212  p521Cert, _ := cert.CreateSelfSignedCertificate(p521Keys, request)
   213  ```
   214  
   215  ### Ed25519 Certificates
   216  Modern elliptic curve cryptography with excellent performance.
   217  
   218  ```go
   219  // Ed25519 (fixed 256-bit, high security + performance)
   220  ed25519Keys, _ := algo.GenerateEd25519KeyPair("")
   221  ed25519Cert, _ := cert.CreateSelfSignedCertificate(ed25519Keys, request)
   222  ```
   223  
   224  ### Algorithm Performance Comparison
   225  Relative performance for certificate creation:
   226  
   227  | Algorithm | Key Generation | Certificate Creation | Total Time | Security Level |
   228  |-----------|----------------|---------------------|------------|----------------|
   229  | Ed25519 | Fastest | Fastest | ~0.02ms | High |
   230  | ECDSA P-256 | Fast | Fast | ~0.05ms | High |
   231  | ECDSA P-384 | Medium | Medium | ~0.10ms | Very High |
   232  | RSA 2048 | Slow | Medium | ~15ms | Medium |
   233  | RSA 3072 | Very Slow | Medium | ~35ms | High |
   234  | RSA 4096 | Slowest | Medium | ~80ms | Very High |
   235  
   236  ## Subject Alternative Names (SAN)
   237  
   238  ### Complex SAN Combinations
   239  Support for multiple DNS names, IP addresses, and email addresses in a single certificate.
   240  
   241  ```go
   242  request := cert.CertificateRequest{
   243      Subject: pkix.Name{
   244          CommonName: "multi-domain.gopki.example.com",
   245      },
   246      // Multiple DNS names including wildcards
   247      DNSNames: []string{
   248          "multi-domain.gopki.example.com",
   249          "api.gopki.example.com",
   250          "www.gopki.example.com",
   251          "admin.gopki.example.com",
   252          "*.staging.gopki.example.com", // Wildcard domain
   253          "localhost",
   254      },
   255      // Multiple IP addresses (IPv4 and IPv6)
   256      IPAddresses: []net.IP{
   257          net.IPv4(127, 0, 0, 1),     // localhost
   258          net.IPv4(192, 168, 1, 100), // private network
   259          net.IPv4(10, 0, 0, 50),     // another private network
   260          net.ParseIP("::1"),         // IPv6 localhost
   261          net.ParseIP("2001:db8::1"), // IPv6 example
   262      },
   263      // Multiple email addresses
   264      EmailAddress: []string{
   265          "admin@gopki.example.com",
   266          "support@gopki.example.com",
   267          "security@gopki.example.com",
   268      },
   269      ValidFor: 2 * 365 * 24 * time.Hour, // 2 years
   270  }
   271  ```
   272  
   273  ### Domain-Specific SAN Patterns
   274  
   275  #### Web Server Certificate Pattern
   276  ```go
   277  webServerSAN := []string{
   278      "example.com",
   279      "www.example.com",
   280      "api.example.com",
   281      "cdn.example.com",
   282  }
   283  ```
   284  
   285  #### API Service Certificate Pattern
   286  ```go
   287  apiServiceSAN := []string{
   288      "api.service.internal",
   289      "api-v1.service.internal",
   290      "api-v2.service.internal",
   291      "*.microservice.internal",
   292  }
   293  ```
   294  
   295  #### Development Certificate Pattern
   296  ```go
   297  developmentSAN := []string{
   298      "localhost",
   299      "dev.local",
   300      "*.dev.local",
   301      "test.local",
   302  }
   303  ```
   304  
   305  ## Format Operations
   306  
   307  ### PEM vs DER Format Comparison
   308  The module supports both PEM (ASCII) and DER (binary) formats with automatic conversion.
   309  
   310  ```go
   311  // Save in both formats
   312  certificate.SaveToFile("cert.pem")        // PEM format
   313  certificate.SaveToDERFile("cert.der")     // DER format
   314  
   315  // Format conversion
   316  pemData := certificate.ToPEM()
   317  derData := certificate.ToDER()
   318  
   319  // Convert between formats
   320  derData, err := cert.ConvertPEMToDER(pemData)
   321  pemData, err := cert.ConvertDERToPEM(derData)
   322  ```
   323  
   324  **Format Characteristics:**
   325  - **PEM Format**: Human-readable, Base64-encoded, ~33% larger
   326  - **DER Format**: Binary, compact, ~30% smaller, faster parsing
   327  - **Use Cases**:
   328    - PEM: Configuration files, manual inspection, wide compatibility
   329    - DER: Performance-critical applications, binary storage, mobile apps
   330  
   331  ### Format Loading and Parsing
   332  ```go
   333  // Load from files
   334  pemCert, err := cert.LoadCertificateFromFile("cert.pem")
   335  derCert, err := cert.LoadCertificateFromDERFile("cert.der")
   336  
   337  // Parse from data
   338  pemCert, err := cert.ParseCertificateFromPEM(pemData)
   339  derCert, err := cert.ParseCertificateFromDER(derData)
   340  ```
   341  
   342  ### Performance Comparison
   343  Based on 100 parsing iterations:
   344  - **DER parsing**: ~2-3x faster than PEM
   345  - **File size**: DER is ~30% smaller than PEM
   346  - **Memory usage**: DER requires less memory for parsing
   347  
   348  ## PKCS#12 Integration
   349  
   350  ### Certificate Bundle Creation
   351  PKCS#12 format allows bundling certificates and private keys in a single, password-protected file.
   352  
   353  ```go
   354  import "github.com/jasoet/gopki/pkcs12"
   355  
   356  // Save certificate and private key to PKCS#12
   357  password := "secure-password-123"
   358  err := pkcs12.SaveCertToP12(certificate, privateKey, "certificate.p12", password)
   359  ```
   360  
   361  ### Certificate Chain Bundles
   362  Include certificate chains in PKCS#12 bundles for complete trust chain distribution.
   363  
   364  ```go
   365  // Create certificate chain array
   366  caCerts := []*cert.Certificate{rootCA, intermediateCA}
   367  
   368  // Save certificate with full chain
   369  chainPassword := "chain-password-456"
   370  err := pkcs12.SaveCertToP12WithChain(
   371      certificate,
   372      privateKey,
   373      caCerts,
   374      "certificate_with_chain.p12",
   375      chainPassword
   376  )
   377  ```
   378  
   379  ### Loading and Extraction
   380  ```go
   381  // Load certificate from PKCS#12
   382  loadedCert, caCerts, err := pkcs12.FromP12CertFile("certificate.p12", password)
   383  
   384  // Load full certificate chain
   385  certChain, err := pkcs12.LoadCertificateChainFromP12("certificate_with_chain.p12", chainPassword)
   386  
   387  // Extract to PEM files
   388  err = pkcs12.ExtractCertificatesFromP12("certificate.p12", password, "output/")
   389  ```
   390  
   391  ### PKCS#12 Validation and Metadata
   392  ```go
   393  // Validate PKCS#12 file and extract metadata
   394  metadata, err := pkcs12.ValidateP12Certificate("certificate.p12", password)
   395  
   396  // Metadata includes:
   397  // - Certificate count
   398  // - Private key presence
   399  // - CA certificate count
   400  // - Certificate subjects and issuers
   401  // - Validity periods
   402  ```
   403  
   404  ## Certificate Validation
   405  
   406  ### Certificate Chain Validation
   407  Verify certificate chains using the built-in validation engine.
   408  
   409  ```go
   410  // Verify server certificate against CA
   411  err := cert.VerifyCertificate(serverCert, caCert)
   412  if err != nil {
   413      // Validation failed - certificate is invalid
   414  } else {
   415      // Certificate is valid and properly signed
   416  }
   417  ```
   418  
   419  **Validation Checks:**
   420  - **Signature Verification**: Verify certificate signature using CA's public key
   421  - **Certificate Chain**: Validate the complete certificate chain
   422  - **Validity Period**: Check certificate is within valid time range
   423  - **Certificate Extensions**: Verify critical extensions are properly set
   424  
   425  ### Certificate Expiration Checking
   426  ```go
   427  now := time.Now()
   428  cert := certificate.Certificate
   429  
   430  if now.Before(cert.NotBefore) {
   431      // Certificate not yet valid
   432  } else if now.After(cert.NotAfter) {
   433      // Certificate expired
   434  } else {
   435      // Certificate is currently valid
   436      daysLeft := int(cert.NotAfter.Sub(now).Hours() / 24)
   437      fmt.Printf("Certificate valid for %d more days\n", daysLeft)
   438  }
   439  ```
   440  
   441  ### Certificate Information Extraction
   442  Extract detailed certificate information for analysis and monitoring.
   443  
   444  ```go
   445  cert := certificate.Certificate
   446  
   447  // Basic information
   448  serialNumber := cert.SerialNumber.String()
   449  signatureAlgorithm := cert.SignatureAlgorithm.String()
   450  publicKeyAlgorithm := cert.PublicKeyAlgorithm.String()
   451  version := cert.Version
   452  isCA := cert.IsCA
   453  
   454  // Subject Alternative Names
   455  dnsNames := cert.DNSNames
   456  ipAddresses := cert.IPAddresses
   457  emailAddresses := cert.EmailAddresses
   458  
   459  // Fingerprint calculation (example)
   460  fingerprint := sha256.Sum256(cert.Raw)
   461  ```
   462  
   463  ### Invalid Certificate Testing
   464  Test certificate validation with various invalid scenarios to ensure proper security.
   465  
   466  ```go
   467  // Create an invalid self-signed certificate
   468  invalidCert, _ := cert.CreateSelfSignedCertificate(invalidKeyPair, invalidRequest)
   469  
   470  // Try to validate against CA (should fail)
   471  err := cert.VerifyCertificate(invalidCert, caCert)
   472  if err != nil {
   473      // Correctly rejected invalid certificate
   474  } else {
   475      // ERROR: Invalid certificate was incorrectly accepted
   476  }
   477  ```
   478  
   479  ## Integration & Best Practices
   480  
   481  ### Certificate-KeyPair Integration
   482  Seamless integration with the keypair module's type-safe APIs.
   483  
   484  ```go
   485  // All algorithms work identically
   486  algorithms := []func() (interface{}, error){
   487      func() (interface{}, error) { return algo.GenerateRSAKeyPair(algo.KeySize2048) },
   488      func() (interface{}, error) { return algo.GenerateECDSAKeyPair(algo.P256) },
   489      func() (interface{}, error) { return algo.GenerateEd25519KeyPair("") },
   490  }
   491  
   492  for _, genFunc := range algorithms {
   493      keyPair, _ := genFunc()
   494  
   495      // Type-safe certificate creation works with any key type
   496      switch kp := keyPair.(type) {
   497      case *algo.RSAKeyPair:
   498          cert, _ := cert.CreateSelfSignedCertificate(kp, request)
   499      case *algo.ECDSAKeyPair:
   500          cert, _ := cert.CreateSelfSignedCertificate(kp, request)
   501      case *algo.Ed25519KeyPair:
   502          cert, _ := cert.CreateSelfSignedCertificate(kp, request)
   503      }
   504  }
   505  ```
   506  
   507  ### Real-World TLS Server Setup
   508  Complete production-ready TLS server certificate configuration.
   509  
   510  ```go
   511  serverRequest := cert.CertificateRequest{
   512      Subject: pkix.Name{
   513          Country:            []string{"US"},
   514          Province:           []string{"California"},
   515          Locality:           []string{"San Francisco"},
   516          Organization:       []string{"Production Services"},
   517          OrganizationalUnit: []string{"Web Services"},
   518          CommonName:         "api.production.example.com",
   519      },
   520      DNSNames: []string{
   521          "api.production.example.com",
   522          "www.production.example.com",
   523          "cdn.production.example.com",
   524          "admin.production.example.com",
   525      },
   526      IPAddresses: []net.IP{
   527          net.IPv4(203, 0, 113, 10), // Public IP
   528          net.IPv4(203, 0, 113, 11), // Load balancer IP
   529      },
   530      EmailAddress: []string{
   531          "admin@production.example.com",
   532          "security@production.example.com",
   533      },
   534      ValidFor: 2 * 365 * 24 * time.Hour, // 2 years
   535  }
   536  
   537  // Sign with production CA
   538  serverCert, err := cert.SignCertificate(productionCA, caPrivateKey, serverRequest, &serverKeyPair.PrivateKey.PublicKey)
   539  ```
   540  
   541  ### Certificate Analytics and Monitoring
   542  Track certificate collections for operational insights.
   543  
   544  ```go
   545  // Certificate collection analytics
   546  type CertificateAnalytics struct {
   547      TotalCertificates    int
   548      CACertificates      int
   549      SelfSignedCerts     int
   550      EndEntityCerts      int
   551      AlgorithmCounts     map[string]int
   552      ExpiringCerts       []*cert.Certificate // Expiring within 30 days
   553      ExpiredCerts        []*cert.Certificate
   554  }
   555  
   556  // Analyze certificate directory
   557  analytics := AnalyzeCertificateCollection("output/")
   558  ```
   559  
   560  ### Security Best Practices
   561  
   562  #### Algorithm Selection
   563  ```go
   564  // RECOMMENDED: Use ECDSA P-256 or Ed25519 for new certificates
   565  preferredKeyPair, _ := algo.GenerateECDSAKeyPair(algo.P256)
   566  // OR
   567  modernKeyPair, _ := algo.GenerateEd25519KeyPair("")
   568  
   569  // ACCEPTABLE: RSA 2048+ for compatibility requirements
   570  compatKeyPair, _ := algo.GenerateRSAKeyPair(algo.KeySize3072)
   571  ```
   572  
   573  #### CA Hierarchy Design
   574  ```go
   575  // Proper CA hierarchy with path length constraints
   576  rootCA := createCA(MaxPathLen: 2)           // Can sign 2 levels of intermediate CAs
   577  intermediateCA := createCA(MaxPathLen: 0)   // Can only sign end-entity certificates
   578  endEntityCert := signEndEntity()            // Cannot sign other certificates
   579  ```
   580  
   581  #### Certificate Validity Periods
   582  ```go
   583  // Recommended validity periods
   584  const (
   585      RootCAValidity        = 20 * 365 * 24 * time.Hour  // 20 years
   586      IntermediateCAValidity = 10 * 365 * 24 * time.Hour  // 10 years
   587      ServerCertValidity     = 2 * 365 * 24 * time.Hour   // 2 years
   588      ClientCertValidity     = 1 * 365 * 24 * time.Hour   // 1 year
   589  )
   590  ```
   591  
   592  #### File Security
   593  ```go
   594  // Certificates saved with appropriate permissions
   595  certificate.SaveToFile("cert.pem")     // 0644 (world readable)
   596  privateKey.SaveToFile("key.pem")       // 0600 (owner only)
   597  p12Bundle.SaveToFile("bundle.p12")     // 0600 (owner only)
   598  ```
   599  
   600  ### Performance Recommendations
   601  
   602  #### Format Selection
   603  - **PEM**: Use for configuration files, human inspection, wide compatibility
   604  - **DER**: Use for performance-critical applications, binary storage, mobile apps
   605  - **PKCS#12**: Use for secure distribution, enterprise environments
   606  
   607  #### Certificate Storage
   608  ```go
   609  // For high-performance applications, prefer DER format
   610  certificate.SaveToDERFile("high_perf_cert.der")
   611  
   612  // For configuration and compatibility, use PEM
   613  certificate.SaveToFile("config_cert.pem")
   614  
   615  // For secure distribution with private keys, use PKCS#12
   616  pkcs12.SaveCertToP12(cert, privateKey, "secure_bundle.p12", password)
   617  ```
   618  
   619  #### Caching Strategies
   620  ```go
   621  // Cache parsed certificates to avoid repeated parsing
   622  type CertificateCache struct {
   623      cache map[string]*cert.Certificate
   624      mutex sync.RWMutex
   625  }
   626  
   627  func (c *CertificateCache) GetCertificate(path string) (*cert.Certificate, error) {
   628      c.mutex.RLock()
   629      if cached, exists := c.cache[path]; exists {
   630          c.mutex.RUnlock()
   631          return cached, nil
   632      }
   633      c.mutex.RUnlock()
   634  
   635      // Load and cache certificate
   636      certificate, err := cert.LoadCertificateFromFile(path)
   637      if err != nil {
   638          return nil, err
   639      }
   640  
   641      c.mutex.Lock()
   642      c.cache[path] = certificate
   643      c.mutex.Unlock()
   644  
   645      return certificate, nil
   646  }
   647  ```
   648  
   649  ### Error Handling Patterns
   650  
   651  ```go
   652  // Comprehensive error handling for certificate operations
   653  certificate, err := cert.CreateSelfSignedCertificate(keyPair, request)
   654  if err != nil {
   655      switch {
   656      case errors.Is(err, cert.ErrInvalidKeyPair):
   657          return fmt.Errorf("invalid key pair: %w", err)
   658      case errors.Is(err, cert.ErrInvalidCertificateRequest):
   659          return fmt.Errorf("invalid certificate request: %w", err)
   660      case errors.Is(err, cert.ErrCertificateCreationFailed):
   661          return fmt.Errorf("certificate creation failed: %w", err)
   662      default:
   663          return fmt.Errorf("unexpected error: %w", err)
   664      }
   665  }
   666  
   667  // Validation error handling
   668  err = cert.VerifyCertificate(serverCert, caCert)
   669  if err != nil {
   670      switch {
   671      case errors.Is(err, cert.ErrCertificateExpired):
   672          log.Printf("Certificate expired: %v", err)
   673      case errors.Is(err, cert.ErrInvalidSignature):
   674          log.Printf("Invalid certificate signature: %v", err)
   675      case errors.Is(err, cert.ErrUnknownCA):
   676          log.Printf("Unknown certificate authority: %v", err)
   677      default:
   678          log.Printf("Certificate validation failed: %v", err)
   679      }
   680  }
   681  ```
   682  
   683  ---
   684  
   685  For complete working examples demonstrating all these features, see the `main.go` file in this directory.
   686  For integration with other modules, see the main project [README](../../README.md).