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

     1  //go:build example
     2  
     3  package main
     4  
     5  import (
     6  	"crypto"
     7  	"crypto/ecdsa"
     8  	"crypto/ed25519"
     9  	"crypto/rand"
    10  	"crypto/rsa"
    11  	"crypto/x509"
    12  	"crypto/x509/pkix"
    13  	"encoding/base64"
    14  	"encoding/json"
    15  	"fmt"
    16  	"log"
    17  	"os"
    18  	"strings"
    19  	"time"
    20  
    21  	"github.com/jasoet/gopki/cert"
    22  	"github.com/jasoet/gopki/keypair"
    23  	"github.com/jasoet/gopki/keypair/algo"
    24  	"github.com/jasoet/gopki/signing"
    25  )
    26  
    27  func main() {
    28  	fmt.Println("=== GoPKI Document Signing Module - Comprehensive Examples ===")
    29  	fmt.Println("Demonstrating hybrid approach: PKCS#7 for RSA/ECDSA, raw signatures for Ed25519 (not PKCS#7)")
    30  
    31  	// Create output directory
    32  	if err := os.MkdirAll("output", 0755); err != nil {
    33  		log.Fatal("Failed to create output directory:", err)
    34  	}
    35  
    36  	// Execute all signing examples
    37  	fmt.Println("\nšŸ” PART 1: Multi-Algorithm Document Signing")
    38  	fmt.Println(strings.Repeat("=", 60))
    39  	demonstrateMultiAlgorithmSigning()
    40  
    41  	fmt.Println("\nšŸ“‹ PART 2: Advanced Signing Options")
    42  	fmt.Println(strings.Repeat("=", 60))
    43  	demonstrateAdvancedSigningOptions()
    44  
    45  	fmt.Println("\nāœ… PART 3: Signature Verification & Security")
    46  	fmt.Println(strings.Repeat("=", 60))
    47  	demonstrateSignatureVerification()
    48  
    49  	fmt.Println("\nšŸ“ PART 4: Multi-Party Signatures (Co-signing)")
    50  	fmt.Println(strings.Repeat("=", 60))
    51  	demonstrateMultipleSignatures()
    52  
    53  	fmt.Println("\nšŸ”’ PART 5: PKCS#7 Format & Certificate Chains")
    54  	fmt.Println(strings.Repeat("=", 60))
    55  	demonstratePKCS7FormatExamples()
    56  
    57  	fmt.Println("\nšŸš€ PART 6: Performance & Large Documents")
    58  	fmt.Println(strings.Repeat("=", 60))
    59  	demonstratePerformanceComparison()
    60  
    61  	fmt.Println("\nšŸ“ PART 7: File Operations & Detached Signatures")
    62  	fmt.Println(strings.Repeat("=", 60))
    63  	demonstrateFileOperations()
    64  
    65  	fmt.Println("\n\n=" + strings.Repeat("=", 58) + "=")
    66  	fmt.Println("āœ… ALL EXAMPLES COMPLETED SUCCESSFULLY!")
    67  	fmt.Println("šŸ“ Output files saved in: ./output/")
    68  	fmt.Println("šŸ” Review signature formats and certificate integration")
    69  	fmt.Println("=" + strings.Repeat("=", 58) + "=")
    70  }
    71  
    72  func demonstrateMultiAlgorithmSigning() {
    73  	fmt.Println("1. RSA Document Signing (PKCS#7 Format)")
    74  	fmt.Println("----------------------------------------")
    75  	demonstrateRSASigning()
    76  
    77  	fmt.Println("2. ECDSA Document Signing (PKCS#7 Format)")
    78  	fmt.Println("-----------------------------------------")
    79  	demonstrateECDSASigning()
    80  
    81  	fmt.Println("3. Ed25519 Document Signing (Raw Signatures - Not PKCS#7)")
    82  	fmt.Println("---------------------------------------------------------")
    83  	demonstrateEd25519Signing()
    84  }
    85  
    86  func demonstrateRSASigning() {
    87  	// Generate RSA key pair using the generic API
    88  	keyManager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048)
    89  	if err != nil {
    90  		log.Fatal("Failed to generate RSA key pair:", err)
    91  	}
    92  	keyPair := keyManager.KeyPair()
    93  	fmt.Println("āœ“ Generated 2048-bit RSA key pair using type-safe API")
    94  
    95  	// Create a certificate for signing
    96  	certificate, err := cert.CreateSelfSignedCertificate(keyPair, cert.CertificateRequest{
    97  		Subject: pkix.Name{
    98  			CommonName:         "RSA Document Signer",
    99  			Organization:       []string{"Example Corp"},
   100  			OrganizationalUnit: []string{"Security Division"},
   101  			Country:            []string{"US"},
   102  		},
   103  		EmailAddress: []string{"signer@example.com"},
   104  		ValidFor:     365 * 24 * time.Hour,
   105  	})
   106  	if err != nil {
   107  		log.Fatal("Failed to create certificate:", err)
   108  	}
   109  	fmt.Printf("āœ“ Created certificate for: %s\n", certificate.Certificate.Subject.CommonName)
   110  
   111  	// Document to sign
   112  	document := []byte(`{
   113  		"title": "Important Contract",
   114  		"date": "2024-01-15",
   115  		"parties": ["Example Corp", "Client Inc"],
   116  		"amount": 50000,
   117  		"currency": "USD"
   118  	}`)
   119  
   120  	// Sign the document using PKCS#7 format
   121  	signature, err := signing.SignData(document, keyPair, certificate)
   122  	if err != nil {
   123  		log.Fatal("Failed to sign document:", err)
   124  	}
   125  	fmt.Printf("āœ“ Signed document using %s with %s\n",
   126  		signature.Algorithm,
   127  		signing.HashAlgorithmToString(signature.HashAlgorithm))
   128  
   129  	// Save signature with PKCS#7 format details
   130  	saveSignature(signature, "output/rsa_signature.json")
   131  	fmt.Printf("  Format: %s (industry standard)\n", signature.Format)
   132  
   133  	// Verify the signature
   134  	err = signing.VerifySignature(document, signature, signing.DefaultVerifyOptions())
   135  	if err != nil {
   136  		log.Fatal("Signature verification failed:", err)
   137  	}
   138  	fmt.Println("āœ“ Signature verification successful")
   139  
   140  	// Save the certificate and keys
   141  	certificate.SaveToFile("output/rsa_signer.crt")
   142  	keypair.ToPEMFiles(keyPair, "output/rsa_private.pem", "output/rsa_public.pem")
   143  
   144  	fmt.Println()
   145  }
   146  
   147  func demonstrateECDSASigning() {
   148  	// Generate ECDSA key pair with P-256 curve using generic API
   149  	keyManager, err := keypair.Generate[algo.ECDSACurve, *algo.ECDSAKeyPair, *ecdsa.PrivateKey, *ecdsa.PublicKey](algo.P256)
   150  	if err != nil {
   151  		log.Fatal("Failed to generate ECDSA key pair:", err)
   152  	}
   153  	keyPair := keyManager.KeyPair()
   154  	fmt.Println("āœ“ Generated ECDSA key pair (P-256 curve) using type-safe API")
   155  
   156  	// Create a certificate
   157  	certificate, err := cert.CreateSelfSignedCertificate(keyPair, cert.CertificateRequest{
   158  		Subject: pkix.Name{
   159  			CommonName:   "ECDSA Document Signer",
   160  			Organization: []string{"Example Corp"},
   161  		},
   162  		ValidFor: 365 * 24 * time.Hour,
   163  	})
   164  	if err != nil {
   165  		log.Fatal("Failed to create certificate:", err)
   166  	}
   167  	fmt.Printf("āœ“ Created certificate for: %s\n", certificate.Certificate.Subject.CommonName)
   168  
   169  	// Document to sign
   170  	document := []byte("This is a confidential document that requires ECDSA signature.")
   171  
   172  	// Sign with PKCS#7 detached format options
   173  	opts := signing.SignOptions{
   174  		HashAlgorithm:      crypto.SHA256,
   175  		Format:             signing.FormatPKCS7Detached,
   176  		IncludeCertificate: true,
   177  		IncludeChain:       false,
   178  		Detached:           true,
   179  		Attributes: map[string]interface{}{
   180  			"documentType": "confidential",
   181  			"signedAt":     time.Now().Format(time.RFC3339),
   182  		},
   183  	}
   184  
   185  	signature, err := signing.SignDocument(document, keyPair, certificate, opts)
   186  	if err != nil {
   187  		log.Fatal("Failed to sign document:", err)
   188  	}
   189  	fmt.Printf("āœ“ Signed document using %s with %s\n",
   190  		signature.Algorithm,
   191  		signing.HashAlgorithmToString(signature.HashAlgorithm))
   192  
   193  	// Display signature size
   194  	fmt.Printf("  Signature size: %d bytes\n", len(signature.Data))
   195  
   196  	// Verify
   197  	err = signing.VerifySignature(document, signature, signing.DefaultVerifyOptions())
   198  	if err != nil {
   199  		log.Fatal("Verification failed:", err)
   200  	}
   201  	fmt.Println("āœ“ Signature verification successful")
   202  
   203  	// Save signature with format details
   204  	saveSignature(signature, "output/ecdsa_signature.json")
   205  	fmt.Printf("  Format: %s (detached PKCS#7)\n", signature.Format)
   206  
   207  	fmt.Println()
   208  }
   209  
   210  func demonstrateEd25519Signing() {
   211  	// Generate Ed25519 key pair using generic API
   212  	keyManager, err := keypair.Generate[algo.Ed25519Config, *algo.Ed25519KeyPair, ed25519.PrivateKey, ed25519.PublicKey](algo.Ed25519Default)
   213  	if err != nil {
   214  		log.Fatal("Failed to generate Ed25519 key pair:", err)
   215  	}
   216  	keyPair := keyManager.KeyPair()
   217  	fmt.Println("āœ“ Generated Ed25519 key pair using type-safe API")
   218  
   219  	// Create a certificate
   220  	certificate, err := cert.CreateSelfSignedCertificate(keyPair, cert.CertificateRequest{
   221  		Subject: pkix.Name{
   222  			CommonName:   "Ed25519 Document Signer",
   223  			Organization: []string{"Example Corp"},
   224  		},
   225  		ValidFor: 365 * 24 * time.Hour,
   226  	})
   227  	if err != nil {
   228  		log.Fatal("Failed to create certificate:", err)
   229  	}
   230  	fmt.Printf("āœ“ Created certificate for: %s\n", certificate.Certificate.Subject.CommonName)
   231  
   232  	// Large document to demonstrate performance
   233  	largeDocument := make([]byte, 1024*10) // 10KB document
   234  	for i := range largeDocument {
   235  		largeDocument[i] = byte(i % 256)
   236  	}
   237  
   238  	// Measure signing time
   239  	startTime := time.Now()
   240  	signature, err := signing.SignData(largeDocument, keyPair, certificate)
   241  	if err != nil {
   242  		log.Fatal("Failed to sign document:", err)
   243  	}
   244  	signingTime := time.Since(startTime)
   245  
   246  	fmt.Printf("āœ“ Signed 10KB document in %v\n", signingTime)
   247  	fmt.Printf("  Algorithm: %s\n", signature.Algorithm)
   248  	fmt.Printf("  Signature size: %d bytes\n", len(signature.Data))
   249  
   250  	// Measure verification time
   251  	startTime = time.Now()
   252  	err = signing.VerifySignature(largeDocument, signature, signing.DefaultVerifyOptions())
   253  	if err != nil {
   254  		log.Fatal("Verification failed:", err)
   255  	}
   256  	verificationTime := time.Since(startTime)
   257  	fmt.Printf("āœ“ Verified signature in %v\n", verificationTime)
   258  
   259  	// Save signature with hybrid approach details
   260  	saveSignature(signature, "output/ed25519_signature.json")
   261  	fmt.Printf("  Format: %s (hybrid approach - raw signature stored in PKCS#7 format field)\n", signature.Format)
   262  	fmt.Println("  Note: Ed25519 uses raw signatures, not PKCS#7, since RFC 8419 is not implemented by libraries")
   263  
   264  	fmt.Println()
   265  }
   266  
   267  func demonstrateAdvancedSigningOptions() {
   268  	fmt.Println("1. Certificate Chains & Advanced Options")
   269  	fmt.Println("-----------------------------------------")
   270  
   271  	// Generate key pair for CA
   272  	caKeyManager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize3072)
   273  	if err != nil {
   274  		log.Fatal("Failed to generate CA key pair:", err)
   275  	}
   276  	caKeyPair := caKeyManager.KeyPair()
   277  
   278  	// Create CA certificate
   279  	caCert, err := cert.CreateCACertificate(caKeyPair, cert.CertificateRequest{
   280  		Subject: pkix.Name{
   281  			CommonName:   "Example CA",
   282  			Organization: []string{"Example Corp"},
   283  			Country:      []string{"US"},
   284  		},
   285  		MaxPathLen: 1,
   286  		ValidFor:   10 * 365 * 24 * time.Hour,
   287  	})
   288  	if err != nil {
   289  		log.Fatal("Failed to create CA certificate:", err)
   290  	}
   291  	fmt.Println("āœ“ Created CA certificate")
   292  
   293  	// Create signing certificate signed by CA
   294  	signerKeyManager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048)
   295  	if err != nil {
   296  		log.Fatal("Failed to generate signer key pair:", err)
   297  	}
   298  	signerKeyPair := signerKeyManager.KeyPair()
   299  
   300  	signerCert, err := cert.SignCertificate(caCert, caKeyPair, cert.CertificateRequest{
   301  		Subject: pkix.Name{
   302  			CommonName:   "Document Signer",
   303  			Organization: []string{"Example Corp"},
   304  		},
   305  		ValidFor: 2 * 365 * 24 * time.Hour,
   306  	}, signerKeyPair.PublicKey)
   307  	if err != nil {
   308  		log.Fatal("Failed to create signer certificate:", err)
   309  	}
   310  	fmt.Println("āœ“ Created signer certificate signed by CA")
   311  
   312  	// Document to sign
   313  	document := []byte("Important document with certificate chain")
   314  
   315  	// Sign with chain included
   316  	opts := signing.SignOptions{
   317  		HashAlgorithm:      crypto.SHA384, // Stronger hash for 3072-bit key
   318  		Format:             signing.FormatPKCS7,
   319  		IncludeCertificate: true,
   320  		IncludeChain:       true,
   321  		ExtraCertificates:  []*x509.Certificate{caCert.Certificate},
   322  		Attributes: map[string]interface{}{
   323  			"version":    "1.0",
   324  			"author":     "John Doe",
   325  			"department": "Legal",
   326  		},
   327  	}
   328  
   329  	signature, err := signing.SignDocument(document, signerKeyPair, signerCert, opts)
   330  	if err != nil {
   331  		log.Fatal("Failed to sign document:", err)
   332  	}
   333  	fmt.Printf("āœ“ Signed with SHA-384 and certificate chain\n")
   334  
   335  	// Display metadata
   336  	if signature.Metadata != nil {
   337  		fmt.Println("  Metadata included:")
   338  		for key, value := range signature.Metadata {
   339  			fmt.Printf("    %s: %v\n", key, value)
   340  		}
   341  	}
   342  
   343  	// Verify with chain validation (create root pool with CA certificate)
   344  	verifyOpts := signing.DefaultVerifyOptions()
   345  	verifyOpts.VerifyChain = true
   346  	verifyOpts.Roots = x509.NewCertPool()
   347  	verifyOpts.Roots.AddCert(caCert.Certificate)
   348  	err = signing.VerifySignature(document, signature, verifyOpts)
   349  	if err != nil {
   350  		log.Fatal("Verification failed:", err)
   351  	}
   352  	fmt.Println("āœ“ Verified signature with certificate chain")
   353  
   354  	saveSignature(signature, "output/chain_signature.json")
   355  
   356  	fmt.Println()
   357  }
   358  
   359  func demonstrateSignatureVerification() {
   360  	fmt.Println("1. Security Testing & Tamper Detection")
   361  	fmt.Println("--------------------------------------")
   362  
   363  	// Generate key pair
   364  	keyManager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048)
   365  	if err != nil {
   366  		log.Fatal("Failed to generate key pair:", err)
   367  	}
   368  	keyPair := keyManager.KeyPair()
   369  
   370  	// Create certificate with specific key usage
   371  	certificate, err := cert.CreateSelfSignedCertificate(keyPair, cert.CertificateRequest{
   372  		Subject: pkix.Name{
   373  			CommonName: "Security Test Signer",
   374  		},
   375  		ValidFor: 365 * 24 * time.Hour,
   376  	})
   377  	if err != nil {
   378  		log.Fatal("Failed to create certificate:", err)
   379  	}
   380  
   381  	document := []byte("Test document for verification scenarios")
   382  
   383  	// Sign the document
   384  	signature, err := signing.SignData(document, keyPair, certificate)
   385  	if err != nil {
   386  		log.Fatal("Failed to sign document:", err)
   387  	}
   388  	fmt.Println("āœ“ Document signed")
   389  
   390  	// Test 1: Normal verification
   391  	err = signing.VerifySignature(document, signature, signing.DefaultVerifyOptions())
   392  	if err != nil {
   393  		log.Fatal("Normal verification failed:", err)
   394  	}
   395  	fmt.Println("āœ“ Test 1: Normal verification passed")
   396  
   397  	// Test 2: Tampered data detection
   398  	tamperedDocument := append(document, []byte(" TAMPERED")...)
   399  	err = signing.VerifySignature(tamperedDocument, signature, signing.DefaultVerifyOptions())
   400  	if err == nil {
   401  		log.Fatal("Expected verification to fail with tampered data")
   402  	}
   403  	fmt.Println("āœ“ Test 2: Tampered data detected")
   404  
   405  	// Test 3: Modified signature detection
   406  	originalSigData := signature.Data[0]
   407  	signature.Data[0] ^= 0xFF
   408  	err = signing.VerifySignature(document, signature, signing.DefaultVerifyOptions())
   409  	if err == nil {
   410  		log.Fatal("Expected verification to fail with modified signature")
   411  	}
   412  	signature.Data[0] = originalSigData // Restore
   413  	fmt.Println("āœ“ Test 3: Modified signature detected")
   414  
   415  	// Test 4: Wrong certificate
   416  	wrongKeyManager, _ := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048)
   417  	wrongKeyPair := wrongKeyManager.KeyPair()
   418  	wrongCert, _ := cert.CreateSelfSignedCertificate(wrongKeyPair, cert.CertificateRequest{
   419  		Subject:  pkix.Name{CommonName: "Wrong Signer"},
   420  		ValidFor: 365 * 24 * time.Hour,
   421  	})
   422  
   423  	err = signing.VerifyWithCertificate(document, signature, wrongCert.Certificate, signing.DefaultVerifyOptions())
   424  	if err == nil {
   425  		log.Fatal("Expected verification to fail with wrong certificate")
   426  	}
   427  	fmt.Println("āœ“ Test 4: Wrong certificate detected")
   428  
   429  	// Test 5: Get signature information
   430  	fmt.Println("\nSignature Information:")
   431  	info := signing.GetSignatureInfo(signature)
   432  	fmt.Print(info)
   433  
   434  	fmt.Println()
   435  }
   436  
   437  func demonstrateMultipleSignatures() {
   438  	fmt.Println("1. Multi-Party Document Signing")
   439  	fmt.Println("-------------------------------")
   440  
   441  	document := []byte("Multi-party agreement requiring multiple signatures")
   442  
   443  	// Create three different signers
   444  	signers := []struct {
   445  		name      string
   446  		algorithm string
   447  		keyPair   interface{}
   448  		cert      *cert.Certificate
   449  	}{}
   450  
   451  	// Signer 1: RSA
   452  	rsaKeyManager, _ := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048)
   453  	rsaKeyPair := rsaKeyManager.KeyPair()
   454  	rsaCert, _ := cert.CreateSelfSignedCertificate(rsaKeyPair, cert.CertificateRequest{
   455  		Subject:  pkix.Name{CommonName: "Alice (RSA)"},
   456  		ValidFor: 365 * 24 * time.Hour,
   457  	})
   458  	signers = append(signers, struct {
   459  		name      string
   460  		algorithm string
   461  		keyPair   interface{}
   462  		cert      *cert.Certificate
   463  	}{"Alice", "RSA", rsaKeyPair, rsaCert})
   464  
   465  	// Signer 2: ECDSA
   466  	ecdsaKeyManager, _ := keypair.Generate[algo.ECDSACurve, *algo.ECDSAKeyPair, *ecdsa.PrivateKey, *ecdsa.PublicKey](algo.P256)
   467  	ecdsaKeyPair := ecdsaKeyManager.KeyPair()
   468  	ecdsaCert, _ := cert.CreateSelfSignedCertificate(ecdsaKeyPair, cert.CertificateRequest{
   469  		Subject:  pkix.Name{CommonName: "Bob (ECDSA)"},
   470  		ValidFor: 365 * 24 * time.Hour,
   471  	})
   472  	signers = append(signers, struct {
   473  		name      string
   474  		algorithm string
   475  		keyPair   interface{}
   476  		cert      *cert.Certificate
   477  	}{"Bob", "ECDSA", ecdsaKeyPair, ecdsaCert})
   478  
   479  	// Signer 3: Ed25519
   480  	ed25519KeyManager, _ := keypair.Generate[algo.Ed25519Config, *algo.Ed25519KeyPair, ed25519.PrivateKey, ed25519.PublicKey](algo.Ed25519Default)
   481  	ed25519KeyPair := ed25519KeyManager.KeyPair()
   482  	ed25519Cert, _ := cert.CreateSelfSignedCertificate(ed25519KeyPair, cert.CertificateRequest{
   483  		Subject:  pkix.Name{CommonName: "Charlie (Ed25519)"},
   484  		ValidFor: 365 * 24 * time.Hour,
   485  	})
   486  	signers = append(signers, struct {
   487  		name      string
   488  		algorithm string
   489  		keyPair   interface{}
   490  		cert      *cert.Certificate
   491  	}{"Charlie", "Ed25519", ed25519KeyPair, ed25519Cert})
   492  
   493  	// Collect signatures from all parties
   494  	var signatures []*signing.Signature
   495  	for _, signer := range signers {
   496  		var sig *signing.Signature
   497  		var err error
   498  
   499  		switch kp := signer.keyPair.(type) {
   500  		case *algo.RSAKeyPair:
   501  			sig, err = signing.SignData(document, kp, signer.cert)
   502  		case *algo.ECDSAKeyPair:
   503  			sig, err = signing.SignData(document, kp, signer.cert)
   504  		case *algo.Ed25519KeyPair:
   505  			sig, err = signing.SignData(document, kp, signer.cert)
   506  		}
   507  
   508  		if err != nil {
   509  			log.Fatalf("Failed to sign for %s: %v", signer.name, err)
   510  		}
   511  
   512  		signatures = append(signatures, sig)
   513  		fmt.Printf("āœ“ %s signed using %s\n", signer.name, signer.algorithm)
   514  	}
   515  
   516  	// Verify all signatures
   517  	fmt.Println("\nVerifying all signatures:")
   518  	for i, sig := range signatures {
   519  		err := signing.VerifySignature(document, sig, signing.DefaultVerifyOptions())
   520  		if err != nil {
   521  			log.Fatalf("Failed to verify signature from %s: %v", signers[i].name, err)
   522  		}
   523  		fmt.Printf("āœ“ Verified signature from %s\n", signers[i].name)
   524  	}
   525  
   526  	// Save multi-signature document
   527  	multiSig := map[string]interface{}{
   528  		"document":   base64.StdEncoding.EncodeToString(document),
   529  		"signatures": []map[string]interface{}{},
   530  	}
   531  
   532  	for i, sig := range signatures {
   533  		sigData := map[string]interface{}{
   534  			"signer":    signers[i].name,
   535  			"algorithm": string(sig.Algorithm),
   536  			"hash":      signing.HashAlgorithmToString(sig.HashAlgorithm),
   537  			"signature": base64.StdEncoding.EncodeToString(sig.Data),
   538  			"digest":    base64.StdEncoding.EncodeToString(sig.Digest),
   539  			"format":    string(sig.Format),
   540  		}
   541  		multiSig["signatures"] = append(multiSig["signatures"].([]map[string]interface{}), sigData)
   542  	}
   543  
   544  	saveJSON(multiSig, "output/multi_signature.json")
   545  	fmt.Println("\nāœ“ Multi-signature document saved")
   546  
   547  	fmt.Println()
   548  }
   549  
   550  func demonstratePKCS7FormatExamples() {
   551  	fmt.Println("1. PKCS#7 Format Demonstrations")
   552  	fmt.Println("-------------------------------")
   553  
   554  	// Generate key pair and certificate
   555  	keyManager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048)
   556  	if err != nil {
   557  		log.Fatal("Failed to generate key pair:", err)
   558  	}
   559  	keyPair := keyManager.KeyPair()
   560  
   561  	certificate, err := cert.CreateSelfSignedCertificate(keyPair, cert.CertificateRequest{
   562  		Subject: pkix.Name{
   563  			CommonName:   "PKCS#7 Document Signer",
   564  			Organization: []string{"Example Corp"},
   565  		},
   566  		ValidFor: 365 * 24 * time.Hour,
   567  	})
   568  	if err != nil {
   569  		log.Fatal("Failed to create certificate:", err)
   570  	}
   571  	fmt.Printf("āœ“ Created certificate for: %s\n", certificate.Certificate.Subject.CommonName)
   572  
   573  	document := []byte("Important contract requiring PKCS#7 signature")
   574  
   575  	// Test attached PKCS#7
   576  	fmt.Println("\n--- Attached PKCS#7 ---")
   577  	attachedOpts := signing.SignOptions{
   578  		HashAlgorithm:      crypto.SHA256,
   579  		Format:             signing.FormatPKCS7,
   580  		IncludeCertificate: true,
   581  		Detached:           false,
   582  	}
   583  
   584  	attachedSig, err := signing.SignDocument(document, keyPair, certificate, attachedOpts)
   585  	if err != nil {
   586  		log.Fatal("Failed to create attached PKCS#7:", err)
   587  	}
   588  	fmt.Printf("āœ“ Created attached PKCS#7 signature (%d bytes)\n", len(attachedSig.Data))
   589  
   590  	// Verify attached PKCS#7
   591  	err = signing.VerifySignature(document, attachedSig, signing.DefaultVerifyOptions())
   592  	if err != nil {
   593  		log.Fatal("Attached PKCS#7 verification failed:", err)
   594  	}
   595  	fmt.Println("āœ“ Attached PKCS#7 verified successfully")
   596  
   597  	// Test detached PKCS#7
   598  	fmt.Println("\n--- Detached PKCS#7 ---")
   599  	detachedOpts := signing.SignOptions{
   600  		HashAlgorithm:      crypto.SHA384,
   601  		Format:             signing.FormatPKCS7Detached,
   602  		IncludeCertificate: true,
   603  		Detached:           true,
   604  	}
   605  
   606  	detachedSig, err := signing.SignDocument(document, keyPair, certificate, detachedOpts)
   607  	if err != nil {
   608  		log.Fatal("Failed to create detached PKCS#7:", err)
   609  	}
   610  	fmt.Printf("āœ“ Created detached PKCS#7 signature (%d bytes)\n", len(detachedSig.Data))
   611  
   612  	// Verify detached PKCS#7
   613  	err = signing.VerifySignature(document, detachedSig, signing.DefaultVerifyOptions())
   614  	if err != nil {
   615  		log.Fatal("Detached PKCS#7 verification failed:", err)
   616  	}
   617  	fmt.Println("āœ“ Detached PKCS#7 verified successfully")
   618  
   619  	// Save PKCS#7 signatures
   620  	os.WriteFile("output/pkcs7_attached.p7s", attachedSig.Data, 0644)
   621  	os.WriteFile("output/pkcs7_detached.p7s", detachedSig.Data, 0644)
   622  	fmt.Println("\nāœ“ PKCS#7 signatures saved to output/ directory")
   623  
   624  	fmt.Println()
   625  }
   626  
   627  func demonstratePerformanceComparison() {
   628  	fmt.Println("1. Algorithm Performance Comparison")
   629  	fmt.Println("----------------------------------")
   630  
   631  	// Test data - 100KB document
   632  	testData := make([]byte, 100*1024)
   633  	for i := range testData {
   634  		testData[i] = byte(i % 256)
   635  	}
   636  	fmt.Printf("Testing with %d KB document\n", len(testData)/1024)
   637  
   638  	algorithms := []struct {
   639  		name    string
   640  		keyPair interface{}
   641  		cert    *cert.Certificate
   642  	}{}
   643  
   644  	// RSA
   645  	rsaKeyManager, _ := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048)
   646  	rsaKeyPair := rsaKeyManager.KeyPair()
   647  	rsaCert, _ := cert.CreateSelfSignedCertificate(rsaKeyPair, cert.CertificateRequest{
   648  		Subject:  pkix.Name{CommonName: "RSA Perf Test"},
   649  		ValidFor: 24 * time.Hour,
   650  	})
   651  	algorithms = append(algorithms, struct {
   652  		name    string
   653  		keyPair interface{}
   654  		cert    *cert.Certificate
   655  	}{"RSA-2048", rsaKeyPair, rsaCert})
   656  
   657  	// ECDSA
   658  	ecdsaKeyManager, _ := keypair.Generate[algo.ECDSACurve, *algo.ECDSAKeyPair, *ecdsa.PrivateKey, *ecdsa.PublicKey](algo.P256)
   659  	ecdsaKeyPair := ecdsaKeyManager.KeyPair()
   660  	ecdsaCert, _ := cert.CreateSelfSignedCertificate(ecdsaKeyPair, cert.CertificateRequest{
   661  		Subject:  pkix.Name{CommonName: "ECDSA Perf Test"},
   662  		ValidFor: 24 * time.Hour,
   663  	})
   664  	algorithms = append(algorithms, struct {
   665  		name    string
   666  		keyPair interface{}
   667  		cert    *cert.Certificate
   668  	}{"ECDSA-P256", ecdsaKeyPair, ecdsaCert})
   669  
   670  	// Ed25519
   671  	ed25519KeyManager, _ := keypair.Generate[algo.Ed25519Config, *algo.Ed25519KeyPair, ed25519.PrivateKey, ed25519.PublicKey](algo.Ed25519Default)
   672  	ed25519KeyPair := ed25519KeyManager.KeyPair()
   673  	ed25519Cert, _ := cert.CreateSelfSignedCertificate(ed25519KeyPair, cert.CertificateRequest{
   674  		Subject:  pkix.Name{CommonName: "Ed25519 Perf Test"},
   675  		ValidFor: 24 * time.Hour,
   676  	})
   677  	algorithms = append(algorithms, struct {
   678  		name    string
   679  		keyPair interface{}
   680  		cert    *cert.Certificate
   681  	}{"Ed25519", ed25519KeyPair, ed25519Cert})
   682  
   683  	fmt.Printf("\n%-12s %-12s %-12s %-8s\n", "Algorithm", "Sign Time", "Verify Time", "Sig Size")
   684  	fmt.Println(strings.Repeat("-", 50))
   685  
   686  	for _, alg := range algorithms {
   687  		var signature *signing.Signature
   688  		var err error
   689  
   690  		// Measure signing time
   691  		startTime := time.Now()
   692  		switch kp := alg.keyPair.(type) {
   693  		case *algo.RSAKeyPair:
   694  			signature, err = signing.SignData(testData, kp, alg.cert)
   695  		case *algo.ECDSAKeyPair:
   696  			signature, err = signing.SignData(testData, kp, alg.cert)
   697  		case *algo.Ed25519KeyPair:
   698  			signature, err = signing.SignData(testData, kp, alg.cert)
   699  		}
   700  		signTime := time.Since(startTime)
   701  
   702  		if err != nil {
   703  			log.Printf("Failed to sign with %s: %v", alg.name, err)
   704  			continue
   705  		}
   706  
   707  		// Measure verification time
   708  		startTime = time.Now()
   709  		err = signing.VerifySignature(testData, signature, signing.DefaultVerifyOptions())
   710  		verifyTime := time.Since(startTime)
   711  
   712  		if err != nil {
   713  			log.Printf("Failed to verify with %s: %v", alg.name, err)
   714  			continue
   715  		}
   716  
   717  		fmt.Printf("%-12s %-12v %-12v %-8d\n",
   718  			alg.name, signTime, verifyTime, len(signature.Data))
   719  	}
   720  
   721  	fmt.Println()
   722  }
   723  
   724  func demonstrateFileOperations() {
   725  	fmt.Println("1. File Signing & Detached Signatures")
   726  	fmt.Println("-------------------------------------")
   727  
   728  	// Generate key pair
   729  	keyManager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048)
   730  	if err != nil {
   731  		log.Fatal("Failed to generate key pair:", err)
   732  	}
   733  	keyPair := keyManager.KeyPair()
   734  
   735  	certificate, err := cert.CreateSelfSignedCertificate(keyPair, cert.CertificateRequest{
   736  		Subject: pkix.Name{
   737  			CommonName: "File Signer",
   738  		},
   739  		ValidFor: 365 * 24 * time.Hour,
   740  	})
   741  	if err != nil {
   742  		log.Fatal("Failed to create certificate:", err)
   743  	}
   744  
   745  	// Create a test file
   746  	testFileContent := []byte(`This is a test document that will be signed.
   747  It contains multiple lines and represents a real file that needs
   748  digital signature protection for integrity and authenticity.`)
   749  
   750  	err = os.WriteFile("output/test_document.txt", testFileContent, 0644)
   751  	if err != nil {
   752  		log.Fatal("Failed to create test file:", err)
   753  	}
   754  	fmt.Println("āœ“ Created test document file")
   755  
   756  	// Sign the file
   757  	signature, err := signing.SignFile("output/test_document.txt", keyPair, certificate, signing.DefaultSignOptions())
   758  	if err != nil {
   759  		log.Fatal("Failed to sign file:", err)
   760  	}
   761  	fmt.Printf("āœ“ Signed file using %s\n", signature.Algorithm)
   762  
   763  	// Save signature
   764  	saveSignature(signature, "output/document_signature.json")
   765  
   766  	// Verify file signature by reading the file again
   767  	fileData, err := os.ReadFile("output/test_document.txt")
   768  	if err != nil {
   769  		log.Fatal("Failed to read test file:", err)
   770  	}
   771  
   772  	err = signing.VerifySignature(fileData, signature, signing.DefaultVerifyOptions())
   773  	if err != nil {
   774  		log.Fatal("File signature verification failed:", err)
   775  	}
   776  	fmt.Println("āœ“ File signature verified successfully")
   777  
   778  	// Demonstrate detached signature verification
   779  	fmt.Println("\n--- Detached Signature Test ---")
   780  
   781  	// Create a raw signature for detached verification
   782  	hasher := crypto.SHA256.New()
   783  	hasher.Write(testFileContent)
   784  	digest := hasher.Sum(nil)
   785  
   786  	rawSigBytes, err := keyPair.PrivateKey.Sign(rand.Reader, digest, crypto.SHA256)
   787  	if err != nil {
   788  		log.Fatal("Failed to create raw signature:", err)
   789  	}
   790  
   791  	// Save raw signature bytes
   792  	err = os.WriteFile("output/test_document.sig", rawSigBytes, 0644)
   793  	if err != nil {
   794  		log.Fatal("Failed to save signature file:", err)
   795  	}
   796  	fmt.Println("āœ“ Created detached signature file")
   797  
   798  	// Verify detached signature
   799  	err = signing.VerifyDetachedSignature(testFileContent, rawSigBytes, certificate.Certificate, crypto.SHA256)
   800  	if err != nil {
   801  		log.Fatal("Detached signature verification failed:", err)
   802  	}
   803  	fmt.Println("āœ“ Detached signature verified successfully")
   804  
   805  	fmt.Println()
   806  }
   807  
   808  // Helper functions
   809  
   810  func saveSignature(sig *signing.Signature, filename string) {
   811  	data := map[string]interface{}{
   812  		"algorithm":     string(sig.Algorithm),
   813  		"hashAlgorithm": signing.HashAlgorithmToString(sig.HashAlgorithm),
   814  		"format":        string(sig.Format),
   815  		"signature":     base64.StdEncoding.EncodeToString(sig.Data),
   816  		"digest":        base64.StdEncoding.EncodeToString(sig.Digest),
   817  		"timestamp":     time.Now().Format(time.RFC3339),
   818  	}
   819  
   820  	if sig.Certificate != nil {
   821  		data["signerCN"] = sig.Certificate.Subject.CommonName
   822  		data["issuerCN"] = sig.Certificate.Issuer.CommonName
   823  		data["validFrom"] = sig.Certificate.NotBefore.Format(time.RFC3339)
   824  		data["validUntil"] = sig.Certificate.NotAfter.Format(time.RFC3339)
   825  	}
   826  
   827  	if sig.Metadata != nil {
   828  		data["metadata"] = sig.Metadata
   829  	}
   830  
   831  	saveJSON(data, filename)
   832  }
   833  
   834  func saveJSON(data interface{}, filename string) {
   835  	jsonData, err := json.MarshalIndent(data, "", "  ")
   836  	if err != nil {
   837  		log.Printf("Failed to marshal JSON: %v", err)
   838  		return
   839  	}
   840  
   841  	err = os.WriteFile(filename, jsonData, 0644)
   842  	if err != nil {
   843  		log.Printf("Failed to save file %s: %v", filename, err)
   844  		return
   845  	}
   846  }