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

     1  // Package pkcs12 provides PKCS#12 (P12) keypair integration for the GoPKI project.
     2  // This file implements P12 import/export functionality with type-safe operations
     3  // that integrate seamlessly with the existing keypair abstractions.
     4  //
     5  // P12 files (PKCS#12) are a standard format for storing cryptographic materials
     6  // including private keys, certificates, and certificate chains in a single
     7  // password-protected file. This implementation provides both generic and
     8  // algorithm-specific functions for maximum flexibility and type safety.
     9  //
    10  // Example usage:
    11  //
    12  //	// Generate a key pair
    13  //	rsaKeys, err := keypair.GenerateKeyPair[algo.KeySize, *algo.RSAKeyPair](2048)
    14  //	if err != nil {
    15  //		log.Fatal(err)
    16  //	}
    17  //
    18  //	// Create a self-signed certificate
    19  //	cert, err := cert.CreateSelfSignedCertificate(rsaKeys, cert.CertificateRequest{
    20  //		Subject: pkix.Name{CommonName: "example.com"},
    21  //		ValidFor: 365 * 24 * time.Hour,
    22  //	})
    23  //	if err != nil {
    24  //		log.Fatal(err)
    25  //	}
    26  //
    27  //	// Export to P12 format
    28  //	p12Data, err := pkcs12.ToP12KeyPair(rsaKeys, cert.Certificate, "password123")
    29  //	if err != nil {
    30  //		log.Fatal(err)
    31  //	}
    32  //
    33  //	// Save to file
    34  //	err = pkcs12.ToP12KeyPairFile(rsaKeys, cert.Certificate, "keystore.p12", "password123")
    35  //	if err != nil {
    36  //		log.Fatal(err)
    37  //	}
    38  //
    39  //	// Load from P12 file
    40  //	loadedKeyPair, loadedCert, caCerts, err := pkcs12.FromP12KeyPairFile[*algo.RSAKeyPair]("keystore.p12", "password123")
    41  //	if err != nil {
    42  //		log.Fatal(err)
    43  //	}
    44  //
    45  // The package supports all key algorithms available in GoPKI:
    46  //   - RSA (2048+ bits recommended)
    47  //   - ECDSA (P-224, P-256, P-384, P-521)
    48  //   - Ed25519
    49  //
    50  // Type-safe algorithm-specific functions are provided for scenarios where
    51  // you know the exact key type:
    52  //   - ToP12RSAKeyPair/FromP12RSAKeyPair for RSA keys
    53  //   - ToP12ECDSAKeyPair/FromP12ECDSAKeyPair for ECDSA keys
    54  //   - ToP12Ed25519KeyPair/FromP12Ed25519KeyPair for Ed25519 keys
    55  package pkcs12
    56  
    57  import (
    58  	"crypto/ecdsa"
    59  	"crypto/ed25519"
    60  	"crypto/rsa"
    61  	"crypto/x509"
    62  	"encoding/pem"
    63  	"fmt"
    64  	"os"
    65  	"path/filepath"
    66  
    67  	"github.com/jasoet/gopki/keypair"
    68  	"github.com/jasoet/gopki/keypair/algo"
    69  )
    70  
    71  // ToP12KeyPair exports a key pair to PKCS#12 format with the given certificate.
    72  //
    73  // This generic function accepts any KeyPair type (RSA, ECDSA, or Ed25519) and
    74  // creates a password-protected P12 byte array containing the private key and
    75  // certificate. The function uses default P12 creation options which provide
    76  // good security for most use cases.
    77  //
    78  // Parameters:
    79  //   - keyPair: The keypair to export (must implement KeyPair interface)
    80  //   - certificate: The X.509 certificate associated with the key pair
    81  //   - password: Password to protect the P12 file (cannot be empty)
    82  //
    83  // Returns:
    84  //   - []byte: The P12 data that can be saved to a file or transmitted
    85  //   - error: Any error that occurred during the export process
    86  //
    87  // Example:
    88  //
    89  //	rsaKeys, _ := keypair.GenerateKeyPair[algo.KeySize, *algo.RSAKeyPair](2048)
    90  //	cert, _ := cert.CreateSelfSignedCertificate(rsaKeys, request)
    91  //	p12Data, err := pkcs12.ToP12KeyPair(rsaKeys, cert.Certificate, "securePassword")
    92  //	if err != nil {
    93  //		log.Fatal("Failed to create P12:", err)
    94  //	}
    95  //
    96  // Security considerations:
    97  //   - Use a strong password as P12 security depends on password strength
    98  //   - The resulting P12 data should be transmitted securely
    99  //   - Consider the sensitivity of the private key material
   100  func ToP12KeyPair[T keypair.KeyPair](keyPair T, certificate *x509.Certificate, password string) ([]byte, error) {
   101  	if keyPair == nil {
   102  		return nil, fmt.Errorf("key pair is required")
   103  	}
   104  	if certificate == nil {
   105  		return nil, fmt.Errorf("certificate is required")
   106  	}
   107  	if password == "" {
   108  		return nil, fmt.Errorf("password is required")
   109  	}
   110  
   111  	// Extract private key from key pair
   112  	// Create P12 with default options
   113  	opts := DefaultCreateOptions(password)
   114  
   115  	switch kp := any(keyPair).(type) {
   116  	case *algo.RSAKeyPair:
   117  		return CreateP12(kp.PrivateKey, certificate, nil, opts)
   118  	case *algo.ECDSAKeyPair:
   119  		return CreateP12(kp.PrivateKey, certificate, nil, opts)
   120  	case *algo.Ed25519KeyPair:
   121  		return CreateP12(kp.PrivateKey, certificate, nil, opts)
   122  	default:
   123  		return nil, fmt.Errorf("unsupported key pair type: %T", keyPair)
   124  	}
   125  }
   126  
   127  // ToP12KeyPairFile exports a key pair and certificate to a PKCS#12 file.
   128  //
   129  // This is a convenience function that wraps ToP12KeyPair and writes the result
   130  // directly to a file. The file will be created with appropriate permissions
   131  // (0600) to protect the private key material.
   132  //
   133  // Parameters:
   134  //   - keyPair: The keypair to export (any KeyPair type)
   135  //   - certificate: The X.509 certificate associated with the key pair
   136  //   - filename: Path where the P12 file should be created
   137  //   - password: Password to protect the P12 file
   138  //
   139  // Returns:
   140  //   - error: Any error that occurred during export or file creation
   141  //
   142  // Example:
   143  //
   144  //	err := pkcs12.ToP12KeyPairFile(keyPair, cert.Certificate, "/path/to/keystore.p12", "password")
   145  //	if err != nil {
   146  //		log.Fatal("Failed to save P12 file:", err)
   147  //	}
   148  //
   149  // The function will create any necessary parent directories and set
   150  // restrictive file permissions to protect the private key.
   151  func ToP12KeyPairFile[T keypair.KeyPair](keyPair T, certificate *x509.Certificate, filename, password string) error {
   152  	if keyPair == nil {
   153  		return fmt.Errorf("key pair is required")
   154  	}
   155  	if certificate == nil {
   156  		return fmt.Errorf("certificate is required")
   157  	}
   158  
   159  	// Create P12 file with default options
   160  	opts := DefaultCreateOptions(password)
   161  
   162  	switch kp := any(keyPair).(type) {
   163  	case *algo.RSAKeyPair:
   164  		return CreateP12File(filename, kp.PrivateKey, certificate, nil, opts)
   165  	case *algo.ECDSAKeyPair:
   166  		return CreateP12File(filename, kp.PrivateKey, certificate, nil, opts)
   167  	case *algo.Ed25519KeyPair:
   168  		return CreateP12File(filename, kp.PrivateKey, certificate, nil, opts)
   169  	default:
   170  		return fmt.Errorf("unsupported key pair type: %T", keyPair)
   171  	}
   172  }
   173  
   174  // FromP12KeyPair loads a key pair from PKCS#12 data.
   175  //
   176  // This generic function parses P12 binary data and extracts the private key, certificate,
   177  // and any CA certificates. The private key is automatically converted to the
   178  // appropriate GoPKI KeyPair type based on its algorithm.
   179  //
   180  // Type Parameters:
   181  //   - T: The expected KeyPair type (*algo.RSAKeyPair, *algo.ECDSAKeyPair, or *algo.Ed25519KeyPair)
   182  //
   183  // Parameters:
   184  //   - p12Data: The P12 binary data to parse
   185  //   - password: Password to decrypt the P12 data
   186  //
   187  // Returns:
   188  //   - T: The extracted key pair of the specified type
   189  //   - *x509.Certificate: The main certificate from the P12
   190  //   - []*x509.Certificate: Any CA certificates included in the P12
   191  //   - error: Any error that occurred during parsing
   192  //
   193  // Example:
   194  //
   195  //	p12Data, _ := os.ReadFile("keystore.p12")
   196  //	keyPair, cert, caCerts, err := pkcs12.FromP12KeyPair[*algo.RSAKeyPair](p12Data, "password")
   197  //	if err != nil {
   198  //		log.Fatal("Failed to parse P12:", err)
   199  //	}
   200  //	fmt.Printf("RSA key size: %d bits\n", keyPair.PrivateKey.N.BitLen())
   201  //
   202  // The function automatically detects the key algorithm and returns the
   203  // appropriate GoPKI KeyPair type for seamless integration with other
   204  // GoPKI functions.
   205  func FromP12KeyPair[T keypair.KeyPair](p12Data []byte, password string) (T, *x509.Certificate, []*x509.Certificate, error) {
   206  	var zero T
   207  	if len(p12Data) == 0 {
   208  		return zero, nil, nil, fmt.Errorf("P12 data is required")
   209  	}
   210  	if password == "" {
   211  		return zero, nil, nil, fmt.Errorf("password is required")
   212  	}
   213  
   214  	// Parse P12 data
   215  	opts := DefaultLoadOptions(password)
   216  	container, err := ParseP12(p12Data, opts)
   217  	if err != nil {
   218  		return zero, nil, nil, fmt.Errorf("failed to parse P12 data: %w", err)
   219  	}
   220  
   221  	// Convert to keypair based on private key type
   222  	keyPair, err := createKeyPairFromPrivateKeyAny(container.PrivateKey)
   223  	if err != nil {
   224  		return zero, nil, nil, fmt.Errorf("failed to create key pair: %w", err)
   225  	}
   226  
   227  	// Type assert to the expected type
   228  	typedKeyPair, ok := keyPair.(T)
   229  	if !ok {
   230  		return zero, nil, nil, fmt.Errorf("expected key pair type %T, got %T", zero, keyPair)
   231  	}
   232  
   233  	return typedKeyPair, container.Certificate, container.CACertificates, nil
   234  }
   235  
   236  // FromP12KeyPairFile loads a key pair from a PKCS#12 file.
   237  //
   238  // This generic function loads P12 file and extracts the private key, certificate,
   239  // and any CA certificates. The private key is automatically converted to the
   240  // appropriate GoPKI KeyPair type based on its algorithm.
   241  //
   242  // Type Parameters:
   243  //   - T: The expected KeyPair type (*algo.RSAKeyPair, *algo.ECDSAKeyPair, or *algo.Ed25519KeyPair)
   244  //
   245  // Parameters:
   246  //   - filename: Path to the P12 file to load
   247  //   - password: Password to decrypt the P12 file
   248  //
   249  // Returns:
   250  //   - T: The extracted key pair of the specified type
   251  //   - *x509.Certificate: The main certificate from the P12
   252  //   - []*x509.Certificate: Any CA certificates included in the P12
   253  //   - error: Any error that occurred during loading
   254  //
   255  // Example:
   256  //
   257  //	keyPair, cert, caCerts, err := pkcs12.FromP12KeyPairFile[*algo.RSAKeyPair]("keystore.p12", "password")
   258  //	if err != nil {
   259  //		log.Fatal("Failed to load P12 file:", err)
   260  //	}
   261  func FromP12KeyPairFile[T keypair.KeyPair](filename, password string) (T, *x509.Certificate, []*x509.Certificate, error) {
   262  	var zero T
   263  	if filename == "" {
   264  		return zero, nil, nil, fmt.Errorf("filename is required")
   265  	}
   266  	if password == "" {
   267  		return zero, nil, nil, fmt.Errorf("password is required")
   268  	}
   269  
   270  	// Load P12 file
   271  	opts := DefaultLoadOptions(password)
   272  	container, err := LoadFromP12File(filename, opts)
   273  	if err != nil {
   274  		return zero, nil, nil, fmt.Errorf("failed to load P12 file: %w", err)
   275  	}
   276  
   277  	// Convert to keypair based on private key type
   278  	keyPair, err := createKeyPairFromPrivateKeyAny(container.PrivateKey)
   279  	if err != nil {
   280  		return zero, nil, nil, fmt.Errorf("failed to create key pair: %w", err)
   281  	}
   282  
   283  	// Type assert to the expected type
   284  	typedKeyPair, ok := keyPair.(T)
   285  	if !ok {
   286  		return zero, nil, nil, fmt.Errorf("expected key pair type %T, got %T", zero, keyPair)
   287  	}
   288  
   289  	return typedKeyPair, container.Certificate, container.CACertificates, nil
   290  }
   291  
   292  // Type-specific P12 functions for better type safety
   293  //
   294  // The following functions provide algorithm-specific P12 operations with
   295  // compile-time type safety. Use these when you know the exact key algorithm
   296  // and want stronger type guarantees.
   297  
   298  // ToP12RSAKeyPair exports an RSA key pair to PKCS#12 format.
   299  //
   300  // This is a type-safe wrapper around ToP12KeyPair specifically for RSA keys.
   301  // Use this when you have an RSA key pair and want compile-time type safety.
   302  //
   303  // Parameters:
   304  //   - keyPair: The RSA key pair to export
   305  //   - certificate: The X.509 certificate for the RSA key
   306  //   - password: Password to protect the P12 file
   307  //
   308  // Returns:
   309  //   - []byte: The P12 data containing the RSA key and certificate
   310  //   - error: Any error that occurred during export
   311  func ToP12RSAKeyPair(keyPair *algo.RSAKeyPair, certificate *x509.Certificate, password string) ([]byte, error) {
   312  	return ToP12KeyPair(keyPair, certificate, password)
   313  }
   314  
   315  // ToP12ECDSAKeyPair exports an ECDSA key pair to PKCS#12 format.
   316  //
   317  // Type-safe wrapper for ECDSA keys supporting all curves (P-224, P-256, P-384, P-521).
   318  func ToP12ECDSAKeyPair(keyPair *algo.ECDSAKeyPair, certificate *x509.Certificate, password string) ([]byte, error) {
   319  	return ToP12KeyPair(keyPair, certificate, password)
   320  }
   321  
   322  // ToP12Ed25519KeyPair exports an Ed25519 key pair to PKCS#12 format.
   323  //
   324  // Type-safe wrapper for Ed25519 keys, providing modern elliptic curve cryptography.
   325  func ToP12Ed25519KeyPair(keyPair *algo.Ed25519KeyPair, certificate *x509.Certificate, password string) ([]byte, error) {
   326  	return ToP12KeyPair(keyPair, certificate, password)
   327  }
   328  
   329  // FromP12RSAKeyPair loads an RSA key pair from PKCS#12 data
   330  func FromP12RSAKeyPair(p12Data []byte, password string) (*algo.RSAKeyPair, *x509.Certificate, []*x509.Certificate, error) {
   331  	return FromP12KeyPair[*algo.RSAKeyPair](p12Data, password)
   332  }
   333  
   334  // FromP12ECDSAKeyPair loads an ECDSA key pair from PKCS#12 data
   335  func FromP12ECDSAKeyPair(p12Data []byte, password string) (*algo.ECDSAKeyPair, *x509.Certificate, []*x509.Certificate, error) {
   336  	return FromP12KeyPair[*algo.ECDSAKeyPair](p12Data, password)
   337  }
   338  
   339  // FromP12Ed25519KeyPair loads an Ed25519 key pair from PKCS#12 data
   340  func FromP12Ed25519KeyPair(p12Data []byte, password string) (*algo.Ed25519KeyPair, *x509.Certificate, []*x509.Certificate, error) {
   341  	return FromP12KeyPair[*algo.Ed25519KeyPair](p12Data, password)
   342  }
   343  
   344  // ExportKeyPairWithChain exports a key pair with a certificate chain to P12 format
   345  func ExportKeyPairWithChain[T keypair.KeyPair](keyPair T, certificate *x509.Certificate, caCerts []*x509.Certificate, filename, password string) error {
   346  	if keyPair == nil {
   347  		return fmt.Errorf("key pair is required")
   348  	}
   349  	if certificate == nil {
   350  		return fmt.Errorf("certificate is required")
   351  	}
   352  
   353  	// Create P12 with certificate chain
   354  	opts := DefaultCreateOptions(password)
   355  	opts.IncludeChain = true
   356  
   357  	switch kp := any(keyPair).(type) {
   358  	case *algo.RSAKeyPair:
   359  		return CreateP12File(filename, kp.PrivateKey, certificate, caCerts, opts)
   360  	case *algo.ECDSAKeyPair:
   361  		return CreateP12File(filename, kp.PrivateKey, certificate, caCerts, opts)
   362  	case *algo.Ed25519KeyPair:
   363  		return CreateP12File(filename, kp.PrivateKey, certificate, caCerts, opts)
   364  	default:
   365  		return fmt.Errorf("unsupported key pair type: %T", keyPair)
   366  	}
   367  }
   368  
   369  // ImportFromP12KeyPairWithValidation imports a key pair from P12 with comprehensive validation.
   370  //
   371  // This generic function loads P12 file with comprehensive validation including
   372  // certificate chain validation and expiration checking.
   373  //
   374  // Type Parameters:
   375  //   - T: The expected KeyPair type (*algo.RSAKeyPair, *algo.ECDSAKeyPair, or *algo.Ed25519KeyPair)
   376  //
   377  // Parameters:
   378  //   - filename: Path to the P12 file to load
   379  //   - password: Password to decrypt the P12 file
   380  //
   381  // Returns:
   382  //   - T: The extracted key pair of the specified type
   383  //   - *x509.Certificate: The main certificate from the P12
   384  //   - []*x509.Certificate: Any CA certificates included in the P12
   385  //   - error: Any error that occurred during loading or validation
   386  //
   387  // Example:
   388  //
   389  //	keyPair, cert, caCerts, err := pkcs12.ImportFromP12KeyPairWithValidation[*algo.RSAKeyPair]("keystore.p12", "password")
   390  //	if err != nil {
   391  //		log.Fatal("Failed to load and validate P12 file:", err)
   392  //	}
   393  func ImportFromP12KeyPairWithValidation[T keypair.KeyPair](filename, password string) (T, *x509.Certificate, []*x509.Certificate, error) {
   394  	var zero T
   395  	// Load with validation enabled
   396  	opts := DefaultLoadOptions(password)
   397  	opts.ValidateChain = true
   398  	opts.CheckExpiration = true
   399  
   400  	container, err := LoadFromP12File(filename, opts)
   401  	if err != nil {
   402  		return zero, nil, nil, fmt.Errorf("failed to load and validate P12: %w", err)
   403  	}
   404  
   405  	// Convert to keypair
   406  	keyPair, err := createKeyPairFromPrivateKeyAny(container.PrivateKey)
   407  	if err != nil {
   408  		return zero, nil, nil, fmt.Errorf("failed to create key pair: %w", err)
   409  	}
   410  
   411  	// Type assert to the expected type
   412  	typedKeyPair, ok := keyPair.(T)
   413  	if !ok {
   414  		return zero, nil, nil, fmt.Errorf("expected key pair type %T, got %T", zero, keyPair)
   415  	}
   416  
   417  	return typedKeyPair, container.Certificate, container.CACertificates, nil
   418  }
   419  
   420  // ConvertP12KeyPairToPEM converts a P12 file to separate PEM files.
   421  // This function automatically detects the key pair type in the P12 file.
   422  func ConvertP12KeyPairToPEM(p12File, password, privateKeyFile, certFile string) error {
   423  	// Read P12 file
   424  	p12Data, err := os.ReadFile(p12File)
   425  	if err != nil {
   426  		return fmt.Errorf("failed to read P12 file: %w", err)
   427  	}
   428  
   429  	// Try each key pair type until one works
   430  	var keyPair any
   431  	var cert *x509.Certificate
   432  
   433  	// Try RSA first
   434  	if rsaKeyPair, rsaCert, _, rsaErr := FromP12RSAKeyPair(p12Data, password); rsaErr == nil {
   435  		keyPair = rsaKeyPair
   436  		cert = rsaCert
   437  	} else {
   438  		// Try ECDSA
   439  		if ecdsaKeyPair, ecdsaCert, _, ecdsaErr := FromP12ECDSAKeyPair(p12Data, password); ecdsaErr == nil {
   440  			keyPair = ecdsaKeyPair
   441  			cert = ecdsaCert
   442  		} else {
   443  			// Try Ed25519
   444  			if ed25519KeyPair, ed25519Cert, _, ed25519Err := FromP12Ed25519KeyPair(p12Data, password); ed25519Err == nil {
   445  				keyPair = ed25519KeyPair
   446  				cert = ed25519Cert
   447  			} else {
   448  				return fmt.Errorf("failed to load P12 with any key type - RSA: %v, ECDSA: %v, Ed25519: %v", rsaErr, ecdsaErr, ed25519Err)
   449  			}
   450  		}
   451  	}
   452  
   453  	// Save as PEM files
   454  	if privateKeyFile != "" {
   455  		// Convert keyPair back to the correct type for ToFiles
   456  		switch kp := keyPair.(type) {
   457  		case *algo.RSAKeyPair:
   458  			if err := keypair.ToPEMFiles(kp, privateKeyFile, privateKeyFile+".pub"); err != nil {
   459  				return fmt.Errorf("failed to save RSA key pair to PEM: %w", err)
   460  			}
   461  		case *algo.ECDSAKeyPair:
   462  			if err := keypair.ToPEMFiles(kp, privateKeyFile, privateKeyFile+".pub"); err != nil {
   463  				return fmt.Errorf("failed to save ECDSA key pair to PEM: %w", err)
   464  			}
   465  		case *algo.Ed25519KeyPair:
   466  			if err := keypair.ToPEMFiles(kp, privateKeyFile, privateKeyFile+".pub"); err != nil {
   467  				return fmt.Errorf("failed to save Ed25519 key pair to PEM: %w", err)
   468  			}
   469  		default:
   470  			return fmt.Errorf("unsupported key pair type for PEM conversion: %T", keyPair)
   471  		}
   472  	}
   473  
   474  	if certFile != "" {
   475  		// Save certificate to PEM file
   476  		if err := saveCertificateToPEM(cert, certFile); err != nil {
   477  			return fmt.Errorf("failed to save certificate to PEM: %w", err)
   478  		}
   479  	}
   480  
   481  	return nil
   482  }
   483  
   484  // createKeyPairFromPrivateKeyAny creates a keypair from any private key type
   485  func createKeyPairFromPrivateKeyAny(privateKey keypair.GenericPrivateKey) (any, error) {
   486  	switch priv := privateKey.(type) {
   487  	case *rsa.PrivateKey:
   488  		return createKeyPairFromPrivateKey(priv)
   489  	case *ecdsa.PrivateKey:
   490  		return createKeyPairFromPrivateKey(priv)
   491  	case ed25519.PrivateKey:
   492  		return createKeyPairFromPrivateKey(priv)
   493  	default:
   494  		return nil, fmt.Errorf("unsupported private key type for keypair creation: %T", privateKey)
   495  	}
   496  }
   497  
   498  // Helper function to create key pair from private key
   499  func createKeyPairFromPrivateKey[T keypair.PrivateKey](privateKey T) (any, error) {
   500  	switch priv := any(privateKey).(type) {
   501  	case *rsa.PrivateKey:
   502  		return &algo.RSAKeyPair{
   503  			PrivateKey: priv,
   504  			PublicKey:  &priv.PublicKey,
   505  		}, nil
   506  	case *ecdsa.PrivateKey:
   507  		return &algo.ECDSAKeyPair{
   508  			PrivateKey: priv,
   509  			PublicKey:  &priv.PublicKey,
   510  		}, nil
   511  	case ed25519.PrivateKey:
   512  		publicKey := priv.Public().(ed25519.PublicKey)
   513  		return &algo.Ed25519KeyPair{
   514  			PrivateKey: priv,
   515  			PublicKey:  publicKey,
   516  		}, nil
   517  	default:
   518  		return nil, fmt.Errorf("unsupported private key type for keypair creation: %T", privateKey)
   519  	}
   520  }
   521  
   522  // saveCertificateToPEM saves a certificate to a PEM file
   523  func saveCertificateToPEM(cert *x509.Certificate, filename string) error {
   524  	if cert == nil {
   525  		return fmt.Errorf("certificate is required")
   526  	}
   527  	if filename == "" {
   528  		return fmt.Errorf("filename is required")
   529  	}
   530  
   531  	// Create directory if it doesn't exist
   532  	dir := filepath.Dir(filename)
   533  	if err := os.MkdirAll(dir, 0700); err != nil {
   534  		return fmt.Errorf("failed to create directory: %w", err)
   535  	}
   536  
   537  	// Encode certificate as PEM
   538  	certPEM := pem.EncodeToMemory(&pem.Block{
   539  		Type:  "CERTIFICATE",
   540  		Bytes: cert.Raw,
   541  	})
   542  
   543  	// Write to file
   544  	if err := os.WriteFile(filename, certPEM, 0644); err != nil {
   545  		return fmt.Errorf("failed to write PEM file: %w", err)
   546  	}
   547  
   548  	return nil
   549  }