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

     1  # PKCS#12 Module Documentation
     2  
     3  ## Overview
     4  
     5  The PKCS#12 module provides comprehensive utilities for creating and parsing PKCS#12 files (also known as P12 or PFX files). PKCS#12 is a binary format defined in RFC 7292 for storing cryptographic objects including private keys, certificates, and certificate chains in a single password-protected file.
     6  
     7  This module integrates seamlessly with the GoPKI ecosystem, providing type-safe operations for certificate and key bundling while maintaining compatibility with standard PKCS#12 implementations across different platforms and applications.
     8  
     9  ## Table of Contents
    10  
    11  - [Key Features](#key-features)
    12  - [Use Cases](#use-cases)
    13  - [API Reference](#api-reference)
    14  - [Quick Start](#quick-start)
    15  - [Advanced Usage](#advanced-usage)
    16  - [Security Considerations](#security-considerations)
    17  - [Integration Guide](#integration-guide)
    18  - [Best Practices](#best-practices)
    19  - [Troubleshooting](#troubleshooting)
    20  
    21  ## Key Features
    22  
    23  ### ✅ **Comprehensive Format Support**
    24  - Create P12 files from private keys and certificates
    25  - Parse existing P12 files to extract cryptographic materials
    26  - Support for certificate chains and multiple certificates
    27  - Compatible with all major platforms (Windows, macOS, Linux)
    28  
    29  ### ✅ **Multi-Algorithm Support**
    30  - **RSA**: 2048+ bit keys (recommended for web servers)
    31  - **ECDSA**: All standard curves (P-224, P-256, P-384, P-521)
    32  - **Ed25519**: Modern high-performance algorithm
    33  
    34  ### ✅ **Type-Safe Integration**
    35  - Seamless integration with `keypair.Manager`
    36  - Works with all GoPKI certificate types
    37  - Generic function signatures prevent runtime type errors
    38  - Compile-time safety for all operations
    39  
    40  ### ✅ **Security Features**
    41  - Password protection with configurable encryption
    42  - Configurable iteration counts for key strengthening
    43  - Friendly names for certificate identification
    44  - Validation and verification of P12 contents
    45  
    46  ### ✅ **Developer Experience**
    47  - Quick utility functions for common operations
    48  - Comprehensive error handling and validation
    49  - Test P12 generation for development
    50  - Extensive documentation and examples
    51  
    52  ## Use Cases
    53  
    54  ### 🌐 **Web Server Deployment**
    55  Bundle web server certificates with their private keys for easy deployment across different web servers (Apache, Nginx, IIS).
    56  
    57  ```go
    58  // Create web server certificate bundle
    59  err := pkcs12.CreateP12File("webserver.p12", privateKey, serverCert,
    60      []*x509.Certificate{intermediateCert}, pkcs12.CreateOptions{
    61          Password: "secure_password",
    62          FriendlyName: "Web Server Certificate",
    63          Iterations: 4096,
    64      })
    65  ```
    66  
    67  ### 🔐 **Client Authentication**
    68  Create client certificates for mutual TLS authentication in enterprise applications.
    69  
    70  ```go
    71  // Create client authentication certificate
    72  err := pkcs12.QuickCreateP12("client.p12", "password", clientKey, clientCert)
    73  ```
    74  
    75  ### 📱 **Cross-Platform Migration**
    76  Export certificates from one system and import them into another, maintaining compatibility across different operating systems and applications.
    77  
    78  ### 🔒 **Code Signing**
    79  Bundle code signing certificates for software distribution and application signing.
    80  
    81  ### 🏢 **Enterprise PKI**
    82  Distribute employee certificates and corporate CA certificates in a standardized format.
    83  
    84  ## API Reference
    85  
    86  ### Core Functions
    87  
    88  #### `CreateP12File[T keypair.PrivateKey](filename, privateKey, certificate, caCerts, opts) error`
    89  
    90  Creates a PKCS#12 file with full control over options.
    91  
    92  **Parameters:**
    93  - `filename`: Output file path
    94  - `privateKey`: Private key (RSA, ECDSA, or Ed25519)
    95  - `certificate`: Primary certificate
    96  - `caCerts`: Optional CA certificate chain
    97  - `opts`: Creation options (password, friendly name, iterations)
    98  
    99  **Returns:** Error if creation fails
   100  
   101  #### `LoadFromP12File(filename, opts) (*P12Container, error)`
   102  
   103  Loads and parses a PKCS#12 file.
   104  
   105  **Parameters:**
   106  - `filename`: P12 file path
   107  - `opts`: Load options (password, trusted certificates)
   108  
   109  **Returns:** P12Container with parsed contents or error
   110  
   111  #### `QuickCreateP12[T keypair.PrivateKey](filename, password, privateKey, certificate) error`
   112  
   113  Convenience function for simple P12 creation with default options.
   114  
   115  #### `QuickLoadP12(filename, password) (*P12Container, error)`
   116  
   117  Convenience function for simple P12 loading with minimal configuration.
   118  
   119  ### Container Operations
   120  
   121  #### `P12Container.Validate() error`
   122  
   123  Validates the integrity of the P12 container and its contents.
   124  
   125  #### `P12Container.ExtractCertificateChain() []*x509.Certificate`
   126  
   127  Extracts the complete certificate chain from the container.
   128  
   129  #### `P12Container.GetKeyType() string`
   130  
   131  Returns the type of private key contained in the P12 file.
   132  
   133  ### Configuration Types
   134  
   135  #### `CreateOptions`
   136  
   137  ```go
   138  type CreateOptions struct {
   139      Password     string // Password for P12 protection
   140      FriendlyName string // Human-readable certificate name
   141      Iterations   int    // Key derivation iterations (default: 2048)
   142  }
   143  ```
   144  
   145  #### `LoadOptions`
   146  
   147  ```go
   148  type LoadOptions struct {
   149      Password     string              // Password for P12 decryption
   150      TrustedCerts []*x509.Certificate // Additional trusted certificates
   151  }
   152  ```
   153  
   154  ## Quick Start
   155  
   156  ### 1. Basic P12 Creation
   157  
   158  ```go
   159  package main
   160  
   161  import (
   162      "github.com/jasoet/gopki/keypair"
   163      "github.com/jasoet/gopki/keypair/algo"
   164      "github.com/jasoet/gopki/cert"
   165      "github.com/jasoet/gopki/pkcs12"
   166  )
   167  
   168  func main() {
   169      // Generate key pair
   170      manager, _ := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048)
   171  
   172      // Create certificate
   173      certificate, _ := cert.CreateSelfSignedCertificate(manager.KeyPair(), cert.CertificateRequest{
   174          Subject: pkix.Name{CommonName: "example.com"},
   175          ValidFor: 365 * 24 * time.Hour,
   176      })
   177  
   178      // Create P12 file
   179      err := pkcs12.QuickCreateP12("certificate.p12", "password123",
   180          manager.PrivateKey(), certificate.Certificate)
   181      if err != nil {
   182          log.Fatal(err)
   183      }
   184  }
   185  ```
   186  
   187  ### 2. Loading P12 Files
   188  
   189  ```go
   190  // Load P12 file
   191  container, err := pkcs12.QuickLoadP12("certificate.p12", "password123")
   192  if err != nil {
   193      log.Fatal(err)
   194  }
   195  
   196  // Access contents
   197  fmt.Printf("Certificate: %s\n", container.Certificate.Subject.CommonName)
   198  fmt.Printf("Key Type: %s\n", container.GetKeyType())
   199  
   200  // Validate container
   201  if err := container.Validate(); err != nil {
   202      log.Printf("Validation warning: %v", err)
   203  }
   204  ```
   205  
   206  ## Advanced Usage
   207  
   208  ### Certificate Chains
   209  
   210  ```go
   211  // Create P12 with certificate chain
   212  opts := pkcs12.CreateOptions{
   213      Password:     "secure_password",
   214      FriendlyName: "Server with Chain",
   215      Iterations:   4096,
   216  }
   217  
   218  // Include intermediate and root CA certificates
   219  caCerts := []*x509.Certificate{intermediateCert, rootCert}
   220  err := pkcs12.CreateP12File("server_chain.p12", serverKey, serverCert, caCerts, opts)
   221  ```
   222  
   223  ### Custom Security Options
   224  
   225  ```go
   226  // High-security P12 for sensitive applications
   227  highSecurityOpts := pkcs12.CreateOptions{
   228      Password:     "very_long_and_complex_password_2024",
   229      FriendlyName: "High Security Certificate",
   230      Iterations:   16384, // Very high iteration count
   231  }
   232  
   233  err := pkcs12.CreateP12File("high_security.p12", privateKey, certificate, nil, highSecurityOpts)
   234  ```
   235  
   236  ### Integration with KeyPair Manager
   237  
   238  ```go
   239  // Load existing key from PEM and create P12
   240  manager, err := keypair.LoadFromPEM[*algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey]("existing.pem")
   241  if err != nil {
   242      log.Fatal(err)
   243  }
   244  
   245  // Validate loaded key
   246  if err := manager.Validate(); err != nil {
   247      log.Fatal("Invalid key pair:", err)
   248  }
   249  
   250  // Create P12 from loaded key
   251  err = pkcs12.QuickCreateP12("from_pem.p12", "password",
   252      manager.PrivateKey(), existingCertificate)
   253  ```
   254  
   255  ## Security Considerations
   256  
   257  ### 🔐 **Password Security**
   258  
   259  **Weak Passwords (Avoid):**
   260  - `password123` - Dictionary word with numbers
   261  - `123456` - Sequential numbers
   262  - `qwerty` - Keyboard patterns
   263  
   264  **Strong Passwords (Recommended):**
   265  - `Tr0ub4dor&3` - Mixed case, numbers, symbols
   266  - `correct-horse-battery-staple-2024` - Long passphrase with year
   267  - Use password managers for generated passwords
   268  
   269  ### 🔒 **Iteration Counts**
   270  
   271  | Security Level | Iterations | Use Case |
   272  |---------------|------------|----------|
   273  | **Basic** | 2048 | Development, testing |
   274  | **Standard** | 4096 | Production web services |
   275  | **High** | 8192 | Financial, healthcare |
   276  | **Maximum** | 16384+ | Government, military |
   277  
   278  ### 🛡️ **File Security**
   279  
   280  ```go
   281  // Create P12 with secure file permissions
   282  err := pkcs12.CreateP12File("secure.p12", privateKey, cert, nil, opts)
   283  if err == nil {
   284      // Set restrictive permissions (owner read/write only)
   285      os.Chmod("secure.p12", 0600)
   286  }
   287  ```
   288  
   289  ### ⚠️ **Common Security Mistakes**
   290  
   291  1. **Weak Passwords**: Using easily guessable passwords
   292  2. **Low Iterations**: Using default iteration counts for sensitive data
   293  3. **Insecure Storage**: Storing P12 files with world-readable permissions
   294  4. **Password Reuse**: Using the same password for multiple P12 files
   295  5. **No Validation**: Skipping container validation after creation/loading
   296  
   297  ## Integration Guide
   298  
   299  ### With KeyPair Manager
   300  
   301  ```go
   302  // Generate key with Manager
   303  manager, _ := keypair.Generate[algo.ECDSACurve, *algo.ECDSAKeyPair, *ecdsa.PrivateKey, *ecdsa.PublicKey](algo.P256)
   304  
   305  // Get key information
   306  info, _ := manager.GetInfo()
   307  fmt.Printf("Algorithm: %s, Curve: %s\n", info.Algorithm, info.Curve)
   308  
   309  // Create P12
   310  err := pkcs12.QuickCreateP12("ecdsa.p12", "password", manager.PrivateKey(), certificate)
   311  ```
   312  
   313  ### With Certificate Module
   314  
   315  ```go
   316  // Create CA hierarchy
   317  caCert, _ := cert.CreateCACertificate(caKeys, caRequest)
   318  intermediateCert, _ := cert.SignCertificate(caCert, caKeys, intermediateRequest, intermediatePublicKey)
   319  serverCert, _ := cert.SignCertificate(intermediateCert, intermediateKeys, serverRequest, serverPublicKey)
   320  
   321  // Bundle with complete chain
   322  chain := []*x509.Certificate{intermediateCert.Certificate, caCert.Certificate}
   323  err := pkcs12.CreateP12File("server_with_chain.p12", serverKey, serverCert.Certificate, chain, opts)
   324  ```
   325  
   326  ### Cross-Format Workflows
   327  
   328  ```go
   329  // PEM → P12 → DER workflow
   330  // 1. Load from PEM
   331  manager, _ := keypair.LoadFromPEM[*algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey]("input.pem")
   332  
   333  // 2. Create P12
   334  pkcs12.QuickCreateP12("output.p12", "password", manager.PrivateKey(), certificate)
   335  
   336  // 3. Save as DER
   337  manager.SaveToDER("output.der", "output_public.der")
   338  ```
   339  
   340  ## Best Practices
   341  
   342  ### 📋 **Development Workflow**
   343  
   344  1. **Use KeyPair Manager** for consistent key management
   345  2. **Validate all inputs** before creating P12 files
   346  3. **Test with different passwords** and iteration counts
   347  4. **Use QuickCreateP12** for simple use cases
   348  5. **Use CreateP12File** when you need full control
   349  
   350  ### 🔧 **Production Deployment**
   351  
   352  1. **Use strong passwords** (see Security Considerations)
   353  2. **Set appropriate iteration counts** based on security requirements
   354  3. **Include certificate chains** for proper validation
   355  4. **Set restrictive file permissions** (0600)
   356  5. **Validate P12 containers** after creation and before deployment
   357  
   358  ### 🧪 **Testing**
   359  
   360  ```go
   361  // Generate test P12 for development
   362  err := pkcs12.GenerateTestP12("test.p12", "test_password")
   363  if err != nil {
   364      t.Fatalf("Failed to generate test P12: %v", err)
   365  }
   366  
   367  // Load and validate
   368  container, err := pkcs12.QuickLoadP12("test.p12", "test_password")
   369  assert.NoError(t, err)
   370  assert.NoError(t, container.Validate())
   371  ```
   372  
   373  ### 📦 **Distribution**
   374  
   375  1. **Document password requirements** for end users
   376  2. **Provide installation instructions** for different platforms
   377  3. **Include certificate chain** for proper trust establishment
   378  4. **Test on target platforms** before distribution
   379  
   380  ## Troubleshooting
   381  
   382  ### Common Errors and Solutions
   383  
   384  #### ❌ **"Invalid password"**
   385  - **Cause**: Wrong password provided
   386  - **Solution**: Verify password is correct, check for typos
   387  
   388  #### ❌ **"Failed to parse P12"**
   389  - **Cause**: Corrupted file or incompatible format
   390  - **Solution**: Re-create P12 file, check file integrity
   391  
   392  #### ❌ **"Certificate validation failed"**
   393  - **Cause**: Missing certificate chain or expired certificates
   394  - **Solution**: Include full certificate chain, check certificate validity
   395  
   396  #### ❌ **"Unsupported key type"**
   397  - **Cause**: Trying to use unsupported private key type
   398  - **Solution**: Use RSA, ECDSA, or Ed25519 keys only
   399  
   400  ### Performance Considerations
   401  
   402  #### **Iteration Count vs. Performance**
   403  
   404  | Iterations | Creation Time | Security Level |
   405  |-----------|---------------|----------------|
   406  | 2048 | ~10ms | Basic |
   407  | 4096 | ~20ms | Standard |
   408  | 8192 | ~40ms | High |
   409  | 16384 | ~80ms | Maximum |
   410  
   411  #### **Optimization Tips**
   412  
   413  1. **Use appropriate iteration counts** - higher isn't always necessary
   414  2. **Cache P12 containers** when loading multiple times
   415  3. **Use QuickCreateP12** for simple use cases to reduce overhead
   416  4. **Validate only when necessary** - skip validation for trusted sources
   417  
   418  ### Platform-Specific Notes
   419  
   420  #### **Windows**
   421  - P12 files can be imported into Windows Certificate Store
   422  - Use `.pfx` extension for better Windows compatibility
   423  - Test with IIS and other Windows applications
   424  
   425  #### **macOS**
   426  - P12 files can be imported into Keychain Access
   427  - Requires admin privileges for system keychain import
   428  - Test with Safari and other macOS applications
   429  
   430  #### **Linux**
   431  - Compatible with OpenSSL and most Linux applications
   432  - Can be converted to PEM format using OpenSSL tools
   433  - Test with Apache, Nginx, and other server software
   434  
   435  ## Example Use Cases
   436  
   437  ### 🌐 **Web Server Certificate**
   438  
   439  ```go
   440  // Create production web server certificate
   441  webOpts := pkcs12.CreateOptions{
   442      Password:     os.Getenv("WEB_CERT_PASSWORD"),
   443      FriendlyName: "Production Web Server - example.com",
   444      Iterations:   4096,
   445  }
   446  
   447  err := pkcs12.CreateP12File("webserver.p12", serverKey, serverCert,
   448      []*x509.Certificate{intermediateCert}, webOpts)
   449  ```
   450  
   451  ### 🔐 **Client Authentication**
   452  
   453  ```go
   454  // Create client authentication certificate for enterprise use
   455  clientOpts := pkcs12.CreateOptions{
   456      Password:     generateSecurePassword(),
   457      FriendlyName: fmt.Sprintf("Employee Certificate - %s", employeeName),
   458      Iterations:   8192, // Higher security for client certs
   459  }
   460  
   461  err := pkcs12.CreateP12File(fmt.Sprintf("client_%s.p12", employeeID),
   462      clientKey, clientCert, []*x509.Certificate{corporateCA}, clientOpts)
   463  ```
   464  
   465  ### 📱 **Code Signing**
   466  
   467  ```go
   468  // Create code signing certificate for software distribution
   469  codeSignOpts := pkcs12.CreateOptions{
   470      Password:     os.Getenv("CODE_SIGN_PASSWORD"),
   471      FriendlyName: "Software Publisher Certificate",
   472      Iterations:   10000, // Maximum security for code signing
   473  }
   474  
   475  err := pkcs12.CreateP12File("codesign.p12", codeSignKey, codeSignCert, nil, codeSignOpts)
   476  ```
   477  
   478  ---
   479  
   480  ## Additional Resources
   481  
   482  - **RFC 7292**: PKCS #12: Personal Information Exchange Syntax v1.1
   483  - **GoPKI Documentation**: See other module documentation for integration examples
   484  - **OpenSSL Compatibility**: P12 files created by this module are compatible with OpenSSL
   485  - **Testing**: Run `go run main.go` in this directory for comprehensive examples
   486  
   487  For more examples and use cases, see the `main.go` file in this directory which demonstrates all aspects of PKCS#12 operations in practical scenarios.