github.com/jasoet/gopki@v1.15.0/pkcs12/pkcs12.go (about)

     1  // Package pkcs12 provides comprehensive utilities for creating and parsing PKCS#12 files.
     2  //
     3  // PKCS#12 is a binary format defined in RFC 7292 for storing cryptographic objects
     4  // including private keys, certificates, and certificate chains in a single
     5  // password-protected file. This format is widely used for importing/exporting
     6  // certificates and private keys across different systems and applications.
     7  //
     8  // This package integrates with the existing GoPKI infrastructure to provide
     9  // convenient import/export functionality for certificates and key pairs while
    10  // maintaining compatibility with standard PKCS#12 implementations.
    11  //
    12  // Key features:
    13  //   - Create P12 files from certificates and private keys
    14  //   - Parse P12 files to extract certificates and private keys
    15  //   - Support for certificate chains and multiple certificates
    16  //   - Password protection with configurable encryption algorithms
    17  //   - Type-safe integration with GoPKI keypair and certificate packages
    18  //   - Validation and verification of P12 contents
    19  //   - Quick utility functions for common operations
    20  //   - Test P12 generation for development and testing
    21  //
    22  // Supported algorithms:
    23  //   - RSA private keys (2048+ bits recommended)
    24  //   - ECDSA private keys (all standard curves)
    25  //   - Ed25519 private keys
    26  //   - X.509 certificates and certificate chains
    27  //
    28  // Security considerations:
    29  //   - P12 files are only as secure as their passwords
    30  //   - Use strong passwords for production P12 files
    31  //   - Protect P12 files during transmission and storage
    32  //   - Consider the sensitivity of private key material
    33  //
    34  // Example usage:
    35  //
    36  //	// Basic P12 creation and loading
    37  //	import (
    38  //		"crypto/rsa"
    39  //		"crypto/rand"
    40  //		"github.com/jasoet/gopki/pkcs12"
    41  //	)
    42  //
    43  //	// Generate a test P12 file
    44  //	err := pkcs12.GenerateTestP12("test.p12", "password123")
    45  //	if err != nil {
    46  //		log.Fatal(err)
    47  //	}
    48  //
    49  //	// Load the P12 file
    50  //	container, err := pkcs12.LoadFromP12File("test.p12", pkcs12.DefaultLoadOptions("password123"))
    51  //	if err != nil {
    52  //		log.Fatal(err)
    53  //	}
    54  //
    55  //	// Access the contents
    56  //	fmt.Printf("Key type: %s\n", container.GetKeyType())
    57  //	fmt.Printf("Certificate subject: %s\n", container.Certificate.Subject)
    58  //
    59  //	// Create P12 from existing materials
    60  //	privateKey, _ := rsa.GenerateKey(rand.Reader, 2048)
    61  //	opts := pkcs12.DefaultCreateOptions("newPassword")
    62  //	err = pkcs12.CreateP12File("new.p12", privateKey, certificate, nil, opts)
    63  //
    64  //	// Quick operations
    65  //	container, err = pkcs12.QuickLoadP12("new.p12", "newPassword")
    66  //	err = pkcs12.QuickCreateP12("quick.p12", "password", privateKey, certificate)
    67  //
    68  // Integration with GoPKI:
    69  //
    70  //	This package is designed to work seamlessly with other GoPKI packages.
    71  //	See the keypair/p12.go and cert/p12.go files for type-safe integration
    72  //	functions that leverage the GoPKI keypair and certificate abstractions.
    73  package pkcs12
    74  
    75  import (
    76  	"crypto/rand"
    77  	"crypto/rsa"
    78  	"crypto/x509"
    79  	"crypto/x509/pkix"
    80  	"fmt"
    81  	"math/big"
    82  	"os"
    83  	"path/filepath"
    84  	"reflect"
    85  	"time"
    86  
    87  	"software.sslmate.com/src/go-pkcs12"
    88  
    89  	"github.com/jasoet/gopki/keypair"
    90  )
    91  
    92  // P12Container represents a PKCS#12 container with its contents
    93  type P12Container struct {
    94  	// Private key from the P12 file
    95  	PrivateKey keypair.GenericPrivateKey
    96  	// Primary certificate associated with the private key
    97  	Certificate *x509.Certificate
    98  	// Additional certificates (certificate chain)
    99  	CACertificates []*x509.Certificate
   100  	// Friendly name (if available)
   101  	FriendlyName string
   102  }
   103  
   104  // CreateOptions contains options for creating P12 files
   105  type CreateOptions struct {
   106  	// Password to encrypt the P12 file
   107  	Password string
   108  	// Friendly name for the certificate
   109  	FriendlyName string
   110  	// Include certificate chain
   111  	IncludeChain bool
   112  	// Legacy mode for compatibility with older systems
   113  	LegacyMode bool
   114  	// Additional CA certificates to include
   115  	ExtraCAs []*x509.Certificate
   116  }
   117  
   118  // LoadOptions contains options for loading P12 files
   119  type LoadOptions struct {
   120  	// Password to decrypt the P12 file
   121  	Password string
   122  	// Validate certificate chain
   123  	ValidateChain bool
   124  	// Check certificate expiration
   125  	CheckExpiration bool
   126  }
   127  
   128  // DefaultCreateOptions returns sensible default options for creating P12 files.
   129  //
   130  // The default configuration provides good security and compatibility:
   131  //   - Includes certificate chain if provided
   132  //   - Uses modern encryption (not legacy mode)
   133  //   - No friendly name set
   134  //   - No extra CA certificates
   135  //
   136  // Parameters:
   137  //   - password: The password to encrypt the P12 file
   138  //
   139  // Returns:
   140  //   - CreateOptions: A struct with default settings for P12 creation
   141  //
   142  // Example:
   143  //
   144  //	opts := pkcs12.DefaultCreateOptions("strongPassword123")
   145  //	p12Data, err := pkcs12.CreateP12(privateKey, cert, nil, opts)
   146  func DefaultCreateOptions(password string) CreateOptions {
   147  	return CreateOptions{
   148  		Password:     password,
   149  		FriendlyName: "",
   150  		IncludeChain: true,
   151  		LegacyMode:   false,
   152  		ExtraCAs:     nil,
   153  	}
   154  }
   155  
   156  // DefaultLoadOptions returns safe default options for loading P12 files.
   157  //
   158  // The default configuration is optimized for compatibility and speed:
   159  //   - No certificate chain validation (faster loading)
   160  //   - No certificate expiration checking
   161  //   - Basic password decryption only
   162  //
   163  // For production use, consider enabling validation options:
   164  //
   165  //	opts := pkcs12.DefaultLoadOptions("password")
   166  //	opts.ValidateChain = true      // Enable chain validation
   167  //	opts.CheckExpiration = true    // Check certificate expiration
   168  //
   169  // Parameters:
   170  //   - password: The password to decrypt the P12 file
   171  //
   172  // Returns:
   173  //   - LoadOptions: A struct with default settings for P12 loading
   174  func DefaultLoadOptions(password string) LoadOptions {
   175  	return LoadOptions{
   176  		Password:        password,
   177  		ValidateChain:   false,
   178  		CheckExpiration: false,
   179  	}
   180  }
   181  
   182  // CreateP12 creates PKCS#12 binary data from a private key, certificate, and optional chain using type-safe generics.
   183  //
   184  // This is the core function for creating P12 data. It accepts any private key type
   185  // supported by the underlying PKCS#12 library (RSA, ECDSA, Ed25519) and combines
   186  // it with the certificate and optional certificate chain into encrypted P12 data.
   187  //
   188  // Type parameter:
   189  //   - T: Private key type (*rsa.PrivateKey, *ecdsa.PrivateKey, ed25519.PrivateKey)
   190  //
   191  // Parameters:
   192  //   - privateKey: The private key (type-safe generic: *rsa.PrivateKey, *ecdsa.PrivateKey, ed25519.PrivateKey)
   193  //   - certificate: The X.509 certificate associated with the private key
   194  //   - caCerts: Optional certificate chain (can be nil)
   195  //   - opts: Creation options including password and encryption settings
   196  //
   197  // Returns:
   198  //   - []byte: The P12 binary data ready for saving or transmission
   199  //   - error: Any error that occurred during P12 creation
   200  //
   201  // Security notes:
   202  //   - The private key will be encrypted with the provided password
   203  //   - Use strong passwords as P12 security depends on password strength
   204  //   - The resulting data should be transmitted and stored securely
   205  //
   206  // Example:
   207  //
   208  //	opts := pkcs12.DefaultCreateOptions("securePassword")
   209  //	p12Data, err := pkcs12.CreateP12(privateKey, certificate, caCertChain, opts)
   210  //	if err != nil {
   211  //		log.Fatal("Failed to create P12:", err)
   212  //	}
   213  //	// Save to file or transmit securely
   214  //	os.WriteFile("certificate.p12", p12Data, 0600)
   215  func CreateP12[T keypair.PrivateKey](privateKey T, certificate *x509.Certificate, caCerts []*x509.Certificate, opts CreateOptions) ([]byte, error) {
   216  	// Check for nil private key using reflection
   217  	if any(privateKey) == nil || reflect.ValueOf(privateKey).IsNil() {
   218  		return nil, fmt.Errorf("private key is required")
   219  	}
   220  	if certificate == nil {
   221  		return nil, fmt.Errorf("certificate is required")
   222  	}
   223  	if opts.Password == "" {
   224  		return nil, fmt.Errorf("password is required")
   225  	}
   226  
   227  	// Combine certificate chain if requested
   228  	var allCACerts []*x509.Certificate
   229  	if opts.IncludeChain {
   230  		allCACerts = append(allCACerts, caCerts...)
   231  	}
   232  	if len(opts.ExtraCAs) > 0 {
   233  		allCACerts = append(allCACerts, opts.ExtraCAs...)
   234  	}
   235  
   236  	// Use different encoding based on legacy mode
   237  	if opts.LegacyMode {
   238  		// Use legacy mode for older systems
   239  		return pkcs12.Legacy.Encode(privateKey, certificate, allCACerts, opts.Password)
   240  	} else {
   241  		// Use modern mode (default)
   242  		return pkcs12.Modern.Encode(privateKey, certificate, allCACerts, opts.Password)
   243  	}
   244  }
   245  
   246  // ParseP12 parses PKCS#12 data and returns the private key, certificate, and CA certificates
   247  func ParseP12(p12Data []byte, opts LoadOptions) (*P12Container, error) {
   248  	if len(p12Data) == 0 {
   249  		return nil, fmt.Errorf("P12 data is empty")
   250  	}
   251  	if opts.Password == "" {
   252  		return nil, fmt.Errorf("password is required")
   253  	}
   254  
   255  	// Parse the P12 data
   256  	privateKey, certificate, caCerts, err := pkcs12.DecodeChain(p12Data, opts.Password)
   257  	if err != nil {
   258  		return nil, fmt.Errorf("failed to decode P12 data: %w", err)
   259  	}
   260  
   261  	container := &P12Container{
   262  		PrivateKey:     privateKey,
   263  		Certificate:    certificate,
   264  		CACertificates: caCerts,
   265  	}
   266  
   267  	// Validate certificate chain if requested
   268  	if opts.ValidateChain && len(caCerts) > 0 {
   269  		if err := validateCertificateChain(certificate, caCerts); err != nil {
   270  			return nil, fmt.Errorf("certificate chain validation failed: %w", err)
   271  		}
   272  	}
   273  
   274  	// Check certificate expiration if requested
   275  	if opts.CheckExpiration && certificate != nil {
   276  		if err := validateCertificateExpiration(certificate); err != nil {
   277  			return nil, fmt.Errorf("certificate validation failed: %w", err)
   278  		}
   279  	}
   280  
   281  	return container, nil
   282  }
   283  
   284  // CreateP12File creates a PKCS#12 file from a private key and certificate using type-safe generics.
   285  //
   286  // Type parameter:
   287  //   - T: Private key type (*rsa.PrivateKey, *ecdsa.PrivateKey, ed25519.PrivateKey)
   288  func CreateP12File[T keypair.PrivateKey](filename string, privateKey T, certificate *x509.Certificate, caCerts []*x509.Certificate, opts CreateOptions) error {
   289  	// Create P12 data
   290  	p12Data, err := CreateP12(privateKey, certificate, caCerts, opts)
   291  	if err != nil {
   292  		return fmt.Errorf("failed to create P12 data: %w", err)
   293  	}
   294  
   295  	// Create directory if it doesn't exist
   296  	dir := filepath.Dir(filename)
   297  	if err := os.MkdirAll(dir, 0700); err != nil {
   298  		return fmt.Errorf("failed to create directory %s: %w", dir, err)
   299  	}
   300  
   301  	// Write to file with secure permissions
   302  	if err := os.WriteFile(filename, p12Data, 0600); err != nil {
   303  		return fmt.Errorf("failed to write P12 file %s: %w", filename, err)
   304  	}
   305  
   306  	return nil
   307  }
   308  
   309  // LoadFromP12File loads a PKCS#12 file and returns the container
   310  func LoadFromP12File(filename string, opts LoadOptions) (*P12Container, error) {
   311  	// Read the P12 file
   312  	p12Data, err := os.ReadFile(filename)
   313  	if err != nil {
   314  		return nil, fmt.Errorf("failed to read P12 file %s: %w", filename, err)
   315  	}
   316  
   317  	// Parse the P12 data
   318  	return ParseP12(p12Data, opts)
   319  }
   320  
   321  // Type-safe integration functions with GoPKI packages
   322  
   323  // Note: Integration functions with GoPKI packages are available in separate files
   324  // to avoid import cycles. See keypair/p12.go and cert/p12.go for GoPKI integration.
   325  
   326  // Utility functions for working with P12 containers
   327  
   328  // ExtractCertificateChain extracts the complete certificate chain from a P12 container
   329  func (c *P12Container) ExtractCertificateChain() []*x509.Certificate {
   330  	chain := []*x509.Certificate{c.Certificate}
   331  	chain = append(chain, c.CACertificates...)
   332  	return chain
   333  }
   334  
   335  // GetKeyType returns the type of private key in the container
   336  func (c *P12Container) GetKeyType() string {
   337  	return getPrivateKeyType(c.PrivateKey)
   338  }
   339  
   340  // Validate performs basic validation on the P12 container contents
   341  func (c *P12Container) Validate() error {
   342  	if c.PrivateKey == nil {
   343  		return fmt.Errorf("private key is missing")
   344  	}
   345  	if c.Certificate == nil {
   346  		return fmt.Errorf("certificate is missing")
   347  	}
   348  
   349  	// Validate that private key matches certificate public key
   350  	if err := validateKeyPairMatch(c.PrivateKey, c.Certificate.PublicKey); err != nil {
   351  		return fmt.Errorf("private key does not match certificate: %w", err)
   352  	}
   353  
   354  	return nil
   355  }
   356  
   357  // QuickCreateP12 provides a simple interface for creating P12 files with default options using type-safe generics.
   358  //
   359  // This is a simplified wrapper around CreateP12File that uses default creation
   360  // options. It's perfect for development, testing, or simple use cases where
   361  // you don't need to customize the P12 creation settings.
   362  //
   363  // Type parameter:
   364  //   - T: Private key type (*rsa.PrivateKey, *ecdsa.PrivateKey, ed25519.PrivateKey)
   365  //
   366  // Parameters:
   367  //   - filename: Path where the P12 file will be created
   368  //   - password: Password to protect the P12 file
   369  //   - privateKey: The private key to include
   370  //   - certificate: The certificate to include
   371  //
   372  // Returns:
   373  //   - error: Any error that occurred during creation
   374  //
   375  // Example:
   376  //
   377  //	err := pkcs12.QuickCreateP12("my-cert.p12", "password123", privateKey, certificate)
   378  //	if err != nil {
   379  //		log.Fatal("Failed to create P12:", err)
   380  //	}
   381  func QuickCreateP12[T keypair.PrivateKey](filename, password string, privateKey T, certificate *x509.Certificate) error {
   382  	opts := DefaultCreateOptions(password)
   383  	return CreateP12File(filename, privateKey, certificate, nil, opts)
   384  }
   385  
   386  // QuickLoadP12 provides a simple interface for loading P12 files with default options
   387  func QuickLoadP12(filename, password string) (*P12Container, error) {
   388  	opts := DefaultLoadOptions(password)
   389  	return LoadFromP12File(filename, opts)
   390  }
   391  
   392  // GenerateTestP12 generates a P12 file with a self-signed certificate for testing
   393  func GenerateTestP12(filename, password string) error {
   394  	// Generate RSA key pair using standard library
   395  	privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
   396  	if err != nil {
   397  		return fmt.Errorf("failed to generate private key: %w", err)
   398  	}
   399  
   400  	// Create self-signed certificate template
   401  	template := &x509.Certificate{
   402  		Subject: pkix.Name{
   403  			CommonName:   "Test Certificate",
   404  			Organization: []string{"GoPKI Test"},
   405  			Country:      []string{"US"},
   406  		},
   407  		NotBefore:    time.Now(),
   408  		NotAfter:     time.Now().Add(365 * 24 * time.Hour), // 1 year
   409  		KeyUsage:     x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
   410  		SerialNumber: big.NewInt(1),
   411  	}
   412  
   413  	// Create certificate
   414  	certDER, err := x509.CreateCertificate(rand.Reader, template, template, &privateKey.PublicKey, privateKey)
   415  	if err != nil {
   416  		return fmt.Errorf("failed to create certificate: %w", err)
   417  	}
   418  
   419  	certificate, err := x509.ParseCertificate(certDER)
   420  	if err != nil {
   421  		return fmt.Errorf("failed to parse certificate: %w", err)
   422  	}
   423  
   424  	// Create P12 file
   425  	opts := DefaultCreateOptions(password)
   426  	opts.FriendlyName = "Test Certificate"
   427  
   428  	return CreateP12File(filename, privateKey, certificate, nil, opts)
   429  }