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

     1  //go:build example
     2  
     3  package main
     4  
     5  import (
     6  	"crypto/x509/pkix"
     7  	"fmt"
     8  	"log"
     9  	"net"
    10  	"os"
    11  	"strings"
    12  	"time"
    13  
    14  	"github.com/jasoet/gopki/cert"
    15  	"github.com/jasoet/gopki/keypair"
    16  	"github.com/jasoet/gopki/keypair/algo"
    17  	"github.com/jasoet/gopki/keypair/format"
    18  	"github.com/jasoet/gopki/pkcs12"
    19  )
    20  
    21  func main() {
    22  	fmt.Println("=== GoPKI Certificate Module - Comprehensive Examples ===")
    23  	fmt.Println("Demonstrating all certificate features with type-safe APIs")
    24  
    25  	// Create output directory
    26  	if err := os.MkdirAll("output", 0755); err != nil {
    27  		log.Fatal("Failed to create output directory:", err)
    28  	}
    29  
    30  	// Execute all certificate examples
    31  	fmt.Println("\nšŸ—ļø PART 1: Core Certificate Creation")
    32  	fmt.Println(strings.Repeat("=", 60))
    33  	demonstrateCoreCreation()
    34  
    35  	fmt.Println("\nšŸ›ļø PART 2: Advanced CA Hierarchies")
    36  	fmt.Println(strings.Repeat("=", 60))
    37  	demonstrateCAHierarchies()
    38  
    39  	fmt.Println("\nšŸ” PART 3: Multi-Algorithm Support")
    40  	fmt.Println(strings.Repeat("=", 60))
    41  	demonstrateMultiAlgorithm()
    42  
    43  	fmt.Println("\n🌐 PART 4: Subject Alternative Names (SAN)")
    44  	fmt.Println(strings.Repeat("=", 60))
    45  	demonstrateSANUsage()
    46  
    47  	fmt.Println("\nšŸ’¾ PART 5: Format Operations")
    48  	fmt.Println(strings.Repeat("=", 60))
    49  	demonstrateFormatOperations()
    50  
    51  	fmt.Println("\nšŸ“¦ PART 6: PKCS#12 Integration")
    52  	fmt.Println(strings.Repeat("=", 60))
    53  	demonstratePKCS12Integration()
    54  
    55  	fmt.Println("\nāœ… PART 7: Certificate Validation")
    56  	fmt.Println(strings.Repeat("=", 60))
    57  	demonstrateCertificateValidation()
    58  
    59  	fmt.Println("\nšŸ”— PART 8: Integration & Advanced Features")
    60  	fmt.Println(strings.Repeat("=", 60))
    61  	demonstrateIntegrationFeatures()
    62  
    63  	fmt.Println("\n" + strings.Repeat("=", 60))
    64  	fmt.Println("āœ… All certificate examples completed successfully!")
    65  	fmt.Println("šŸ“‚ Generated files are in the 'output/' directory")
    66  	fmt.Println("šŸ” Check certificate details with: openssl x509 -in output/<file> -text -noout")
    67  	fmt.Println(strings.Repeat("=", 60))
    68  }
    69  
    70  // PART 1: Core Certificate Creation
    71  func demonstrateCoreCreation() {
    72  	fmt.Println("\n1.1 Self-Signed Certificate Creation")
    73  
    74  	// Generate key pair for self-signed certificate
    75  	keyPair, err := algo.GenerateRSAKeyPair(algo.KeySize2048)
    76  	if err != nil {
    77  		log.Printf("Failed to generate key pair: %v\n", err)
    78  		return
    79  	}
    80  
    81  	// Create self-signed certificate request
    82  	request := cert.CertificateRequest{
    83  		Subject: pkix.Name{
    84  			Country:            []string{"US"},
    85  			Province:           []string{"California"},
    86  			Locality:           []string{"San Francisco"},
    87  			Organization:       []string{"GoPKI Examples Inc"},
    88  			OrganizationalUnit: []string{"IT Department"},
    89  			CommonName:         "GoPKI Self-Signed Certificate",
    90  		},
    91  		DNSNames:    []string{"localhost", "example.com"},
    92  		IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1)},
    93  		ValidFrom:   time.Now(),
    94  		ValidFor:    365 * 24 * time.Hour, // 1 year
    95  	}
    96  
    97  	// Create self-signed certificate
    98  	selfSignedCert, err := cert.CreateSelfSignedCertificate(keyPair, request)
    99  	if err != nil {
   100  		log.Printf("Failed to create self-signed certificate: %v\n", err)
   101  		return
   102  	}
   103  
   104  	// Save certificate and key
   105  	err = selfSignedCert.SaveToFile("output/self_signed.pem")
   106  	if err != nil {
   107  		log.Printf("Failed to save self-signed certificate: %v\n", err)
   108  		return
   109  	}
   110  
   111  	err = keypair.ToPEMFiles(keyPair, "output/self_signed_private.pem", "output/self_signed_public.pem")
   112  	if err != nil {
   113  		log.Printf("Failed to save key pair: %v\n", err)
   114  		return
   115  	}
   116  
   117  	fmt.Printf("   āœ“ Self-signed certificate created\n")
   118  	fmt.Printf("   āœ“ Subject: %s\n", selfSignedCert.Certificate.Subject.CommonName)
   119  	fmt.Printf("   āœ“ Valid from: %s\n", selfSignedCert.Certificate.NotBefore.Format("2006-01-02"))
   120  	fmt.Printf("   āœ“ Valid until: %s\n", selfSignedCert.Certificate.NotAfter.Format("2006-01-02"))
   121  	fmt.Printf("   āœ“ DNS names: %v\n", selfSignedCert.Certificate.DNSNames)
   122  	fmt.Printf("   āœ“ Files: output/self_signed.pem, output/self_signed_private.pem\n")
   123  
   124  	fmt.Println("\n1.2 CA Certificate Creation")
   125  
   126  	// Generate CA key pair
   127  	caKeyPair, err := algo.GenerateRSAKeyPair(algo.KeySize3072)
   128  	if err != nil {
   129  		log.Printf("Failed to generate CA key pair: %v\n", err)
   130  		return
   131  	}
   132  
   133  	// Create CA certificate request
   134  	caRequest := cert.CertificateRequest{
   135  		Subject: pkix.Name{
   136  			Country:      []string{"US"},
   137  			Organization: []string{"GoPKI Root CA"},
   138  			CommonName:   "GoPKI Root Certificate Authority",
   139  		},
   140  		IsCA:       true,
   141  		MaxPathLen: 2, // Allow up to 2 intermediate CAs
   142  		ValidFrom:  time.Now(),
   143  		ValidFor:   10 * 365 * 24 * time.Hour, // 10 years
   144  	}
   145  
   146  	// Create CA certificate
   147  	caCert, err := cert.CreateCACertificate(caKeyPair, caRequest)
   148  	if err != nil {
   149  		log.Printf("Failed to create CA certificate: %v\n", err)
   150  		return
   151  	}
   152  
   153  	// Save CA certificate and key
   154  	err = caCert.SaveToFile("output/root_ca.pem")
   155  	if err != nil {
   156  		log.Printf("Failed to save CA certificate: %v\n", err)
   157  		return
   158  	}
   159  
   160  	err = keypair.ToPEMFiles(caKeyPair, "output/root_ca_private.pem", "output/root_ca_public.pem")
   161  	if err != nil {
   162  		log.Printf("Failed to save CA key pair: %v\n", err)
   163  		return
   164  	}
   165  
   166  	fmt.Printf("   āœ“ Root CA certificate created\n")
   167  	fmt.Printf("   āœ“ Subject: %s\n", caCert.Certificate.Subject.CommonName)
   168  	fmt.Printf("   āœ“ Is CA: %v\n", caCert.Certificate.IsCA)
   169  	fmt.Printf("   āœ“ Max path length: %d\n", caCert.Certificate.MaxPathLen)
   170  	fmt.Printf("   āœ“ Key size: %d bits\n", caKeyPair.PrivateKey.Size()*8)
   171  	fmt.Printf("   āœ“ Files: output/root_ca.pem, output/root_ca_private.pem\n")
   172  
   173  	fmt.Println("\n1.3 Certificate Signing")
   174  
   175  	// Generate server key pair
   176  	serverKeyPair, err := algo.GenerateECDSAKeyPair(algo.P256)
   177  	if err != nil {
   178  		log.Printf("Failed to generate server key pair: %v\n", err)
   179  		return
   180  	}
   181  
   182  	// Create server certificate request
   183  	serverRequest := cert.CertificateRequest{
   184  		Subject: pkix.Name{
   185  			Country:      []string{"US"},
   186  			Organization: []string{"GoPKI Web Services"},
   187  			CommonName:   "api.gopki.example.com",
   188  		},
   189  		DNSNames:     []string{"api.gopki.example.com", "www.gopki.example.com"},
   190  		IPAddresses:  []net.IP{net.IPv4(192, 168, 1, 100)},
   191  		EmailAddress: []string{"admin@gopki.example.com"},
   192  		ValidFrom:    time.Now(),
   193  		ValidFor:     365 * 24 * time.Hour, // 1 year
   194  	}
   195  
   196  	// Sign server certificate with CA
   197  	serverCert, err := cert.SignCertificate(caCert, caKeyPair, serverRequest, &serverKeyPair.PrivateKey.PublicKey)
   198  	if err != nil {
   199  		log.Printf("Failed to sign server certificate: %v\n", err)
   200  		return
   201  	}
   202  
   203  	// Save server certificate and key
   204  	err = serverCert.SaveToFile("output/server.pem")
   205  	if err != nil {
   206  		log.Printf("Failed to save server certificate: %v\n", err)
   207  		return
   208  	}
   209  
   210  	err = keypair.ToPEMFiles(serverKeyPair, "output/server_private.pem", "output/server_public.pem")
   211  	if err != nil {
   212  		log.Printf("Failed to save server key pair: %v\n", err)
   213  		return
   214  	}
   215  
   216  	fmt.Printf("   āœ“ Server certificate signed by CA\n")
   217  	fmt.Printf("   āœ“ Subject: %s\n", serverCert.Certificate.Subject.CommonName)
   218  	fmt.Printf("   āœ“ Issuer: %s\n", serverCert.Certificate.Issuer.CommonName)
   219  	fmt.Printf("   āœ“ Algorithm: ECDSA P-256\n")
   220  	fmt.Printf("   āœ“ Files: output/server.pem, output/server_private.pem\n")
   221  }
   222  
   223  // PART 2: Advanced CA Hierarchies
   224  func demonstrateCAHierarchies() {
   225  	fmt.Println("\n2.1 Multi-Level CA Hierarchy Creation")
   226  
   227  	// Root CA (already created in Part 1, load it)
   228  	fmt.Printf("   → Loading existing Root CA...\n")
   229  	rootCA, err := cert.LoadCertificateFromFile("output/root_ca.pem")
   230  	if err != nil {
   231  		log.Printf("Failed to load root CA: %v\n", err)
   232  		return
   233  	}
   234  
   235  	// Load root CA key pair for signing
   236  	rootCAKeyData, err := os.ReadFile("output/root_ca_private.pem")
   237  	if err != nil {
   238  		log.Printf("Failed to read root CA private key: %v\n", err)
   239  		return
   240  	}
   241  
   242  	// Parse RSA key from PEM data
   243  	parsedKey, err := algo.RSAKeyPairFromPEM(format.PEM(rootCAKeyData))
   244  	if err != nil {
   245  		log.Printf("Failed to parse root CA private key: %v\n", err)
   246  		return
   247  	}
   248  	rootCAKey := parsedKey
   249  
   250  	// Create Intermediate CA
   251  	fmt.Printf("   → Creating Intermediate CA...\n")
   252  	intermediateKeyPair, err := algo.GenerateRSAKeyPair(algo.KeySize2048)
   253  	if err != nil {
   254  		log.Printf("Failed to generate intermediate CA key pair: %v\n", err)
   255  		return
   256  	}
   257  
   258  	intermediateRequest := cert.CertificateRequest{
   259  		Subject: pkix.Name{
   260  			Country:      []string{"US"},
   261  			Organization: []string{"GoPKI Intermediate CA"},
   262  			CommonName:   "GoPKI Intermediate Certificate Authority",
   263  		},
   264  		IsCA:       true,
   265  		MaxPathLen: 0, // Can only sign end-entity certificates
   266  		ValidFrom:  time.Now(),
   267  		ValidFor:   5 * 365 * 24 * time.Hour, // 5 years
   268  	}
   269  
   270  	// Sign intermediate CA with root CA
   271  	intermediateCert, err := cert.SignCertificate(rootCA, rootCAKey, intermediateRequest, &intermediateKeyPair.PrivateKey.PublicKey)
   272  	if err != nil {
   273  		log.Printf("Failed to sign intermediate CA: %v\n", err)
   274  		return
   275  	}
   276  
   277  	// Save intermediate CA
   278  	err = intermediateCert.SaveToFile("output/intermediate_ca.pem")
   279  	if err != nil {
   280  		log.Printf("Failed to save intermediate CA: %v\n", err)
   281  		return
   282  	}
   283  
   284  	err = keypair.ToPEMFiles(intermediateKeyPair, "output/intermediate_ca_private.pem", "output/intermediate_ca_public.pem")
   285  	if err != nil {
   286  		log.Printf("Failed to save intermediate CA key pair: %v\n", err)
   287  		return
   288  	}
   289  
   290  	fmt.Printf("     āœ“ Intermediate CA created and signed by Root CA\n")
   291  	fmt.Printf("     āœ“ Subject: %s\n", intermediateCert.Certificate.Subject.CommonName)
   292  	fmt.Printf("     āœ“ Issuer: %s\n", intermediateCert.Certificate.Issuer.CommonName)
   293  	fmt.Printf("     āœ“ Max path length: %d (end-entity only)\n", intermediateCert.Certificate.MaxPathLen)
   294  
   295  	fmt.Println("\n2.2 End-Entity Certificate from Intermediate CA")
   296  
   297  	// Create end-entity certificate signed by intermediate CA
   298  	endEntityKeyPair, err := algo.GenerateEd25519KeyPair()
   299  	if err != nil {
   300  		log.Printf("Failed to generate end-entity key pair: %v\n", err)
   301  		return
   302  	}
   303  
   304  	endEntityRequest := cert.CertificateRequest{
   305  		Subject: pkix.Name{
   306  			Country:      []string{"US"},
   307  			Organization: []string{"GoPKI Client Services"},
   308  			CommonName:   "client.gopki.example.com",
   309  		},
   310  		DNSNames:     []string{"client.gopki.example.com"},
   311  		EmailAddress: []string{"client@gopki.example.com"},
   312  		ValidFrom:    time.Now(),
   313  		ValidFor:     365 * 24 * time.Hour, // 1 year
   314  	}
   315  
   316  	// Sign end-entity certificate with intermediate CA
   317  	endEntityCert, err := cert.SignCertificate(intermediateCert, intermediateKeyPair, endEntityRequest, endEntityKeyPair.PublicKey)
   318  	if err != nil {
   319  		log.Printf("Failed to sign end-entity certificate: %v\n", err)
   320  		return
   321  	}
   322  
   323  	// Save end-entity certificate
   324  	err = endEntityCert.SaveToFile("output/end_entity.pem")
   325  	if err != nil {
   326  		log.Printf("Failed to save end-entity certificate: %v\n", err)
   327  		return
   328  	}
   329  
   330  	err = keypair.ToPEMFiles(endEntityKeyPair, "output/end_entity_private.pem", "output/end_entity_public.pem")
   331  	if err != nil {
   332  		log.Printf("Failed to save end-entity key pair: %v\n", err)
   333  		return
   334  	}
   335  
   336  	fmt.Printf("     āœ“ End-entity certificate created\n")
   337  	fmt.Printf("     āœ“ Subject: %s\n", endEntityCert.Certificate.Subject.CommonName)
   338  	fmt.Printf("     āœ“ Issuer: %s\n", endEntityCert.Certificate.Issuer.CommonName)
   339  	fmt.Printf("     āœ“ Algorithm: Ed25519\n")
   340  	fmt.Printf("     āœ“ Certificate chain: Root CA → Intermediate CA → End Entity\n")
   341  
   342  	fmt.Println("\n2.3 Path Length Constraint Enforcement")
   343  
   344  	fmt.Printf("   → Testing path length constraints...\n")
   345  
   346  	// Test 1: Intermediate CA with MaxPathLen=0 should not be able to sign another CA
   347  	fmt.Printf("     • Testing: Intermediate CA (MaxPathLen=0) signing another CA (should fail)\n")
   348  
   349  	// Try to create another intermediate CA (this should fail due to path length constraint)
   350  	anotherIntermediateKeyPair, err := algo.GenerateRSAKeyPair(algo.KeySize2048)
   351  	if err != nil {
   352  		log.Printf("Failed to generate key pair for test: %v\n", err)
   353  		return
   354  	}
   355  
   356  	anotherIntermediateRequest := cert.CertificateRequest{
   357  		Subject: pkix.Name{
   358  			CommonName: "Another Intermediate CA (Should Fail)",
   359  		},
   360  		IsCA:      true,
   361  		ValidFrom: time.Now(),
   362  		ValidFor:  365 * 24 * time.Hour,
   363  	}
   364  
   365  	// This should fail because intermediate CA has MaxPathLen=0
   366  	_, err = cert.SignCertificate(intermediateCert, intermediateKeyPair, anotherIntermediateRequest, &anotherIntermediateKeyPair.PrivateKey.PublicKey)
   367  	if err != nil {
   368  		fmt.Printf("       āœ“ Correctly rejected: %v\n", err)
   369  	} else {
   370  		fmt.Printf("       āŒ ERROR: Should have been rejected due to path length constraint\n")
   371  	}
   372  
   373  	// Test 2: Root CA with MaxPathLen=2 should be able to sign intermediate CAs
   374  	fmt.Printf("     • Testing: Root CA (MaxPathLen=2) signing intermediate CA (should succeed)\n")
   375  
   376  	validIntermediateRequest := cert.CertificateRequest{
   377  		Subject: pkix.Name{
   378  			CommonName: "Valid Intermediate CA",
   379  		},
   380  		IsCA:       true,
   381  		MaxPathLen: 0, // This intermediate can only sign end-entity certs
   382  		ValidFrom:  time.Now(),
   383  		ValidFor:   365 * 24 * time.Hour,
   384  	}
   385  
   386  	// This should succeed because root CA has MaxPathLen=2
   387  	validIntermediate, err := cert.SignCertificate(rootCA, rootCAKey, validIntermediateRequest, &anotherIntermediateKeyPair.PrivateKey.PublicKey)
   388  	if err != nil {
   389  		fmt.Printf("       āŒ ERROR: Should have succeeded: %v\n", err)
   390  	} else {
   391  		fmt.Printf("       āœ“ Correctly allowed by Root CA\n")
   392  		fmt.Printf("       āœ“ Created valid intermediate with MaxPathLen=0\n")
   393  
   394  		// Save the valid intermediate for reference
   395  		err = validIntermediate.SaveToFile("output/valid_intermediate_ca.pem")
   396  		if err != nil {
   397  			log.Printf("Failed to save valid intermediate CA: %v\n", err)
   398  		}
   399  	}
   400  }
   401  
   402  // PART 3: Multi-Algorithm Support
   403  func demonstrateMultiAlgorithm() {
   404  	fmt.Println("\n3.1 RSA Certificate Variants")
   405  
   406  	rsaSizes := []struct {
   407  		size algo.KeySize
   408  		name string
   409  	}{
   410  		{algo.KeySize2048, "RSA-2048"},
   411  		{algo.KeySize3072, "RSA-3072"},
   412  		{algo.KeySize4096, "RSA-4096"},
   413  	}
   414  
   415  	for _, rsaSize := range rsaSizes {
   416  		fmt.Printf("   → Creating %s certificate...\n", rsaSize.name)
   417  
   418  		keyPair, err := algo.GenerateRSAKeyPair(rsaSize.size)
   419  		if err != nil {
   420  			log.Printf("Failed to generate %s key pair: %v\n", rsaSize.name, err)
   421  			continue
   422  		}
   423  
   424  		request := cert.CertificateRequest{
   425  			Subject: pkix.Name{
   426  				Organization: []string{"GoPKI Examples"},
   427  				CommonName:   fmt.Sprintf("%s Test Certificate", rsaSize.name),
   428  			},
   429  			ValidFrom: time.Now(),
   430  			ValidFor:  365 * 24 * time.Hour,
   431  		}
   432  
   433  		certificate, err := cert.CreateSelfSignedCertificate(keyPair, request)
   434  		if err != nil {
   435  			log.Printf("Failed to create %s certificate: %v\n", rsaSize.name, err)
   436  			continue
   437  		}
   438  
   439  		filename := fmt.Sprintf("output/%s_cert.pem", strings.ToLower(strings.ReplaceAll(rsaSize.name, "-", "_")))
   440  		err = certificate.SaveToFile(filename)
   441  		if err != nil {
   442  			log.Printf("Failed to save %s certificate: %v\n", rsaSize.name, err)
   443  			continue
   444  		}
   445  
   446  		fmt.Printf("     āœ“ %s certificate created\n", rsaSize.name)
   447  		fmt.Printf("     āœ“ Key size: %d bits\n", keyPair.PrivateKey.Size()*8)
   448  		fmt.Printf("     āœ“ Subject: %s\n", certificate.Certificate.Subject.CommonName)
   449  		fmt.Printf("     āœ“ File: %s\n", filename)
   450  	}
   451  
   452  	fmt.Println("\n3.2 ECDSA Certificate Variants")
   453  
   454  	ecdsaCurves := []struct {
   455  		curve algo.ECDSACurve
   456  		name  string
   457  	}{
   458  		{algo.P224, "ECDSA-P224"},
   459  		{algo.P256, "ECDSA-P256"},
   460  		{algo.P384, "ECDSA-P384"},
   461  		{algo.P521, "ECDSA-P521"},
   462  	}
   463  
   464  	for _, ecdsaCurve := range ecdsaCurves {
   465  		fmt.Printf("   → Creating %s certificate...\n", ecdsaCurve.name)
   466  
   467  		keyPair, err := algo.GenerateECDSAKeyPair(ecdsaCurve.curve)
   468  		if err != nil {
   469  			log.Printf("Failed to generate %s key pair: %v\n", ecdsaCurve.name, err)
   470  			continue
   471  		}
   472  
   473  		request := cert.CertificateRequest{
   474  			Subject: pkix.Name{
   475  				Organization: []string{"GoPKI Examples"},
   476  				CommonName:   fmt.Sprintf("%s Test Certificate", ecdsaCurve.name),
   477  			},
   478  			ValidFrom: time.Now(),
   479  			ValidFor:  365 * 24 * time.Hour,
   480  		}
   481  
   482  		certificate, err := cert.CreateSelfSignedCertificate(keyPair, request)
   483  		if err != nil {
   484  			log.Printf("Failed to create %s certificate: %v\n", ecdsaCurve.name, err)
   485  			continue
   486  		}
   487  
   488  		filename := fmt.Sprintf("output/%s_cert.pem", strings.ToLower(strings.ReplaceAll(ecdsaCurve.name, "-", "_")))
   489  		err = certificate.SaveToFile(filename)
   490  		if err != nil {
   491  			log.Printf("Failed to save %s certificate: %v\n", ecdsaCurve.name, err)
   492  			continue
   493  		}
   494  
   495  		fmt.Printf("     āœ“ %s certificate created\n", ecdsaCurve.name)
   496  		fmt.Printf("     āœ“ Curve: %s\n", keyPair.PrivateKey.Curve.Params().Name)
   497  		fmt.Printf("     āœ“ Bit size: %d\n", keyPair.PrivateKey.Curve.Params().BitSize)
   498  		fmt.Printf("     āœ“ Subject: %s\n", certificate.Certificate.Subject.CommonName)
   499  		fmt.Printf("     āœ“ File: %s\n", filename)
   500  	}
   501  
   502  	fmt.Println("\n3.3 Ed25519 Certificate")
   503  
   504  	fmt.Printf("   → Creating Ed25519 certificate...\n")
   505  
   506  	keyPair, err := algo.GenerateEd25519KeyPair()
   507  	if err != nil {
   508  		log.Printf("Failed to generate Ed25519 key pair: %v\n", err)
   509  		return
   510  	}
   511  
   512  	request := cert.CertificateRequest{
   513  		Subject: pkix.Name{
   514  			Organization: []string{"GoPKI Examples"},
   515  			CommonName:   "Ed25519 Test Certificate",
   516  		},
   517  		ValidFrom: time.Now(),
   518  		ValidFor:  365 * 24 * time.Hour,
   519  	}
   520  
   521  	certificate, err := cert.CreateSelfSignedCertificate(keyPair, request)
   522  	if err != nil {
   523  		log.Printf("Failed to create Ed25519 certificate: %v\n", err)
   524  		return
   525  	}
   526  
   527  	err = certificate.SaveToFile("output/ed25519_cert.pem")
   528  	if err != nil {
   529  		log.Printf("Failed to save Ed25519 certificate: %v\n", err)
   530  		return
   531  	}
   532  
   533  	fmt.Printf("     āœ“ Ed25519 certificate created\n")
   534  	fmt.Printf("     āœ“ Key size: 256 bits (fixed)\n")
   535  	fmt.Printf("     āœ“ Private key length: %d bytes\n", len(keyPair.PrivateKey))
   536  	fmt.Printf("     āœ“ Public key length: %d bytes\n", len(keyPair.PublicKey))
   537  	fmt.Printf("     āœ“ Subject: %s\n", certificate.Certificate.Subject.CommonName)
   538  	fmt.Printf("     āœ“ File: output/ed25519_cert.pem\n")
   539  
   540  	fmt.Println("\n3.4 Algorithm Performance Comparison")
   541  
   542  	fmt.Printf("   → Measuring certificate creation performance...\n")
   543  	fmt.Printf("   Algorithm    Key Gen    Cert Creation  Total Time\n")
   544  	fmt.Printf("   --------------------------------------------------------\n")
   545  
   546  	algorithms := []struct {
   547  		name string
   548  		fn   func() (interface{}, error)
   549  	}{
   550  		{"RSA-2048", func() (interface{}, error) {
   551  			keyPair, err := algo.GenerateRSAKeyPair(algo.KeySize2048)
   552  			if err != nil {
   553  				return nil, err
   554  			}
   555  			req := cert.CertificateRequest{
   556  				Subject:   pkix.Name{CommonName: "Performance Test"},
   557  				ValidFrom: time.Now(),
   558  				ValidFor:  365 * 24 * time.Hour,
   559  			}
   560  			return cert.CreateSelfSignedCertificate(keyPair, req)
   561  		}},
   562  		{"ECDSA-P256", func() (interface{}, error) {
   563  			keyPair, err := algo.GenerateECDSAKeyPair(algo.P256)
   564  			if err != nil {
   565  				return nil, err
   566  			}
   567  			req := cert.CertificateRequest{
   568  				Subject:   pkix.Name{CommonName: "Performance Test"},
   569  				ValidFrom: time.Now(),
   570  				ValidFor:  365 * 24 * time.Hour,
   571  			}
   572  			return cert.CreateSelfSignedCertificate(keyPair, req)
   573  		}},
   574  		{"Ed25519", func() (interface{}, error) {
   575  			keyPair, err := algo.GenerateEd25519KeyPair()
   576  			if err != nil {
   577  				return nil, err
   578  			}
   579  			req := cert.CertificateRequest{
   580  				Subject:   pkix.Name{CommonName: "Performance Test"},
   581  				ValidFrom: time.Now(),
   582  				ValidFor:  365 * 24 * time.Hour,
   583  			}
   584  			return cert.CreateSelfSignedCertificate(keyPair, req)
   585  		}},
   586  	}
   587  
   588  	for _, alg := range algorithms {
   589  		start := time.Now()
   590  		_, err := alg.fn()
   591  		duration := time.Since(start)
   592  
   593  		if err != nil {
   594  			fmt.Printf("   %-12s Error: %v\n", alg.name, err)
   595  		} else {
   596  			fmt.Printf("   %-12s %-10s %-14s %.2fms\n", alg.name, "N/A", "N/A", float64(duration.Nanoseconds())/1000000)
   597  		}
   598  	}
   599  }
   600  
   601  // PART 4: Subject Alternative Names (SAN)
   602  func demonstrateSANUsage() {
   603  	fmt.Println("\n4.1 Complex SAN Combinations")
   604  
   605  	// Create certificate with comprehensive SAN usage
   606  	keyPair, err := algo.GenerateECDSAKeyPair(algo.P256)
   607  	if err != nil {
   608  		log.Printf("Failed to generate key pair: %v\n", err)
   609  		return
   610  	}
   611  
   612  	// Complex SAN request
   613  	request := cert.CertificateRequest{
   614  		Subject: pkix.Name{
   615  			Country:      []string{"US"},
   616  			Organization: []string{"GoPKI Multi-Domain Services"},
   617  			CommonName:   "multi-domain.gopki.example.com",
   618  		},
   619  		// Multiple DNS names
   620  		DNSNames: []string{
   621  			"multi-domain.gopki.example.com",
   622  			"api.gopki.example.com",
   623  			"www.gopki.example.com",
   624  			"admin.gopki.example.com",
   625  			"*.staging.gopki.example.com", // Wildcard domain
   626  			"localhost",
   627  		},
   628  		// Multiple IP addresses (IPv4 and IPv6)
   629  		IPAddresses: []net.IP{
   630  			net.IPv4(127, 0, 0, 1),     // localhost
   631  			net.IPv4(192, 168, 1, 100), // private network
   632  			net.IPv4(10, 0, 0, 50),     // another private network
   633  			net.ParseIP("::1"),         // IPv6 localhost
   634  			net.ParseIP("2001:db8::1"), // IPv6 example
   635  		},
   636  		// Multiple email addresses
   637  		EmailAddress: []string{
   638  			"admin@gopki.example.com",
   639  			"support@gopki.example.com",
   640  			"security@gopki.example.com",
   641  		},
   642  		ValidFrom: time.Now(),
   643  		ValidFor:  2 * 365 * 24 * time.Hour, // 2 years
   644  	}
   645  
   646  	certificate, err := cert.CreateSelfSignedCertificate(keyPair, request)
   647  	if err != nil {
   648  		log.Printf("Failed to create certificate with complex SAN: %v\n", err)
   649  		return
   650  	}
   651  
   652  	err = certificate.SaveToFile("output/complex_san_cert.pem")
   653  	if err != nil {
   654  		log.Printf("Failed to save complex SAN certificate: %v\n", err)
   655  		return
   656  	}
   657  
   658  	fmt.Printf("   āœ“ Complex SAN certificate created\n")
   659  	fmt.Printf("   āœ“ Subject: %s\n", certificate.Certificate.Subject.CommonName)
   660  	fmt.Printf("   āœ“ DNS names (%d):\n", len(certificate.Certificate.DNSNames))
   661  	for _, dns := range certificate.Certificate.DNSNames {
   662  		fmt.Printf("     - %s\n", dns)
   663  	}
   664  	fmt.Printf("   āœ“ IP addresses (%d):\n", len(certificate.Certificate.IPAddresses))
   665  	for _, ip := range certificate.Certificate.IPAddresses {
   666  		fmt.Printf("     - %s\n", ip.String())
   667  	}
   668  	fmt.Printf("   āœ“ Email addresses (%d):\n", len(certificate.Certificate.EmailAddresses))
   669  	for _, email := range certificate.Certificate.EmailAddresses {
   670  		fmt.Printf("     - %s\n", email)
   671  	}
   672  
   673  	fmt.Println("\n4.2 Domain-Specific SAN Patterns")
   674  
   675  	// Web server certificate pattern
   676  	fmt.Printf("   → Creating web server certificate pattern...\n")
   677  	webServerCert := createSANPattern("web-server", []string{
   678  		"example.com",
   679  		"www.example.com",
   680  		"api.example.com",
   681  		"cdn.example.com",
   682  	}, []net.IP{
   683  		net.IPv4(203, 0, 113, 10),
   684  	}, []string{
   685  		"webmaster@example.com",
   686  	})
   687  	if webServerCert != nil {
   688  		fmt.Printf("     āœ“ Web server certificate created with production-ready SAN\n")
   689  	}
   690  
   691  	// API service certificate pattern
   692  	fmt.Printf("   → Creating API service certificate pattern...\n")
   693  	apiServiceCert := createSANPattern("api-service", []string{
   694  		"api.service.internal",
   695  		"api-v1.service.internal",
   696  		"api-v2.service.internal",
   697  		"*.microservice.internal",
   698  	}, []net.IP{
   699  		net.IPv4(10, 0, 1, 100),
   700  		net.IPv4(10, 0, 1, 101),
   701  	}, []string{
   702  		"api-admin@service.internal",
   703  	})
   704  	if apiServiceCert != nil {
   705  		fmt.Printf("     āœ“ API service certificate created with microservice SAN\n")
   706  	}
   707  
   708  	// Development certificate pattern
   709  	fmt.Printf("   → Creating development certificate pattern...\n")
   710  	devCert := createSANPattern("development", []string{
   711  		"localhost",
   712  		"dev.local",
   713  		"*.dev.local",
   714  		"test.local",
   715  	}, []net.IP{
   716  		net.IPv4(127, 0, 0, 1),
   717  		net.IPv6loopback,
   718  		net.IPv4(192, 168, 1, 10),
   719  	}, []string{
   720  		"developer@dev.local",
   721  	})
   722  	if devCert != nil {
   723  		fmt.Printf("     āœ“ Development certificate created with local development SAN\n")
   724  	}
   725  }
   726  
   727  func createSANPattern(name string, dnsNames []string, ipAddresses []net.IP, emailAddresses []string) *cert.Certificate {
   728  	keyPair, err := algo.GenerateECDSAKeyPair(algo.P256)
   729  	if err != nil {
   730  		log.Printf("Failed to generate key pair for %s: %v\n", name, err)
   731  		return nil
   732  	}
   733  
   734  	request := cert.CertificateRequest{
   735  		Subject: pkix.Name{
   736  			Organization: []string{"GoPKI SAN Examples"},
   737  			CommonName:   fmt.Sprintf("%s.gopki.example.com", name),
   738  		},
   739  		DNSNames:     dnsNames,
   740  		IPAddresses:  ipAddresses,
   741  		EmailAddress: emailAddresses,
   742  		ValidFrom:    time.Now(),
   743  		ValidFor:     365 * 24 * time.Hour,
   744  	}
   745  
   746  	certificate, err := cert.CreateSelfSignedCertificate(keyPair, request)
   747  	if err != nil {
   748  		log.Printf("Failed to create %s certificate: %v\n", name, err)
   749  		return nil
   750  	}
   751  
   752  	filename := fmt.Sprintf("output/%s_san_cert.pem", name)
   753  	err = certificate.SaveToFile(filename)
   754  	if err != nil {
   755  		log.Printf("Failed to save %s certificate: %v\n", name, err)
   756  		return nil
   757  	}
   758  
   759  	return certificate
   760  }
   761  
   762  // PART 5: Format Operations
   763  func demonstrateFormatOperations() {
   764  	fmt.Println("\n5.1 PEM vs DER Format Comparison")
   765  
   766  	// Create a certificate for format testing
   767  	keyPair, err := algo.GenerateRSAKeyPair(algo.KeySize2048)
   768  	if err != nil {
   769  		log.Printf("Failed to generate key pair: %v\n", err)
   770  		return
   771  	}
   772  
   773  	request := cert.CertificateRequest{
   774  		Subject: pkix.Name{
   775  			Organization: []string{"Format Testing"},
   776  			CommonName:   "format-test.gopki.example.com",
   777  		},
   778  		DNSNames:  []string{"format-test.gopki.example.com"},
   779  		ValidFrom: time.Now(),
   780  		ValidFor:  365 * 24 * time.Hour,
   781  	}
   782  
   783  	certificate, err := cert.CreateSelfSignedCertificate(keyPair, request)
   784  	if err != nil {
   785  		log.Printf("Failed to create certificate: %v\n", err)
   786  		return
   787  	}
   788  
   789  	// Save in PEM format
   790  	err = certificate.SaveToFile("output/format_test.pem")
   791  	if err != nil {
   792  		log.Printf("Failed to save PEM certificate: %v\n", err)
   793  		return
   794  	}
   795  
   796  	// Save in DER format
   797  	err = certificate.SaveToDERFile("output/format_test.der")
   798  	if err != nil {
   799  		log.Printf("Failed to save DER certificate: %v\n", err)
   800  		return
   801  	}
   802  
   803  	// Compare file sizes
   804  	pemInfo, err := os.Stat("output/format_test.pem")
   805  	if err != nil {
   806  		log.Printf("Failed to stat PEM file: %v\n", err)
   807  		return
   808  	}
   809  
   810  	derInfo, err := os.Stat("output/format_test.der")
   811  	if err != nil {
   812  		log.Printf("Failed to stat DER file: %v\n", err)
   813  		return
   814  	}
   815  
   816  	fmt.Printf("   āœ“ Certificate saved in both formats\n")
   817  	fmt.Printf("   āœ“ PEM format: %d bytes (human-readable)\n", pemInfo.Size())
   818  	fmt.Printf("   āœ“ DER format: %d bytes (binary)\n", derInfo.Size())
   819  	fmt.Printf("   āœ“ DER is %.1f%% smaller than PEM\n",
   820  		(1.0-float64(derInfo.Size())/float64(pemInfo.Size()))*100)
   821  
   822  	fmt.Println("\n5.2 Format Conversion Operations")
   823  
   824  	// Test PEM to DER conversion
   825  	fmt.Printf("   → Testing PEM to DER conversion...\n")
   826  	pemData := certificate.ToPEM()
   827  	derData, err := cert.ConvertPEMToDER(pemData)
   828  	if err != nil {
   829  		log.Printf("Failed to convert PEM to DER: %v\n", err)
   830  		return
   831  	}
   832  
   833  	// Save converted DER
   834  	err = os.WriteFile("output/converted_to_der.der", derData, 0644)
   835  	if err != nil {
   836  		log.Printf("Failed to write converted DER: %v\n", err)
   837  		return
   838  	}
   839  	fmt.Printf("     āœ“ PEM to DER conversion successful (%d bytes)\n", len(derData))
   840  
   841  	// Test DER to PEM conversion
   842  	fmt.Printf("   → Testing DER to PEM conversion...\n")
   843  	originalDER := certificate.ToDER()
   844  	convertedPEM, err := cert.ConvertDERToPEM(originalDER)
   845  	if err != nil {
   846  		log.Printf("Failed to convert DER to PEM: %v\n", err)
   847  		return
   848  	}
   849  
   850  	// Save converted PEM
   851  	err = os.WriteFile("output/converted_to_pem.pem", convertedPEM, 0644)
   852  	if err != nil {
   853  		log.Printf("Failed to write converted PEM: %v\n", err)
   854  		return
   855  	}
   856  	fmt.Printf("     āœ“ DER to PEM conversion successful (%d bytes)\n", len(convertedPEM))
   857  
   858  	fmt.Println("\n5.3 Format Loading and Parsing")
   859  
   860  	// Test loading from PEM file
   861  	fmt.Printf("   → Testing PEM file loading...\n")
   862  	loadedFromPEM, err := cert.LoadCertificateFromFile("output/format_test.pem")
   863  	if err != nil {
   864  		log.Printf("Failed to load from PEM file: %v\n", err)
   865  		return
   866  	}
   867  	fmt.Printf("     āœ“ PEM file loaded successfully\n")
   868  	fmt.Printf("     āœ“ Subject: %s\n", loadedFromPEM.Certificate.Subject.CommonName)
   869  
   870  	// Test loading from DER file
   871  	fmt.Printf("   → Testing DER file loading...\n")
   872  	loadedFromDER, err := cert.LoadCertificateFromDERFile("output/format_test.der")
   873  	if err != nil {
   874  		log.Printf("Failed to load from DER file: %v\n", err)
   875  		return
   876  	}
   877  	fmt.Printf("     āœ“ DER file loaded successfully\n")
   878  	fmt.Printf("     āœ“ Subject: %s\n", loadedFromDER.Certificate.Subject.CommonName)
   879  
   880  	// Verify both loaded certificates are identical
   881  	if loadedFromPEM.Certificate.Subject.CommonName == loadedFromDER.Certificate.Subject.CommonName &&
   882  		loadedFromPEM.Certificate.SerialNumber.Cmp(loadedFromDER.Certificate.SerialNumber) == 0 {
   883  		fmt.Printf("     āœ“ Both formats contain identical certificate data\n")
   884  	} else {
   885  		fmt.Printf("     āŒ Format loading mismatch detected\n")
   886  	}
   887  
   888  	fmt.Println("\n5.4 Performance Comparison")
   889  
   890  	fmt.Printf("   → Measuring format operation performance...\n")
   891  
   892  	// Measure PEM parsing performance
   893  	pemStart := time.Now()
   894  	for i := 0; i < 100; i++ {
   895  		_, err := cert.ParseCertificateFromPEM(pemData)
   896  		if err != nil {
   897  			break
   898  		}
   899  	}
   900  	pemDuration := time.Since(pemStart)
   901  
   902  	// Measure DER parsing performance
   903  	derStart := time.Now()
   904  	for i := 0; i < 100; i++ {
   905  		_, err := cert.ParseCertificateFromDER(originalDER)
   906  		if err != nil {
   907  			break
   908  		}
   909  	}
   910  	derDuration := time.Since(derStart)
   911  
   912  	fmt.Printf("     āœ“ PEM parsing (100 iterations): %.2fms\n", float64(pemDuration.Nanoseconds())/1000000)
   913  	fmt.Printf("     āœ“ DER parsing (100 iterations): %.2fms\n", float64(derDuration.Nanoseconds())/1000000)
   914  
   915  	if derDuration < pemDuration {
   916  		speedup := float64(pemDuration) / float64(derDuration)
   917  		fmt.Printf("     āœ“ DER parsing is %.1fx faster than PEM\n", speedup)
   918  	}
   919  }
   920  
   921  // PART 6: PKCS#12 Integration
   922  func demonstratePKCS12Integration() {
   923  	fmt.Println("\n6.1 PKCS#12 Certificate Bundle Creation")
   924  
   925  	// Create a certificate and key pair for PKCS#12 testing
   926  	keyPair, err := algo.GenerateRSAKeyPair(algo.KeySize2048)
   927  	if err != nil {
   928  		log.Printf("Failed to generate key pair: %v\n", err)
   929  		return
   930  	}
   931  
   932  	request := cert.CertificateRequest{
   933  		Subject: pkix.Name{
   934  			Organization: []string{"PKCS#12 Testing"},
   935  			CommonName:   "pkcs12-test.gopki.example.com",
   936  		},
   937  		DNSNames:  []string{"pkcs12-test.gopki.example.com"},
   938  		ValidFrom: time.Now(),
   939  		ValidFor:  365 * 24 * time.Hour,
   940  	}
   941  
   942  	certificate, err := cert.CreateSelfSignedCertificate(keyPair, request)
   943  	if err != nil {
   944  		log.Printf("Failed to create certificate: %v\n", err)
   945  		return
   946  	}
   947  
   948  	// Save to PKCS#12 format
   949  	fmt.Printf("   → Creating PKCS#12 bundle...\n")
   950  	password := "test-password-123"
   951  	err = pkcs12.SaveCertToP12(certificate, keyPair.PrivateKey, "output/certificate.p12", password)
   952  	if err != nil {
   953  		log.Printf("Failed to save PKCS#12 bundle: %v\n", err)
   954  		return
   955  	}
   956  	fmt.Printf("     āœ“ PKCS#12 bundle created: output/certificate.p12\n")
   957  	fmt.Printf("     āœ“ Password: %s\n", password)
   958  
   959  	fmt.Println("\n6.2 PKCS#12 Bundle Loading and Extraction")
   960  
   961  	// Load certificate from PKCS#12
   962  	fmt.Printf("   → Loading certificate from PKCS#12...\n")
   963  	loadedCert, _, err := pkcs12.FromP12CertFile("output/certificate.p12", password)
   964  	if err != nil {
   965  		log.Printf("Failed to load from PKCS#12: %v\n", err)
   966  		return
   967  	}
   968  	fmt.Printf("     āœ“ Certificate loaded from PKCS#12\n")
   969  	fmt.Printf("     āœ“ Subject: %s\n", loadedCert.Certificate.Subject.CommonName)
   970  
   971  	// Extract and save to PEM format
   972  	fmt.Printf("   → Extracting PKCS#12 contents to PEM files...\n")
   973  	err = pkcs12.ExtractCertificatesFromP12("output/certificate.p12", password, "output/extracted/")
   974  	if err != nil {
   975  		log.Printf("Failed to extract PKCS#12 contents: %v\n", err)
   976  		return
   977  	}
   978  	fmt.Printf("     āœ“ PKCS#12 contents extracted to output/extracted/\n")
   979  
   980  	fmt.Println("\n6.3 PKCS#12 Certificate Chain Bundle")
   981  
   982  	// Create a certificate chain and save to PKCS#12
   983  	fmt.Printf("   → Creating certificate chain bundle...\n")
   984  
   985  	// Load the CA certificate created earlier
   986  	caCert, err := cert.LoadCertificateFromFile("output/root_ca.pem")
   987  	if err != nil {
   988  		log.Printf("Failed to load CA certificate: %v\n", err)
   989  		return
   990  	}
   991  
   992  	// Create chain array
   993  	caCerts := []*cert.Certificate{caCert}
   994  
   995  	// Save certificate with chain to PKCS#12
   996  	chainPassword := "chain-password-456"
   997  	err = pkcs12.SaveCertToP12WithChain(certificate, keyPair.PrivateKey, caCerts, "output/certificate_with_chain.p12", chainPassword)
   998  	if err != nil {
   999  		log.Printf("Failed to save certificate chain to PKCS#12: %v\n", err)
  1000  		return
  1001  	}
  1002  	fmt.Printf("     āœ“ Certificate chain bundle created: output/certificate_with_chain.p12\n")
  1003  	fmt.Printf("     āœ“ Chain password: %s\n", chainPassword)
  1004  
  1005  	// Load certificate chain from PKCS#12
  1006  	fmt.Printf("   → Loading certificate chain from PKCS#12...\n")
  1007  	certChain, err := pkcs12.LoadCertificateChainFromP12("output/certificate_with_chain.p12", chainPassword)
  1008  	if err != nil {
  1009  		log.Printf("Failed to load certificate chain: %v\n", err)
  1010  		return
  1011  	}
  1012  	fmt.Printf("     āœ“ Certificate chain loaded (%d certificates)\n", len(certChain))
  1013  	for i, cert := range certChain {
  1014  		fmt.Printf("       [%d] %s\n", i, cert.Certificate.Subject.CommonName)
  1015  	}
  1016  
  1017  	fmt.Println("\n6.4 PKCS#12 Validation and Metadata")
  1018  
  1019  	// Validate PKCS#12 file
  1020  	fmt.Printf("   → Validating PKCS#12 files...\n")
  1021  	metadata, err := pkcs12.ValidateP12Certificate("output/certificate.p12", password)
  1022  	if err != nil {
  1023  		log.Printf("Failed to validate PKCS#12: %v\n", err)
  1024  		return
  1025  	}
  1026  	fmt.Printf("     āœ“ PKCS#12 validation successful\n")
  1027  	fmt.Printf("     āœ“ Metadata:\n")
  1028  	for key, value := range metadata {
  1029  		fmt.Printf("       - %s: %v\n", key, value)
  1030  	}
  1031  }
  1032  
  1033  // PART 7: Certificate Validation
  1034  func demonstrateCertificateValidation() {
  1035  	fmt.Println("\n7.1 Certificate Chain Validation")
  1036  
  1037  	// Load certificates for validation testing
  1038  	fmt.Printf("   → Loading certificates for validation...\n")
  1039  
  1040  	rootCA, err := cert.LoadCertificateFromFile("output/root_ca.pem")
  1041  	if err != nil {
  1042  		log.Printf("Failed to load root CA: %v\n", err)
  1043  		return
  1044  	}
  1045  
  1046  	serverCert, err := cert.LoadCertificateFromFile("output/server.pem")
  1047  	if err != nil {
  1048  		log.Printf("Failed to load server certificate: %v\n", err)
  1049  		return
  1050  	}
  1051  
  1052  	// Validate server certificate against root CA
  1053  	fmt.Printf("   → Validating server certificate against root CA...\n")
  1054  	err = cert.VerifyCertificate(serverCert, rootCA)
  1055  	if err != nil {
  1056  		fmt.Printf("     āŒ Validation failed: %v\n", err)
  1057  	} else {
  1058  		fmt.Printf("     āœ“ Server certificate is valid\n")
  1059  		fmt.Printf("     āœ“ Issuer: %s\n", serverCert.Certificate.Issuer.CommonName)
  1060  		fmt.Printf("     āœ“ Subject: %s\n", serverCert.Certificate.Subject.CommonName)
  1061  	}
  1062  
  1063  	fmt.Println("\n7.2 Certificate Expiration Checking")
  1064  
  1065  	fmt.Printf("   → Checking certificate validity periods...\n")
  1066  
  1067  	certificates := []struct {
  1068  		name string
  1069  		cert *cert.Certificate
  1070  	}{
  1071  		{"Root CA", rootCA},
  1072  		{"Server", serverCert},
  1073  	}
  1074  
  1075  	now := time.Now()
  1076  	for _, certInfo := range certificates {
  1077  		certData := certInfo.cert
  1078  		fmt.Printf("     %s Certificate:\n", certInfo.name)
  1079  		fmt.Printf("       - Valid from: %s\n", certData.Certificate.NotBefore.Format("2006-01-02 15:04:05"))
  1080  		fmt.Printf("       - Valid until: %s\n", certData.Certificate.NotAfter.Format("2006-01-02 15:04:05"))
  1081  
  1082  		if now.Before(certData.Certificate.NotBefore) {
  1083  			fmt.Printf("       - Status: āŒ Not yet valid\n")
  1084  		} else if now.After(certData.Certificate.NotAfter) {
  1085  			fmt.Printf("       - Status: āŒ Expired\n")
  1086  		} else {
  1087  			daysLeft := int(certData.Certificate.NotAfter.Sub(now).Hours() / 24)
  1088  			fmt.Printf("       - Status: āœ… Valid (%d days remaining)\n", daysLeft)
  1089  		}
  1090  	}
  1091  
  1092  	fmt.Println("\n7.3 Certificate Information Extraction")
  1093  
  1094  	fmt.Printf("   → Extracting detailed certificate information...\n")
  1095  
  1096  	// Analyze the server certificate in detail
  1097  	certDetails := serverCert.Certificate
  1098  	fmt.Printf("     Certificate Analysis:\n")
  1099  	fmt.Printf("       - Serial Number: %s\n", certDetails.SerialNumber.String())
  1100  	fmt.Printf("       - Signature Algorithm: %s\n", certDetails.SignatureAlgorithm.String())
  1101  	fmt.Printf("       - Public Key Algorithm: %s\n", certDetails.PublicKeyAlgorithm.String())
  1102  	fmt.Printf("       - Version: %d\n", certDetails.Version)
  1103  	fmt.Printf("       - Is CA: %v\n", certDetails.IsCA)
  1104  
  1105  	if len(certDetails.DNSNames) > 0 {
  1106  		fmt.Printf("       - DNS Names: %v\n", certDetails.DNSNames)
  1107  	}
  1108  	if len(certDetails.IPAddresses) > 0 {
  1109  		fmt.Printf("       - IP Addresses: %v\n", certDetails.IPAddresses)
  1110  	}
  1111  	if len(certDetails.EmailAddresses) > 0 {
  1112  		fmt.Printf("       - Email Addresses: %v\n", certDetails.EmailAddresses)
  1113  	}
  1114  
  1115  	// Calculate and display certificate fingerprints
  1116  	fmt.Printf("       - SHA-256 Fingerprint: %x\n", certDetails.Raw[:32]) // First 32 bytes as example
  1117  
  1118  	fmt.Println("\n7.4 Invalid Certificate Testing")
  1119  
  1120  	fmt.Printf("   → Testing validation with invalid scenarios...\n")
  1121  
  1122  	// Create a self-signed certificate that shouldn't validate against the CA
  1123  	invalidKeyPair, err := algo.GenerateECDSAKeyPair(algo.P256)
  1124  	if err != nil {
  1125  		log.Printf("Failed to generate invalid certificate key pair: %v\n", err)
  1126  		return
  1127  	}
  1128  
  1129  	invalidRequest := cert.CertificateRequest{
  1130  		Subject: pkix.Name{
  1131  			CommonName: "invalid-cert.example.com",
  1132  		},
  1133  		ValidFrom: time.Now(),
  1134  		ValidFor:  365 * 24 * time.Hour,
  1135  	}
  1136  
  1137  	invalidCert, err := cert.CreateSelfSignedCertificate(invalidKeyPair, invalidRequest)
  1138  	if err != nil {
  1139  		log.Printf("Failed to create invalid certificate: %v\n", err)
  1140  		return
  1141  	}
  1142  
  1143  	// Try to validate this self-signed certificate against the CA (should fail)
  1144  	err = cert.VerifyCertificate(invalidCert, rootCA)
  1145  	if err != nil {
  1146  		fmt.Printf("     āœ“ Invalid certificate correctly rejected: %v\n", err)
  1147  	} else {
  1148  		fmt.Printf("     āŒ ERROR: Invalid certificate was incorrectly accepted\n")
  1149  	}
  1150  }
  1151  
  1152  // PART 8: Integration & Advanced Features
  1153  func demonstrateIntegrationFeatures() {
  1154  	fmt.Println("\n8.1 Certificate-KeyPair Integration")
  1155  
  1156  	fmt.Printf("   → Demonstrating seamless certificate-keypair integration...\n")
  1157  
  1158  	// Generate keys with different algorithms
  1159  	algorithms := []struct {
  1160  		name    string
  1161  		genFunc func() (interface{}, error)
  1162  	}{
  1163  		{"RSA", func() (interface{}, error) { return algo.GenerateRSAKeyPair(algo.KeySize2048) }},
  1164  		{"ECDSA", func() (interface{}, error) { return algo.GenerateECDSAKeyPair(algo.P256) }},
  1165  		{"Ed25519", func() (interface{}, error) { return algo.GenerateEd25519KeyPair() }},
  1166  	}
  1167  
  1168  	for _, alg := range algorithms {
  1169  		fmt.Printf("     → Creating %s certificate with integrated key management...\n", alg.name)
  1170  
  1171  		keyPairInterface, err := alg.genFunc()
  1172  		if err != nil {
  1173  			log.Printf("Failed to generate %s key pair: %v\n", alg.name, err)
  1174  			continue
  1175  		}
  1176  
  1177  		request := cert.CertificateRequest{
  1178  			Subject: pkix.Name{
  1179  				Organization: []string{"Integration Testing"},
  1180  				CommonName:   fmt.Sprintf("%s Integration Test", alg.name),
  1181  			},
  1182  			ValidFrom: time.Now(),
  1183  			ValidFor:  365 * 24 * time.Hour,
  1184  		}
  1185  
  1186  		var certificate *cert.Certificate
  1187  		var keyFilename string
  1188  
  1189  		switch keyPair := keyPairInterface.(type) {
  1190  		case *algo.RSAKeyPair:
  1191  			certificate, err = cert.CreateSelfSignedCertificate(keyPair, request)
  1192  			if err == nil {
  1193  				err = keypair.ToPEMFiles(keyPair, "output/integration_rsa_private.pem", "output/integration_rsa_public.pem")
  1194  				keyFilename = "output/integration_rsa_private.pem"
  1195  			}
  1196  		case *algo.ECDSAKeyPair:
  1197  			certificate, err = cert.CreateSelfSignedCertificate(keyPair, request)
  1198  			if err == nil {
  1199  				err = keypair.ToPEMFiles(keyPair, "output/integration_ecdsa_private.pem", "output/integration_ecdsa_public.pem")
  1200  				keyFilename = "output/integration_ecdsa_private.pem"
  1201  			}
  1202  		case *algo.Ed25519KeyPair:
  1203  			certificate, err = cert.CreateSelfSignedCertificate(keyPair, request)
  1204  			if err == nil {
  1205  				err = keypair.ToPEMFiles(keyPair, "output/integration_ed25519_private.pem", "output/integration_ed25519_public.pem")
  1206  				keyFilename = "output/integration_ed25519_private.pem"
  1207  			}
  1208  		}
  1209  
  1210  		if err != nil {
  1211  			log.Printf("Failed to create %s certificate or save keys: %v\n", alg.name, err)
  1212  			continue
  1213  		}
  1214  
  1215  		certFilename := fmt.Sprintf("output/integration_%s_cert.pem", strings.ToLower(alg.name))
  1216  		err = certificate.SaveToFile(certFilename)
  1217  		if err != nil {
  1218  			log.Printf("Failed to save %s certificate: %v\n", alg.name, err)
  1219  			continue
  1220  		}
  1221  
  1222  		fmt.Printf("       āœ“ %s certificate and key pair created\n", alg.name)
  1223  		fmt.Printf("       āœ“ Certificate: %s\n", certFilename)
  1224  		fmt.Printf("       āœ“ Private key: %s\n", keyFilename)
  1225  	}
  1226  
  1227  	fmt.Println("\n8.2 Real-World TLS Server Setup Simulation")
  1228  
  1229  	fmt.Printf("   → Simulating complete TLS server certificate setup...\n")
  1230  
  1231  	// Create a production-like server certificate
  1232  	serverKeyPair, err := algo.GenerateECDSAKeyPair(algo.P256)
  1233  	if err != nil {
  1234  		log.Printf("Failed to generate server key pair: %v\n", err)
  1235  		return
  1236  	}
  1237  
  1238  	serverRequest := cert.CertificateRequest{
  1239  		Subject: pkix.Name{
  1240  			Country:            []string{"US"},
  1241  			Province:           []string{"California"},
  1242  			Locality:           []string{"San Francisco"},
  1243  			Organization:       []string{"GoPKI Production Services"},
  1244  			OrganizationalUnit: []string{"Web Services"},
  1245  			CommonName:         "api.production.gopki.com",
  1246  		},
  1247  		DNSNames: []string{
  1248  			"api.production.gopki.com",
  1249  			"www.production.gopki.com",
  1250  			"cdn.production.gopki.com",
  1251  			"admin.production.gopki.com",
  1252  		},
  1253  		IPAddresses: []net.IP{
  1254  			net.IPv4(203, 0, 113, 10), // Example public IP
  1255  			net.IPv4(203, 0, 113, 11), // Load balancer IP
  1256  		},
  1257  		EmailAddress: []string{
  1258  			"admin@production.gopki.com",
  1259  			"security@production.gopki.com",
  1260  		},
  1261  		ValidFrom: time.Now(),
  1262  		ValidFor:  2 * 365 * 24 * time.Hour, // 2 years
  1263  	}
  1264  
  1265  	// Load the CA for signing
  1266  	rootCA, err := cert.LoadCertificateFromFile("output/root_ca.pem")
  1267  	if err != nil {
  1268  		log.Printf("Failed to load root CA: %v\n", err)
  1269  		return
  1270  	}
  1271  
  1272  	// Load CA private key
  1273  	caKeyData, err := os.ReadFile("output/root_ca_private.pem")
  1274  	if err != nil {
  1275  		log.Printf("Failed to read CA private key: %v\n", err)
  1276  		return
  1277  	}
  1278  
  1279  	// Parse RSA key from PEM data
  1280  	parsedCAKey, err := algo.RSAKeyPairFromPEM(format.PEM(caKeyData))
  1281  	if err != nil {
  1282  		log.Printf("Failed to parse CA private key: %v\n", err)
  1283  		return
  1284  	}
  1285  	caKey := parsedCAKey
  1286  
  1287  	// Sign server certificate with CA
  1288  	serverCert, err := cert.SignCertificate(rootCA, caKey, serverRequest, &serverKeyPair.PrivateKey.PublicKey)
  1289  	if err != nil {
  1290  		log.Printf("Failed to sign server certificate: %v\n", err)
  1291  		return
  1292  	}
  1293  
  1294  	// Save production server certificate and key
  1295  	err = serverCert.SaveToFile("output/production_server.pem")
  1296  	if err != nil {
  1297  		log.Printf("Failed to save production server certificate: %v\n", err)
  1298  		return
  1299  	}
  1300  
  1301  	err = keypair.ToPEMFiles(serverKeyPair, "output/production_server_private.pem", "output/production_server_public.pem")
  1302  	if err != nil {
  1303  		log.Printf("Failed to save production server keys: %v\n", err)
  1304  		return
  1305  	}
  1306  
  1307  	fmt.Printf("     āœ“ Production TLS server certificate created\n")
  1308  	fmt.Printf("     āœ“ Subject: %s\n", serverCert.Certificate.Subject.CommonName)
  1309  	fmt.Printf("     āœ“ SAN domains: %v\n", serverCert.Certificate.DNSNames)
  1310  	fmt.Printf("     āœ“ Valid for: 2 years\n")
  1311  	fmt.Printf("     āœ“ Ready for TLS server deployment\n")
  1312  
  1313  	fmt.Println("\n8.3 Certificate Metadata and Analytics")
  1314  
  1315  	fmt.Printf("   → Analyzing certificate collection metrics...\n")
  1316  
  1317  	// Scan output directory for certificates
  1318  	files, err := os.ReadDir("output")
  1319  	if err != nil {
  1320  		log.Printf("Failed to read output directory: %v\n", err)
  1321  		return
  1322  	}
  1323  
  1324  	var certFiles []string
  1325  	for _, file := range files {
  1326  		if strings.HasSuffix(file.Name(), ".pem") && !strings.Contains(file.Name(), "private") && !strings.Contains(file.Name(), "public") {
  1327  			certFiles = append(certFiles, file.Name())
  1328  		}
  1329  	}
  1330  
  1331  	fmt.Printf("     āœ“ Found %d certificate files\n", len(certFiles))
  1332  
  1333  	algorithmCounts := make(map[string]int)
  1334  	var totalCerts int
  1335  	var caCerts int
  1336  	var selfSignedCerts int
  1337  
  1338  	for _, certFile := range certFiles {
  1339  		certPath := fmt.Sprintf("output/%s", certFile)
  1340  		certificate, err := cert.LoadCertificateFromFile(certPath)
  1341  		if err != nil {
  1342  			continue
  1343  		}
  1344  
  1345  		totalCerts++
  1346  
  1347  		// Count by algorithm
  1348  		alg := certificate.Certificate.PublicKeyAlgorithm.String()
  1349  		algorithmCounts[alg]++
  1350  
  1351  		// Count CA certificates
  1352  		if certificate.Certificate.IsCA {
  1353  			caCerts++
  1354  		}
  1355  
  1356  		// Count self-signed (issuer == subject)
  1357  		if certificate.Certificate.Issuer.CommonName == certificate.Certificate.Subject.CommonName {
  1358  			selfSignedCerts++
  1359  		}
  1360  	}
  1361  
  1362  	fmt.Printf("     āœ“ Certificate Collection Analytics:\n")
  1363  	fmt.Printf("       - Total certificates: %d\n", totalCerts)
  1364  	fmt.Printf("       - CA certificates: %d\n", caCerts)
  1365  	fmt.Printf("       - Self-signed certificates: %d\n", selfSignedCerts)
  1366  	fmt.Printf("       - End-entity certificates: %d\n", totalCerts-selfSignedCerts)
  1367  	fmt.Printf("     āœ“ Algorithm distribution:\n")
  1368  	for alg, count := range algorithmCounts {
  1369  		percentage := float64(count) / float64(totalCerts) * 100
  1370  		fmt.Printf("       - %s: %d (%.1f%%)\n", alg, count, percentage)
  1371  	}
  1372  
  1373  	fmt.Println("\n8.4 Integration Summary and Best Practices")
  1374  
  1375  	fmt.Printf("   → Certificate module integration summary...\n")
  1376  	fmt.Printf("     āœ“ Multi-algorithm support demonstrated (RSA, ECDSA, Ed25519)\n")
  1377  	fmt.Printf("     āœ“ Complete CA hierarchy created (Root → Intermediate → End-entity)\n")
  1378  	fmt.Printf("     āœ“ Complex SAN configurations working correctly\n")
  1379  	fmt.Printf("     āœ“ Format operations (PEM/DER) functioning properly\n")
  1380  	fmt.Printf("     āœ“ PKCS#12 integration for certificate distribution\n")
  1381  	fmt.Printf("     āœ“ Certificate validation and chain verification working\n")
  1382  	fmt.Printf("     āœ“ Production-ready TLS server setup demonstrated\n")
  1383  
  1384  	fmt.Printf("\n     Best Practices Demonstrated:\n")
  1385  	fmt.Printf("       • Use ECDSA P-256+ or Ed25519 for new certificates\n")
  1386  	fmt.Printf("       • Implement proper CA hierarchies with path length constraints\n")
  1387  	fmt.Printf("       • Use comprehensive SAN for multi-domain certificates\n")
  1388  	fmt.Printf("       • Store certificates in DER format for performance\n")
  1389  	fmt.Printf("       • Use PKCS#12 for secure certificate distribution\n")
  1390  	fmt.Printf("       • Implement proper certificate validation workflows\n")
  1391  	fmt.Printf("       • Regular certificate expiration monitoring\n")
  1392  }