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

     1  //go:build example
     2  
     3  // GoPKI PKCS#12 Examples - Comprehensive demonstration of PKCS#12 functionality
     4  //
     5  // This example demonstrates all aspects of PKCS#12 operations in GoPKI:
     6  // 1. Basic P12 creation with different algorithms
     7  // 2. Advanced P12 operations with certificate chains
     8  // 3. Loading and parsing P12 files
     9  // 4. Integration with other GoPKI modules
    10  // 5. Real-world scenarios and use cases
    11  // 6. Validation and security operations
    12  //
    13  // PKCS#12 is a binary format for storing cryptographic objects including
    14  // private keys, certificates, and certificate chains in a password-protected file.
    15  // It's widely used for importing/exporting certificates across different systems.
    16  
    17  package main
    18  
    19  import (
    20  	"crypto/ecdsa"
    21  	"crypto/ed25519"
    22  	"crypto/rsa"
    23  	"crypto/x509"
    24  	"crypto/x509/pkix"
    25  	"fmt"
    26  	"log"
    27  	"os"
    28  	"path/filepath"
    29  	"time"
    30  
    31  	"github.com/jasoet/gopki/cert"
    32  	"github.com/jasoet/gopki/keypair"
    33  	"github.com/jasoet/gopki/keypair/algo"
    34  	"github.com/jasoet/gopki/pkcs12"
    35  )
    36  
    37  func main() {
    38  	fmt.Println("=== GoPKI PKCS#12 Module - Comprehensive Examples ===")
    39  	fmt.Println("Demonstrating password-protected certificate and key bundling with RFC 7292 compliance")
    40  	fmt.Println()
    41  
    42  	// Setup output directory
    43  	outputDir := "output"
    44  	if err := os.MkdirAll(outputDir, 0755); err != nil {
    45  		log.Fatalf("Failed to create output directory: %v", err)
    46  	}
    47  
    48  	// Part 1: Basic PKCS#12 Creation
    49  	fmt.Println("šŸ” PART 1: Basic PKCS#12 Creation")
    50  	fmt.Println("============================================================")
    51  	runBasicP12Creation(outputDir)
    52  
    53  	// Part 2: Advanced PKCS#12 Operations
    54  	fmt.Println("\nšŸ“¦ PART 2: Advanced PKCS#12 Operations with Certificate Chains")
    55  	fmt.Println("============================================================")
    56  	runAdvancedP12Operations(outputDir)
    57  
    58  	// Part 3: PKCS#12 Loading and Parsing
    59  	fmt.Println("\nšŸ“‚ PART 3: PKCS#12 Loading and Parsing")
    60  	fmt.Println("============================================================")
    61  	runP12LoadingAndParsing(outputDir)
    62  
    63  	// Part 4: Integration with GoPKI Modules
    64  	fmt.Println("\nšŸ”— PART 4: Integration with GoPKI Modules")
    65  	fmt.Println("============================================================")
    66  	runGoPKIIntegration(outputDir)
    67  
    68  	// Part 5: Real-World Scenarios
    69  	fmt.Println("\n🌐 PART 5: Real-World Scenarios")
    70  	fmt.Println("============================================================")
    71  	runRealWorldScenarios(outputDir)
    72  
    73  	// Part 6: Validation and Security
    74  	fmt.Println("\nšŸ›”ļø PART 6: Validation and Security")
    75  	fmt.Println("============================================================")
    76  	runValidationAndSecurity(outputDir)
    77  
    78  	fmt.Println("\n============================================================")
    79  	fmt.Println("āœ… ALL PKCS#12 EXAMPLES COMPLETED!")
    80  	fmt.Printf("šŸ“ Output files saved in: ./%s/\n", outputDir)
    81  	fmt.Println("šŸ” Review P12 files and certificate bundles")
    82  	fmt.Println()
    83  	fmt.Println("šŸ“‹ Summary of Demonstrated Features:")
    84  	fmt.Println("   āœ… Multi-algorithm P12 creation (RSA, ECDSA, Ed25519)")
    85  	fmt.Println("   āœ… Certificate chain bundling and validation")
    86  	fmt.Println("   āœ… Password protection with custom options")
    87  	fmt.Println("   āœ… P12 loading, parsing, and content extraction")
    88  	fmt.Println("   āœ… Integration with keypair Manager and cert modules")
    89  	fmt.Println("   āœ… Real-world use cases (web server, client auth, code signing)")
    90  	fmt.Println("   āœ… Cross-platform certificate migration workflows")
    91  	fmt.Println("   āœ… Security validation and certificate verification")
    92  	fmt.Println("============================================================")
    93  }
    94  
    95  func runBasicP12Creation(outputDir string) {
    96  	fmt.Println("1. RSA Certificate P12 Creation")
    97  	fmt.Println("--------------------------------")
    98  
    99  	// Generate RSA key pair using Manager
   100  	rsaManager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048)
   101  	if err != nil {
   102  		log.Fatalf("Failed to generate RSA key pair: %v", err)
   103  	}
   104  
   105  	fmt.Printf("āœ“ Generated %d-bit RSA key pair using Manager\n", rsaManager.PrivateKey().Size()*8)
   106  
   107  	// Create self-signed certificate
   108  	rsaCert, err := cert.CreateSelfSignedCertificate(rsaManager.KeyPair(), cert.CertificateRequest{
   109  		Subject: pkix.Name{
   110  			CommonName:   "RSA Test Certificate",
   111  			Organization: []string{"GoPKI Examples"},
   112  			Country:      []string{"US"},
   113  		},
   114  		DNSNames: []string{"rsa.example.com"},
   115  		ValidFor: 365 * 24 * time.Hour,
   116  	})
   117  	if err != nil {
   118  		log.Fatalf("Failed to create RSA certificate: %v", err)
   119  	}
   120  
   121  	fmt.Printf("āœ“ Created self-signed certificate for: %s\n", rsaCert.Certificate.Subject.CommonName)
   122  
   123  	// Create P12 file with custom options
   124  	rsaP12Path := filepath.Join(outputDir, "rsa_basic.p12")
   125  	createOpts := pkcs12.DefaultCreateOptions("rsa_secret123")
   126  	createOpts.FriendlyName = "RSA Basic Certificate"
   127  
   128  	err = pkcs12.CreateP12File(rsaP12Path, rsaManager.PrivateKey(), rsaCert.Certificate, nil, createOpts)
   129  	if err != nil {
   130  		log.Fatalf("Failed to create RSA P12 file: %v", err)
   131  	}
   132  
   133  	fmt.Printf("āœ“ Created P12 file: %s\n", rsaP12Path)
   134  	fmt.Printf("  Password: %s\n", createOpts.Password)
   135  	fmt.Printf("  Friendly name: %s\n", createOpts.FriendlyName)
   136  
   137  	// Get file info
   138  	if info, err := os.Stat(rsaP12Path); err == nil {
   139  		fmt.Printf("  File size: %d bytes\n", info.Size())
   140  	}
   141  
   142  	fmt.Println()
   143  
   144  	fmt.Println("2. ECDSA Certificate P12 Creation")
   145  	fmt.Println("----------------------------------")
   146  
   147  	// Generate ECDSA key pair
   148  	ecdsaManager, err := keypair.Generate[algo.ECDSACurve, *algo.ECDSAKeyPair, *ecdsa.PrivateKey, *ecdsa.PublicKey](algo.P256)
   149  	if err != nil {
   150  		log.Fatalf("Failed to generate ECDSA key pair: %v", err)
   151  	}
   152  
   153  	keyInfo, _ := ecdsaManager.GetInfo()
   154  	fmt.Printf("āœ“ Generated ECDSA key pair: %s curve (%d bits)\n", keyInfo.Curve, keyInfo.KeySize)
   155  
   156  	// Create certificate
   157  	ecdsaCert, err := cert.CreateSelfSignedCertificate(ecdsaManager.KeyPair(), cert.CertificateRequest{
   158  		Subject: pkix.Name{
   159  			CommonName:   "ECDSA Test Certificate",
   160  			Organization: []string{"GoPKI Examples"},
   161  		},
   162  		DNSNames: []string{"ecdsa.example.com"},
   163  		ValidFor: 365 * 24 * time.Hour,
   164  	})
   165  	if err != nil {
   166  		log.Fatalf("Failed to create ECDSA certificate: %v", err)
   167  	}
   168  
   169  	// Use QuickCreateP12 for simpler creation
   170  	ecdsaP12Path := filepath.Join(outputDir, "ecdsa_basic.p12")
   171  	err = pkcs12.QuickCreateP12(ecdsaP12Path, "ecdsa_secret123", ecdsaManager.PrivateKey(), ecdsaCert.Certificate)
   172  	if err != nil {
   173  		log.Fatalf("Failed to create ECDSA P12 file: %v", err)
   174  	}
   175  
   176  	fmt.Printf("āœ“ Created P12 file using QuickCreateP12: %s\n", ecdsaP12Path)
   177  	fmt.Println("  Password: ecdsa_secret123")
   178  
   179  	fmt.Println()
   180  
   181  	fmt.Println("3. Ed25519 Certificate P12 Creation")
   182  	fmt.Println("------------------------------------")
   183  
   184  	// Generate Ed25519 key pair
   185  	ed25519Manager, err := keypair.Generate[algo.Ed25519Config, *algo.Ed25519KeyPair, ed25519.PrivateKey, ed25519.PublicKey]("")
   186  	if err != nil {
   187  		log.Fatalf("Failed to generate Ed25519 key pair: %v", err)
   188  	}
   189  
   190  	fmt.Println("āœ“ Generated Ed25519 key pair (256 bits)")
   191  
   192  	// Create certificate
   193  	ed25519Cert, err := cert.CreateSelfSignedCertificate(ed25519Manager.KeyPair(), cert.CertificateRequest{
   194  		Subject: pkix.Name{
   195  			CommonName:   "Ed25519 Test Certificate",
   196  			Organization: []string{"GoPKI Examples"},
   197  		},
   198  		DNSNames: []string{"ed25519.example.com"},
   199  		ValidFor: 365 * 24 * time.Hour,
   200  	})
   201  	if err != nil {
   202  		log.Fatalf("Failed to create Ed25519 certificate: %v", err)
   203  	}
   204  
   205  	// Create P12 with different options
   206  	ed25519P12Path := filepath.Join(outputDir, "ed25519_basic.p12")
   207  	ed25519Opts := pkcs12.DefaultCreateOptions("ed25519_secret123")
   208  	ed25519Opts.FriendlyName = "Ed25519 Modern Certificate"
   209  
   210  	err = pkcs12.CreateP12File(ed25519P12Path, ed25519Manager.PrivateKey(), ed25519Cert.Certificate, nil, ed25519Opts)
   211  	if err != nil {
   212  		log.Fatalf("Failed to create Ed25519 P12 file: %v", err)
   213  	}
   214  
   215  	fmt.Printf("āœ“ Created P12 file: %s\n", ed25519P12Path)
   216  	fmt.Printf("  Password: %s\n", ed25519Opts.Password)
   217  	fmt.Printf("  Friendly name: %s\n", ed25519Opts.FriendlyName)
   218  
   219  	fmt.Println("šŸ’¾ Basic P12 creation completed for all algorithms")
   220  }
   221  
   222  func runAdvancedP12Operations(outputDir string) {
   223  	fmt.Println("1. Certificate Chain P12 Creation")
   224  	fmt.Println("----------------------------------")
   225  
   226  	// Create CA certificate
   227  	caManager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048)
   228  	if err != nil {
   229  		log.Fatalf("Failed to generate CA key pair: %v", err)
   230  	}
   231  
   232  	caCert, err := cert.CreateCACertificate(caManager.KeyPair(), cert.CertificateRequest{
   233  		Subject: pkix.Name{
   234  			CommonName:   "GoPKI Root CA",
   235  			Organization: []string{"GoPKI Certificate Authority"},
   236  			Country:      []string{"US"},
   237  		},
   238  		ValidFor:   10 * 365 * 24 * time.Hour, // 10 years
   239  		IsCA:       true,
   240  		MaxPathLen: 2,
   241  	})
   242  	if err != nil {
   243  		log.Fatalf("Failed to create CA certificate: %v", err)
   244  	}
   245  
   246  	fmt.Printf("āœ“ Created Root CA: %s\n", caCert.Certificate.Subject.CommonName)
   247  
   248  	// Create intermediate CA
   249  	intermediateManager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048)
   250  	if err != nil {
   251  		log.Fatalf("Failed to generate intermediate key pair: %v", err)
   252  	}
   253  
   254  	intermediateCert, err := cert.SignCertificate(caCert, caManager.KeyPair(), cert.CertificateRequest{
   255  		Subject: pkix.Name{
   256  			CommonName:   "GoPKI Intermediate CA",
   257  			Organization: []string{"GoPKI Certificate Authority"},
   258  		},
   259  		ValidFor:   5 * 365 * 24 * time.Hour, // 5 years
   260  		IsCA:       true,
   261  		MaxPathLen: 1,
   262  	}, intermediateManager.PublicKey())
   263  	if err != nil {
   264  		log.Fatalf("Failed to create intermediate certificate: %v", err)
   265  	}
   266  
   267  	fmt.Printf("āœ“ Created Intermediate CA: %s\n", intermediateCert.Certificate.Subject.CommonName)
   268  
   269  	// Create end-entity certificate
   270  	serverManager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048)
   271  	if err != nil {
   272  		log.Fatalf("Failed to generate server key pair: %v", err)
   273  	}
   274  
   275  	serverCert, err := cert.SignCertificate(intermediateCert, intermediateManager.KeyPair(), cert.CertificateRequest{
   276  		Subject: pkix.Name{
   277  			CommonName:   "server.example.com",
   278  			Organization: []string{"Example Corp"},
   279  		},
   280  		DNSNames: []string{"server.example.com", "api.example.com", "www.example.com"},
   281  		ValidFor: 365 * 24 * time.Hour, // 1 year
   282  	}, serverManager.PublicKey())
   283  	if err != nil {
   284  		log.Fatalf("Failed to create server certificate: %v", err)
   285  	}
   286  
   287  	fmt.Printf("āœ“ Created server certificate: %s\n", serverCert.Certificate.Subject.CommonName)
   288  
   289  	// Create P12 with full certificate chain
   290  	chainP12Path := filepath.Join(outputDir, "server_with_chain.p12")
   291  	chainOpts := pkcs12.DefaultCreateOptions("chain_secret123")
   292  	chainOpts.FriendlyName = "Server Certificate with Chain"
   293  
   294  	// Include the full chain: intermediate CA + root CA
   295  	caCerts := []*x509.Certificate{intermediateCert.Certificate, caCert.Certificate}
   296  	err = pkcs12.CreateP12File(chainP12Path, serverManager.PrivateKey(), serverCert.Certificate, caCerts, chainOpts)
   297  	if err != nil {
   298  		log.Fatalf("Failed to create chain P12 file: %v", err)
   299  	}
   300  
   301  	fmt.Printf("āœ“ Created P12 with certificate chain: %s\n", chainP12Path)
   302  	fmt.Printf("  Chain: Server → Intermediate CA → Root CA\n")
   303  	fmt.Printf("  Password: %s\n", chainOpts.Password)
   304  
   305  	// Get file info
   306  	if info, err := os.Stat(chainP12Path); err == nil {
   307  		fmt.Printf("  File size: %d bytes (larger due to certificate chain)\n", info.Size())
   308  	}
   309  
   310  	fmt.Println("šŸ’¾ Advanced P12 operations completed")
   311  }
   312  
   313  func runP12LoadingAndParsing(outputDir string) {
   314  	fmt.Println("1. Loading Basic P12 Files")
   315  	fmt.Println("--------------------------")
   316  
   317  	// Load the RSA P12 file we created earlier
   318  	rsaP12Path := filepath.Join(outputDir, "rsa_basic.p12")
   319  	loadOpts := pkcs12.DefaultLoadOptions("rsa_secret123")
   320  
   321  	container, err := pkcs12.LoadFromP12File(rsaP12Path, loadOpts)
   322  	if err != nil {
   323  		log.Fatalf("Failed to load RSA P12 file: %v", err)
   324  	}
   325  
   326  	fmt.Printf("āœ“ Loaded P12 file: %s\n", rsaP12Path)
   327  	fmt.Printf("  Key type: %s\n", container.GetKeyType())
   328  	fmt.Printf("  Certificate subject: %s\n", container.Certificate.Subject.CommonName)
   329  
   330  	// Extract certificate chain
   331  	chain := container.ExtractCertificateChain()
   332  	fmt.Printf("  Certificate chain length: %d\n", len(chain))
   333  
   334  	// Validate the container
   335  	if err := container.Validate(); err != nil {
   336  		log.Printf("āš ļø Container validation warning: %v", err)
   337  	} else {
   338  		fmt.Println("āœ“ Container validation passed")
   339  	}
   340  
   341  	fmt.Println()
   342  
   343  	fmt.Println("2. Quick Loading with QuickLoadP12")
   344  	fmt.Println("----------------------------------")
   345  
   346  	// Use the convenience function for simple loading
   347  	ecdsaP12Path := filepath.Join(outputDir, "ecdsa_basic.p12")
   348  	quickContainer, err := pkcs12.QuickLoadP12(ecdsaP12Path, "ecdsa_secret123")
   349  	if err != nil {
   350  		log.Fatalf("Failed to quick load ECDSA P12: %v", err)
   351  	}
   352  
   353  	fmt.Printf("āœ“ Quick loaded P12: %s\n", ecdsaP12Path)
   354  	fmt.Printf("  Algorithm: %s\n", quickContainer.GetKeyType())
   355  	fmt.Printf("  Certificate CN: %s\n", quickContainer.Certificate.Subject.CommonName)
   356  	fmt.Printf("  Valid from: %s\n", quickContainer.Certificate.NotBefore.Format("2006-01-02"))
   357  	fmt.Printf("  Valid until: %s\n", quickContainer.Certificate.NotAfter.Format("2006-01-02"))
   358  
   359  	fmt.Println("šŸ’¾ P12 loading and parsing completed")
   360  }
   361  
   362  func runGoPKIIntegration(outputDir string) {
   363  	fmt.Println("1. P12 Creation from Existing KeyPair Manager")
   364  	fmt.Println("----------------------------------------------")
   365  
   366  	// Load an existing key pair from PEM (simulate existing infrastructure)
   367  	// First, create a PEM file to load from
   368  	tempManager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048)
   369  	if err != nil {
   370  		log.Fatalf("Failed to generate temp key pair: %v", err)
   371  	}
   372  
   373  	tempPEMPath := filepath.Join(outputDir, "temp_private.pem")
   374  	privatePEM, _, err := tempManager.ToPEM()
   375  	if err != nil {
   376  		log.Fatalf("Failed to convert to PEM: %v", err)
   377  	}
   378  
   379  	err = os.WriteFile(tempPEMPath, privatePEM, 0600)
   380  	if err != nil {
   381  		log.Fatalf("Failed to write PEM file: %v", err)
   382  	}
   383  
   384  	// Now load it back using Manager
   385  	loadedManager, err := keypair.LoadFromPEM[*algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](tempPEMPath)
   386  	if err != nil {
   387  		log.Fatalf("Failed to load key pair from PEM: %v", err)
   388  	}
   389  
   390  	fmt.Printf("āœ“ Loaded existing key pair from PEM using Manager\n")
   391  
   392  	// Get key information
   393  	keyInfo, err := loadedManager.GetInfo()
   394  	if err != nil {
   395  		log.Fatalf("Failed to get key info: %v", err)
   396  	}
   397  
   398  	fmt.Printf("  Algorithm: %s\n", keyInfo.Algorithm)
   399  	fmt.Printf("  Key size: %d bits\n", keyInfo.KeySize)
   400  
   401  	// Validate the loaded key pair
   402  	if err := loadedManager.Validate(); err != nil {
   403  		log.Fatalf("Key pair validation failed: %v", err)
   404  	}
   405  
   406  	fmt.Println("āœ“ Key pair validation passed")
   407  
   408  	// Create certificate for the loaded key
   409  	integrationCert, err := cert.CreateSelfSignedCertificate(loadedManager.KeyPair(), cert.CertificateRequest{
   410  		Subject: pkix.Name{
   411  			CommonName:   "Integration Test Certificate",
   412  			Organization: []string{"GoPKI Integration"},
   413  		},
   414  		DNSNames: []string{"integration.example.com"},
   415  		ValidFor: 365 * 24 * time.Hour,
   416  	})
   417  	if err != nil {
   418  		log.Fatalf("Failed to create integration certificate: %v", err)
   419  	}
   420  
   421  	// Create P12 from the loaded Manager
   422  	integrationP12Path := filepath.Join(outputDir, "integration.p12")
   423  	err = pkcs12.QuickCreateP12(integrationP12Path, "integration_secret123", loadedManager.PrivateKey(), integrationCert.Certificate)
   424  	if err != nil {
   425  		log.Fatalf("Failed to create integration P12: %v", err)
   426  	}
   427  
   428  	fmt.Printf("āœ“ Created P12 from loaded Manager: %s\n", integrationP12Path)
   429  
   430  	// Clean up temp file
   431  	os.Remove(tempPEMPath)
   432  
   433  	fmt.Println("šŸ’¾ GoPKI integration examples completed")
   434  }
   435  
   436  func runRealWorldScenarios(outputDir string) {
   437  	fmt.Println("1. Web Server Certificate Bundle")
   438  	fmt.Println("---------------------------------")
   439  
   440  	// Create web server scenario with proper certificate hierarchy
   441  	webServerManager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048)
   442  	if err != nil {
   443  		log.Fatalf("Failed to generate web server key: %v", err)
   444  	}
   445  
   446  	webServerCert, err := cert.CreateSelfSignedCertificate(webServerManager.KeyPair(), cert.CertificateRequest{
   447  		Subject: pkix.Name{
   448  			CommonName:   "web.example.com",
   449  			Organization: []string{"Example Web Services"},
   450  			Country:      []string{"US"},
   451  		},
   452  		DNSNames: []string{
   453  			"web.example.com",
   454  			"www.example.com",
   455  			"api.example.com",
   456  			"admin.example.com",
   457  		},
   458  		ValidFor: 365 * 24 * time.Hour,
   459  	})
   460  	if err != nil {
   461  		log.Fatalf("Failed to create web server certificate: %v", err)
   462  	}
   463  
   464  	webServerP12Path := filepath.Join(outputDir, "webserver.p12")
   465  	webServerOpts := pkcs12.DefaultCreateOptions("webserver_secure_password_2024")
   466  	webServerOpts.FriendlyName = "Web Server Certificate - Example.com"
   467  
   468  	err = pkcs12.CreateP12File(webServerP12Path, webServerManager.PrivateKey(), webServerCert.Certificate, nil, webServerOpts)
   469  	if err != nil {
   470  		log.Fatalf("Failed to create web server P12: %v", err)
   471  	}
   472  
   473  	fmt.Printf("āœ“ Created web server certificate bundle\n")
   474  	fmt.Printf("  File: %s\n", webServerP12Path)
   475  	fmt.Printf("  Primary domain: %s\n", webServerCert.Certificate.Subject.CommonName)
   476  	fmt.Printf("  SAN domains: %v\n", webServerCert.Certificate.DNSNames)
   477  	fmt.Printf("  Password: %s\n", webServerOpts.Password)
   478  
   479  	fmt.Println()
   480  
   481  	fmt.Println("2. Client Authentication Certificate")
   482  	fmt.Println("-------------------------------------")
   483  
   484  	// Create client authentication certificate with Ed25519 for modern security
   485  	clientAuthManager, err := keypair.Generate[algo.Ed25519Config, *algo.Ed25519KeyPair, ed25519.PrivateKey, ed25519.PublicKey]("")
   486  	if err != nil {
   487  		log.Fatalf("Failed to generate client auth key: %v", err)
   488  	}
   489  
   490  	clientAuthCert, err := cert.CreateSelfSignedCertificate(clientAuthManager.KeyPair(), cert.CertificateRequest{
   491  		Subject: pkix.Name{
   492  			CommonName:   "john.doe@example.com",
   493  			Organization: []string{"Example Corp"},
   494  			Country:      []string{"US"},
   495  		},
   496  		ValidFor: 2 * 365 * 24 * time.Hour, // 2 years for client certs
   497  	})
   498  	if err != nil {
   499  		log.Fatalf("Failed to create client auth certificate: %v", err)
   500  	}
   501  
   502  	clientAuthP12Path := filepath.Join(outputDir, "client_auth.p12")
   503  	err = pkcs12.QuickCreateP12(clientAuthP12Path, "client_auth_john_doe_2024", clientAuthManager.PrivateKey(), clientAuthCert.Certificate)
   504  	if err != nil {
   505  		log.Fatalf("Failed to create client auth P12: %v", err)
   506  	}
   507  
   508  	fmt.Printf("āœ“ Created client authentication certificate\n")
   509  	fmt.Printf("  File: %s\n", clientAuthP12Path)
   510  	fmt.Printf("  User: %s\n", clientAuthCert.Certificate.Subject.CommonName)
   511  	fmt.Printf("  Algorithm: Ed25519 (modern, high-performance)\n")
   512  
   513  	fmt.Println("šŸ’¾ Real-world scenarios completed")
   514  }
   515  
   516  func runValidationAndSecurity(outputDir string) {
   517  	fmt.Println("1. P12 Container Validation")
   518  	fmt.Println("---------------------------")
   519  
   520  	// Load and validate different P12 files
   521  	testFiles := []struct {
   522  		filename string
   523  		password string
   524  		purpose  string
   525  	}{
   526  		{"webserver.p12", "webserver_secure_password_2024", "Web Server"},
   527  		{"client_auth.p12", "client_auth_john_doe_2024", "Client Authentication"},
   528  	}
   529  
   530  	for i, testFile := range testFiles {
   531  		fmt.Printf("%d. Validating %s Certificate\n", i+1, testFile.purpose)
   532  
   533  		p12Path := filepath.Join(outputDir, testFile.filename)
   534  		container, err := pkcs12.QuickLoadP12(p12Path, testFile.password)
   535  		if err != nil {
   536  			log.Printf("āŒ Failed to load %s: %v", testFile.filename, err)
   537  			continue
   538  		}
   539  
   540  		fmt.Printf("   āœ“ Successfully loaded: %s\n", testFile.filename)
   541  
   542  		// Validate container
   543  		if err := container.Validate(); err != nil {
   544  			fmt.Printf("   āš ļø Validation warning: %v\n", err)
   545  		} else {
   546  			fmt.Printf("   āœ“ Container validation passed\n")
   547  		}
   548  
   549  		// Check certificate validity
   550  		now := time.Now()
   551  		if now.Before(container.Certificate.NotBefore) {
   552  			fmt.Printf("   āš ļø Certificate not yet valid (starts: %s)\n", container.Certificate.NotBefore.Format("2006-01-02"))
   553  		} else if now.After(container.Certificate.NotAfter) {
   554  			fmt.Printf("   āŒ Certificate expired (ended: %s)\n", container.Certificate.NotAfter.Format("2006-01-02"))
   555  		} else {
   556  			fmt.Printf("   āœ“ Certificate is currently valid\n")
   557  			fmt.Printf("     Valid until: %s\n", container.Certificate.NotAfter.Format("2006-01-02 15:04:05"))
   558  		}
   559  
   560  		// Check key type and size
   561  		keyType := container.GetKeyType()
   562  		fmt.Printf("   āœ“ Key type: %s\n", keyType)
   563  
   564  		// Extract and validate certificate chain
   565  		chain := container.ExtractCertificateChain()
   566  		fmt.Printf("   āœ“ Certificate chain length: %d\n", len(chain))
   567  
   568  		fmt.Println()
   569  	}
   570  
   571  	fmt.Println("2. Security Best Practices")
   572  	fmt.Println("---------------------------")
   573  
   574  	fmt.Println("šŸ” Security Recommendations:")
   575  	fmt.Println("  • Use strong, unique passwords for each P12 file")
   576  	fmt.Println("  • Use modern encryption (avoid legacy mode)")
   577  	fmt.Println("  • Use RSA 2048+ bits or ECDSA P-256+ for production")
   578  	fmt.Println("  • Store P12 files securely with restricted file permissions")
   579  	fmt.Println("  • Regularly rotate certificates and passwords")
   580  	fmt.Println("  • Consider Ed25519 for modern, high-performance applications")
   581  
   582  	fmt.Println("šŸ’¾ Validation and security analysis completed")
   583  }