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

     1  //go:build example
     2  
     3  package main
     4  
     5  import (
     6  	"crypto/ecdsa"
     7  	"crypto/ed25519"
     8  	"crypto/rsa"
     9  	"crypto/x509/pkix"
    10  	"encoding/base64"
    11  	"encoding/json"
    12  	"fmt"
    13  	"log"
    14  	"os"
    15  	"strings"
    16  	"time"
    17  
    18  	"github.com/jasoet/gopki/cert"
    19  	"github.com/jasoet/gopki/encryption"
    20  	"github.com/jasoet/gopki/encryption/asymmetric"
    21  	certenc "github.com/jasoet/gopki/encryption/certificate"
    22  	"github.com/jasoet/gopki/encryption/envelope"
    23  	"github.com/jasoet/gopki/keypair"
    24  	"github.com/jasoet/gopki/keypair/algo"
    25  )
    26  
    27  func main() {
    28  	fmt.Println("=== GoPKI Data Encryption Module - Comprehensive Examples ===")
    29  	fmt.Println("Demonstrating type-safe encryption with multi-algorithm support and CMS format compliance")
    30  	fmt.Println()
    31  	fmt.Println("šŸ“ Current Implementation Notes:")
    32  	fmt.Println("   • RSA encryption: Fully supported (direct + envelope)")
    33  	fmt.Println("   • ECDSA encryption: Limited support (envelope encryption has known issues)")
    34  	fmt.Println("   • Ed25519 encryption: Limited support (envelope encryption has known issues)")
    35  	fmt.Println("   • Certificate-based: Works best with RSA keys")
    36  	fmt.Println("   • CMS format: Basic support, some advanced features pending")
    37  	fmt.Println()
    38  
    39  	// Create output directory
    40  	if err := os.MkdirAll("output", 0755); err != nil {
    41  		log.Fatal("Failed to create output directory:", err)
    42  	}
    43  
    44  	// Execute all encryption examples
    45  	fmt.Println("\nšŸ” PART 1: Multi-Algorithm Encryption")
    46  	fmt.Println(strings.Repeat("=", 60))
    47  	demonstrateMultiAlgorithmEncryption()
    48  
    49  	fmt.Println("\nšŸ“¦ PART 2: Envelope Encryption for Large Data")
    50  	fmt.Println(strings.Repeat("=", 60))
    51  	demonstrateEnvelopeEncryption()
    52  
    53  	fmt.Println("\nšŸ›ļø PART 3: Certificate-based Encryption")
    54  	fmt.Println(strings.Repeat("=", 60))
    55  	demonstrateCertificateBasedEncryption()
    56  
    57  	fmt.Println("\nšŸ“„ PART 4: CMS Format & Standards Compliance")
    58  	fmt.Println(strings.Repeat("=", 60))
    59  	demonstrateCMSFormatSupport()
    60  
    61  	fmt.Println("\nšŸ‘„ PART 5: Multi-Recipient Encryption")
    62  	fmt.Println(strings.Repeat("=", 60))
    63  	demonstrateMultiRecipientEncryption()
    64  
    65  	fmt.Println("\nšŸš€ PART 6: Performance & Security Analysis")
    66  	fmt.Println(strings.Repeat("=", 60))
    67  	demonstratePerformanceAnalysis()
    68  
    69  	fmt.Println("\nšŸ’¾ PART 7: File Operations & Integration")
    70  	fmt.Println(strings.Repeat("=", 60))
    71  	demonstrateFileOperations()
    72  
    73  	fmt.Println("\n\n=" + strings.Repeat("=", 58) + "=")
    74  	fmt.Println("āœ… ALL ENCRYPTION EXAMPLES COMPLETED!")
    75  	fmt.Println("šŸ“ Output files saved in: ./output/")
    76  	fmt.Println("šŸ” Review encryption formats and certificate integration")
    77  	fmt.Println()
    78  	fmt.Println("šŸ“‹ Summary of Demonstrated Features:")
    79  	fmt.Println("   āœ… RSA-OAEP direct encryption")
    80  	fmt.Println("   āœ… RSA envelope encryption for large data")
    81  	fmt.Println("   āœ… Certificate-based encryption with RSA")
    82  	fmt.Println("   āœ… Multi-recipient encryption workflows")
    83  	fmt.Println("   āœ… Performance analysis and benchmarking")
    84  	fmt.Println("   āœ… File-based encryption operations")
    85  	fmt.Println("   āš ļø  ECDSA/Ed25519 envelope encryption (implementation pending)")
    86  	fmt.Println("   āš ļø  Full CMS encoding/decoding (basic support available)")
    87  	fmt.Println("=" + strings.Repeat("=", 58) + "=")
    88  }
    89  
    90  func demonstrateMultiAlgorithmEncryption() {
    91  	fmt.Println("1. RSA-OAEP Encryption")
    92  	fmt.Println("----------------------")
    93  	demonstrateRSAEncryption()
    94  
    95  	fmt.Println("2. ECDSA + ECDH Encryption")
    96  	fmt.Println("---------------------------")
    97  	demonstrateECDSAEncryption()
    98  
    99  	fmt.Println("3. Ed25519 + X25519 Encryption")
   100  	fmt.Println("-------------------------------")
   101  	demonstrateEd25519Encryption()
   102  }
   103  
   104  func demonstrateRSAEncryption() {
   105  	// Generate RSA key pair using type-safe API
   106  	keyManager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048)
   107  	if err != nil {
   108  		log.Fatal("Failed to generate RSA key pair:", err)
   109  	}
   110  	keyPair := keyManager.KeyPair()
   111  	fmt.Println("āœ“ Generated 2048-bit RSA key pair using type-safe API")
   112  
   113  	// Small data suitable for RSA-OAEP direct encryption
   114  	smallData := []byte("Confidential RSA message - Hello World!")
   115  	fmt.Printf("  Original data: %s (%d bytes)\n", smallData, len(smallData))
   116  
   117  	// Direct RSA encryption
   118  	opts := encryption.DefaultEncryptOptions()
   119  	encrypted, err := asymmetric.Encrypt(smallData, keyPair, opts)
   120  	if err != nil {
   121  		log.Fatal("RSA encryption failed:", err)
   122  	}
   123  
   124  	fmt.Printf("āœ“ Encrypted using %s\n", encrypted.Algorithm)
   125  	fmt.Printf("  Encrypted size: %d bytes\n", len(encrypted.Data))
   126  	fmt.Printf("  Encryption ratio: %.1fx\n", float64(len(encrypted.Data))/float64(len(smallData)))
   127  
   128  	// Decrypt the data
   129  	decryptOpts := encryption.DefaultDecryptOptions()
   130  	decrypted, err := asymmetric.Decrypt(encrypted, keyPair, decryptOpts)
   131  	if err != nil {
   132  		log.Fatal("RSA decryption failed:", err)
   133  	}
   134  
   135  	fmt.Printf("āœ“ Decrypted: %s\n", decrypted)
   136  
   137  	// Save with metadata
   138  	saveEncryptionResult("rsa_direct", encrypted, map[string]interface{}{
   139  		"algorithm":     string(encrypted.Algorithm),
   140  		"keySize":       2048,
   141  		"dataSize":      len(smallData),
   142  		"encryptedSize": len(encrypted.Data),
   143  		"method":        "RSA-OAEP direct encryption",
   144  	})
   145  
   146  	fmt.Println()
   147  }
   148  
   149  func demonstrateECDSAEncryption() {
   150  	// Generate ECDSA key pair using type-safe API
   151  	keyManager, err := keypair.Generate[algo.ECDSACurve, *algo.ECDSAKeyPair, *ecdsa.PrivateKey, *ecdsa.PublicKey](algo.P256)
   152  	if err != nil {
   153  		log.Fatal("Failed to generate ECDSA key pair:", err)
   154  	}
   155  	keyPair := keyManager.KeyPair()
   156  	fmt.Println("āœ“ Generated ECDSA P-256 key pair using type-safe API")
   157  
   158  	// Data for ECDH + AES-GCM encryption
   159  	data := []byte("Secure ECDSA message using ECDH key agreement and AES-GCM encryption")
   160  	fmt.Printf("  Original data: %s (%d bytes)\n", data, len(data))
   161  
   162  	// ECDH-based encryption using envelope encryption
   163  	opts := encryption.DefaultEncryptOptions()
   164  	opts.Format = encryption.FormatCMS
   165  
   166  	encrypted, err := envelope.Encrypt(data, keyPair, opts)
   167  	if err != nil {
   168  		log.Printf("āš ļø  ECDSA envelope encryption issue: %v", err)
   169  		log.Println("  Note: Known issue with ECDSA envelope encryption - using direct asymmetric encryption")
   170  
   171  		// Fallback to direct asymmetric encryption
   172  		encrypted, err = asymmetric.Encrypt(data, keyPair, opts)
   173  		if err != nil {
   174  			log.Printf("āš ļø  ECDSA encryption not yet fully supported: %v", err)
   175  			fmt.Println("  Skipping ECDSA demonstration due to implementation limitations")
   176  			return
   177  		}
   178  	}
   179  
   180  	fmt.Printf("āœ“ Encrypted using %s\n", encrypted.Algorithm)
   181  	fmt.Printf("  Encrypted size: %d bytes\n", len(encrypted.Data))
   182  	if len(encrypted.EncryptedKey) > 0 {
   183  		fmt.Printf("  Key material size: %d bytes\n", len(encrypted.EncryptedKey))
   184  	}
   185  
   186  	// Decrypt the data
   187  	decryptOpts := encryption.DefaultDecryptOptions()
   188  	var decrypted []byte
   189  	if len(encrypted.EncryptedKey) > 0 {
   190  		// Envelope decryption
   191  		decrypted, err = envelope.Decrypt(encrypted, keyPair, decryptOpts)
   192  	} else {
   193  		// Direct decryption
   194  		decrypted, err = asymmetric.Decrypt(encrypted, keyPair, decryptOpts)
   195  	}
   196  
   197  	if err != nil {
   198  		log.Printf("ECDSA decryption failed: %v", err)
   199  		return
   200  	}
   201  
   202  	// Show complete message for short data, truncate only if very long
   203  	if len(decrypted) <= 100 {
   204  		fmt.Printf("āœ“ Decrypted: %s\n", string(decrypted))
   205  	} else {
   206  		fmt.Printf("āœ“ Decrypted: %s...\n", string(decrypted[:97])+"...")
   207  	}
   208  
   209  	// Save result
   210  	saveEncryptionResult("ecdsa_hybrid", encrypted, map[string]interface{}{
   211  		"algorithm":     string(encrypted.Algorithm),
   212  		"curve":         "P-256",
   213  		"dataSize":      len(data),
   214  		"encryptedSize": len(encrypted.Data),
   215  		"method":        "ECDH + AES-GCM",
   216  	})
   217  
   218  	fmt.Println()
   219  }
   220  
   221  func demonstrateEd25519Encryption() {
   222  	// Generate Ed25519 key pair using type-safe API
   223  	keyManager, err := keypair.Generate[algo.Ed25519Config, *algo.Ed25519KeyPair, ed25519.PrivateKey, ed25519.PublicKey](algo.Ed25519Default)
   224  	if err != nil {
   225  		log.Fatal("Failed to generate Ed25519 key pair:", err)
   226  	}
   227  	keyPair := keyManager.KeyPair()
   228  	fmt.Println("āœ“ Generated Ed25519 key pair using type-safe API")
   229  
   230  	// Data for X25519 + AES-GCM encryption
   231  	data := []byte("Modern Ed25519 message using X25519 key agreement - highest performance encryption")
   232  	fmt.Printf("  Original data: %s (%d bytes)\n", string(data), len(data))
   233  
   234  	// X25519-based encryption using envelope encryption
   235  	opts := encryption.DefaultEncryptOptions()
   236  	opts.Format = encryption.FormatCMS
   237  
   238  	startTime := time.Now()
   239  	encrypted, err := envelope.Encrypt(data, keyPair, opts)
   240  	if err != nil {
   241  		log.Printf("āš ļø  Ed25519 envelope encryption issue: %v", err)
   242  		log.Println("  Note: Known issue with Ed25519 envelope encryption - using direct asymmetric encryption")
   243  
   244  		// Fallback to direct asymmetric encryption
   245  		encrypted, err = asymmetric.Encrypt(data, keyPair, opts)
   246  		if err != nil {
   247  			log.Printf("āš ļø  Ed25519 encryption not yet fully supported: %v", err)
   248  			fmt.Println("  Skipping Ed25519 demonstration due to implementation limitations")
   249  			return
   250  		}
   251  	}
   252  	encryptionTime := time.Since(startTime)
   253  
   254  	fmt.Printf("āœ“ Encrypted using %s in %v\n", encrypted.Algorithm, encryptionTime)
   255  	fmt.Printf("  Encrypted size: %d bytes\n", len(encrypted.Data))
   256  	if len(encrypted.EncryptedKey) > 0 {
   257  		fmt.Printf("  Key material size: %d bytes\n", len(encrypted.EncryptedKey))
   258  	}
   259  
   260  	// Decrypt the data
   261  	startTime = time.Now()
   262  	decryptOpts := encryption.DefaultDecryptOptions()
   263  	var decrypted []byte
   264  	if len(encrypted.EncryptedKey) > 0 {
   265  		// Envelope decryption
   266  		decrypted, err = envelope.Decrypt(encrypted, keyPair, decryptOpts)
   267  	} else {
   268  		// Direct decryption
   269  		decrypted, err = asymmetric.Decrypt(encrypted, keyPair, decryptOpts)
   270  	}
   271  	decryptionTime := time.Since(startTime)
   272  
   273  	if err != nil {
   274  		log.Printf("Ed25519 decryption failed: %v", err)
   275  		return
   276  	}
   277  
   278  	// Show complete message for short data, truncate only if very long
   279  	if len(decrypted) <= 100 {
   280  		fmt.Printf("āœ“ Decrypted in %v: %s\n", decryptionTime, string(decrypted))
   281  	} else {
   282  		fmt.Printf("āœ“ Decrypted in %v: %s...\n", decryptionTime, string(decrypted[:97]))
   283  	}
   284  
   285  	// Save result with timing
   286  	saveEncryptionResult("ed25519_hybrid", encrypted, map[string]interface{}{
   287  		"algorithm":      string(encrypted.Algorithm),
   288  		"curve":          "X25519",
   289  		"dataSize":       len(data),
   290  		"encryptedSize":  len(encrypted.Data),
   291  		"encryptionTime": encryptionTime.String(),
   292  		"decryptionTime": decryptionTime.String(),
   293  		"method":         "X25519 + AES-GCM",
   294  	})
   295  
   296  	fmt.Println()
   297  }
   298  
   299  func demonstrateEnvelopeEncryption() {
   300  	fmt.Println("1. Large Data Encryption with Envelope Method")
   301  	fmt.Println("---------------------------------------------")
   302  
   303  	// Generate RSA key pair for envelope encryption
   304  	keyManager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048)
   305  	if err != nil {
   306  		log.Fatal("Failed to generate RSA key pair:", err)
   307  	}
   308  	keyPair := keyManager.KeyPair()
   309  	fmt.Println("āœ“ Generated 2048-bit RSA key pair for envelope encryption")
   310  
   311  	// Create large test data
   312  	largeData := make([]byte, 1024*50) // 50KB data
   313  	for i := range largeData {
   314  		largeData[i] = byte('A' + (i % 26))
   315  	}
   316  	fmt.Printf("āœ“ Generated test data: %d KB\n", len(largeData)/1024)
   317  
   318  	// Envelope encryption with timing
   319  	startTime := time.Now()
   320  	opts := encryption.DefaultEncryptOptions()
   321  	opts.Format = encryption.FormatCMS
   322  
   323  	encrypted, err := envelope.Encrypt(largeData, keyPair, opts)
   324  	if err != nil {
   325  		log.Fatal("Envelope encryption failed:", err)
   326  	}
   327  	encryptionTime := time.Since(startTime)
   328  
   329  	fmt.Printf("āœ“ Encrypted %d KB → %d KB in %v\n",
   330  		len(largeData)/1024, len(encrypted.Data)/1024, encryptionTime)
   331  	fmt.Printf("  Algorithm: %s\n", encrypted.Algorithm)
   332  	fmt.Printf("  Symmetric key size: %d bytes\n", len(encrypted.EncryptedKey))
   333  	fmt.Printf("  IV size: %d bytes\n", len(encrypted.IV))
   334  	fmt.Printf("  Compression ratio: %.1fx\n", float64(len(encrypted.Data))/float64(len(largeData)))
   335  
   336  	// Envelope decryption with timing
   337  	startTime = time.Now()
   338  	decryptOpts := encryption.DefaultDecryptOptions()
   339  	decrypted, err := envelope.Decrypt(encrypted, keyPair, decryptOpts)
   340  	if err != nil {
   341  		log.Fatal("Envelope decryption failed:", err)
   342  	}
   343  	decryptionTime := time.Since(startTime)
   344  
   345  	fmt.Printf("āœ“ Decrypted %d KB in %v\n", len(decrypted)/1024, decryptionTime)
   346  	fmt.Printf("  Data integrity: %t\n", len(decrypted) == len(largeData))
   347  
   348  	// Save envelope encryption result
   349  	saveEncryptionResult("envelope_large", encrypted, map[string]interface{}{
   350  		"method":          "Envelope encryption",
   351  		"originalSize":    len(largeData),
   352  		"encryptedSize":   len(encrypted.Data),
   353  		"keyMaterialSize": len(encrypted.EncryptedKey),
   354  		"ivSize":          len(encrypted.IV),
   355  		"encryptionTime":  encryptionTime.String(),
   356  		"decryptionTime":  decryptionTime.String(),
   357  		"algorithm":       string(encrypted.Algorithm),
   358  	})
   359  
   360  	// Save raw encrypted data for format demonstration
   361  	os.WriteFile("output/envelope_large.bin", encrypted.Data, 0644)
   362  	fmt.Println("šŸ’¾ Saved large data encryption example")
   363  
   364  	fmt.Println()
   365  }
   366  
   367  func demonstrateCertificateBasedEncryption() {
   368  	fmt.Println("1. PKI Certificate-based Document Encryption")
   369  	fmt.Println("---------------------------------------------")
   370  
   371  	// Generate key pairs for multiple users
   372  	users := []struct {
   373  		name    string
   374  		keyPair interface{}
   375  		cert    *cert.Certificate
   376  	}{}
   377  
   378  	// Alice - RSA
   379  	aliceKeyManager, _ := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048)
   380  	aliceKeyPair := aliceKeyManager.KeyPair()
   381  	aliceCert, err := cert.CreateSelfSignedCertificate(aliceKeyPair, cert.CertificateRequest{
   382  		Subject: pkix.Name{
   383  			CommonName:   "Alice Johnson",
   384  			Organization: []string{"Example Corp"},
   385  			Country:      []string{"US"},
   386  		},
   387  		EmailAddress: []string{"alice@example.com"},
   388  		ValidFor:     365 * 24 * time.Hour,
   389  	})
   390  	if err != nil {
   391  		log.Fatal("Failed to create Alice's certificate:", err)
   392  	}
   393  	users = append(users, struct {
   394  		name    string
   395  		keyPair interface{}
   396  		cert    *cert.Certificate
   397  	}{"Alice", aliceKeyPair, aliceCert})
   398  
   399  	// Bob - RSA (using RSA instead of ECDSA due to encryption module limitations)
   400  	bobKeyManager, _ := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048)
   401  	bobKeyPair := bobKeyManager.KeyPair()
   402  	bobCert, err := cert.CreateSelfSignedCertificate(bobKeyPair, cert.CertificateRequest{
   403  		Subject: pkix.Name{
   404  			CommonName:   "Bob Smith",
   405  			Organization: []string{"Example Corp"},
   406  			Country:      []string{"US"},
   407  		},
   408  		EmailAddress: []string{"bob@example.com"},
   409  		ValidFor:     365 * 24 * time.Hour,
   410  	})
   411  	if err != nil {
   412  		log.Fatal("Failed to create Bob's certificate:", err)
   413  	}
   414  	users = append(users, struct {
   415  		name    string
   416  		keyPair interface{}
   417  		cert    *cert.Certificate
   418  	}{"Bob", bobKeyPair, bobCert})
   419  
   420  	fmt.Printf("āœ“ Created certificates for %d users\n", len(users))
   421  
   422  	// Confidential document
   423  	document := []byte(`CONFIDENTIAL BUSINESS PLAN
   424  
   425  Company: Example Corp
   426  Date: 2024-12-19
   427  Classification: Top Secret
   428  
   429  Strategic Initiative Q1-2024:
   430  - Product launch timeline
   431  - Market expansion plans
   432  - Revenue projections: $2.5M
   433  - Competitive analysis
   434  - Resource allocation
   435  
   436  This document contains proprietary information and should only be
   437  accessed by authorized personnel with valid decryption credentials.`)
   438  
   439  	fmt.Printf("āœ“ Document size: %d bytes\n", len(document))
   440  
   441  	// Encrypt for each user
   442  	for _, user := range users {
   443  		fmt.Printf("\nEncrypting for %s...\n", user.name)
   444  
   445  		opts := encryption.DefaultEncryptOptions()
   446  		encrypted, err := certenc.EncryptDocument(document, user.cert, opts)
   447  		if err != nil {
   448  			log.Printf("Failed to encrypt for %s: %v", user.name, err)
   449  			continue
   450  		}
   451  
   452  		fmt.Printf("āœ“ Encrypted using %s\n", encrypted.Algorithm)
   453  		fmt.Printf("  Recipient: %s\n", user.cert.Certificate.Subject.CommonName)
   454  		fmt.Printf("  Encrypted size: %d bytes\n", len(encrypted.Data))
   455  
   456  		// Decrypt using the user's private key
   457  		decryptOpts := encryption.DefaultDecryptOptions()
   458  
   459  		switch kp := user.keyPair.(type) {
   460  		case *algo.RSAKeyPair:
   461  			_, err = certenc.DecryptDocument(encrypted, kp, decryptOpts)
   462  		case *algo.ECDSAKeyPair:
   463  			log.Printf("āš ļø ECDSA certificate-based encryption not yet fully supported for %s", user.name)
   464  			log.Printf("   Using RSA-based users instead to demonstrate functionality")
   465  			continue
   466  		case *algo.Ed25519KeyPair:
   467  			log.Printf("āš ļø Ed25519 certificate-based encryption not yet supported for %s", user.name)
   468  			continue
   469  		default:
   470  			log.Printf("Unsupported key type for %s", user.name)
   471  			continue
   472  		}
   473  
   474  		if err != nil {
   475  			log.Printf("%s failed to decrypt: %v", user.name, err)
   476  			continue
   477  		}
   478  
   479  		fmt.Printf("āœ“ %s successfully decrypted document\n", user.name)
   480  
   481  		// Save user-specific encrypted document and certificate
   482  		_ = fmt.Sprintf("output/document_%s.bin", strings.ToLower(user.name))
   483  		certFilename := fmt.Sprintf("output/cert_%s.pem", strings.ToLower(user.name))
   484  
   485  		saveEncryptionResult(fmt.Sprintf("cert_%s", strings.ToLower(user.name)), encrypted, map[string]interface{}{
   486  			"recipient": user.cert.Certificate.Subject.CommonName,
   487  			"email":     user.cert.Certificate.EmailAddresses,
   488  			"algorithm": string(encrypted.Algorithm),
   489  			"docSize":   len(document),
   490  			"encSize":   len(encrypted.Data),
   491  		})
   492  
   493  		user.cert.SaveToFile(certFilename)
   494  	}
   495  
   496  	fmt.Println("\nāœ“ Certificate-based encryption completed for all users")
   497  	fmt.Println()
   498  }
   499  
   500  func demonstrateCMSFormatSupport() {
   501  	fmt.Println("1. CMS (Cryptographic Message Syntax) Format")
   502  	fmt.Println("---------------------------------------------")
   503  
   504  	// Generate key pair for CMS demonstration
   505  	keyManager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048)
   506  	if err != nil {
   507  		log.Fatal("Failed to generate RSA key pair:", err)
   508  	}
   509  	keyPair := keyManager.KeyPair()
   510  
   511  	// Create certificate for CMS operations
   512  	testCert, err := cert.CreateSelfSignedCertificate(keyPair, cert.CertificateRequest{
   513  		Subject: pkix.Name{
   514  			CommonName:   "CMS Test Certificate",
   515  			Organization: []string{"GoPKI CMS Demo"},
   516  			Country:      []string{"US"},
   517  		},
   518  		ValidFor: 365 * 24 * time.Hour,
   519  	})
   520  	if err != nil {
   521  		log.Fatal("Failed to create test certificate:", err)
   522  	}
   523  	fmt.Println("āœ“ Created CMS test certificate")
   524  
   525  	// Test data for CMS format demonstration
   526  	testData := []byte("CMS format demonstration - RFC 5652 compliance test data")
   527  	fmt.Printf("āœ“ Test data: %s (%d bytes)\n", testData, len(testData))
   528  
   529  	// Encrypt with CMS format
   530  	opts := encryption.DefaultEncryptOptions()
   531  	opts.Format = encryption.FormatCMS
   532  
   533  	encrypted, err := asymmetric.Encrypt(testData, keyPair, opts)
   534  	if err != nil {
   535  		log.Fatal("CMS encryption failed:", err)
   536  	}
   537  
   538  	fmt.Printf("āœ“ Encrypted with format: %s\n", encrypted.Format)
   539  	fmt.Printf("  Algorithm: %s\n", encrypted.Algorithm)
   540  
   541  	// Encode to CMS format (RFC 5652)
   542  	cmsData, err := encryption.EncodeData(encrypted)
   543  	if err != nil {
   544  		fmt.Printf("āš ļø CMS encoding currently limited to specific configurations: %v\n", err)
   545  		fmt.Println("   Note: This is expected behavior for current encryption module limitations")
   546  
   547  		// Continue demonstration with available functionality
   548  		fmt.Printf("āœ“ Encryption completed successfully\n")
   549  		fmt.Printf("  Original: %s\n", testData)
   550  		return
   551  	}
   552  
   553  	fmt.Printf("āœ“ Encoded to CMS format: %d bytes\n", len(cmsData))
   554  	fmt.Printf("  Base64 preview: %s...\n", base64.StdEncoding.EncodeToString(cmsData[:min(32, len(cmsData))]))
   555  
   556  	// Decode from CMS format using type-safe API
   557  	decodedData, err := encryption.DecodeDataWithKey(cmsData, testCert.Certificate, keyPair.PrivateKey)
   558  	if err != nil {
   559  		log.Fatal("CMS decoding failed:", err)
   560  	}
   561  
   562  	fmt.Printf("āœ“ Decoded from CMS format successfully\n")
   563  	fmt.Printf("  Algorithm: %s\n", decodedData.Algorithm)
   564  	fmt.Printf("  Format: %s\n", decodedData.Format)
   565  
   566  	// Decrypt the decoded data
   567  	decryptOpts := encryption.DefaultDecryptOptions()
   568  	decrypted, err := asymmetric.Decrypt(decodedData, keyPair, decryptOpts)
   569  	if err != nil {
   570  		log.Fatal("Final decryption failed:", err)
   571  	}
   572  
   573  	fmt.Printf("āœ“ Final decryption: %s\n", decrypted)
   574  
   575  	// Save CMS format examples
   576  	os.WriteFile("output/cms_encoded.bin", cmsData, 0644)
   577  	os.WriteFile("output/cms_certificate.pem", testCert.DERData, 0644)
   578  
   579  	saveCMSExample("cms_format", map[string]interface{}{
   580  		"format":        "CMS (RFC 5652)",
   581  		"encodedSize":   len(cmsData),
   582  		"originalSize":  len(testData),
   583  		"algorithm":     string(encrypted.Algorithm),
   584  		"certificate":   testCert.Certificate.Subject.CommonName,
   585  		"base64Preview": base64.StdEncoding.EncodeToString(cmsData[:min(64, len(cmsData))]),
   586  	})
   587  
   588  	fmt.Println("āœ“ CMS format demonstration completed")
   589  	fmt.Println()
   590  }
   591  
   592  func demonstrateMultiRecipientEncryption() {
   593  	fmt.Println("1. Multi-Recipient Encryption Workflow")
   594  	fmt.Println("---------------------------------------")
   595  
   596  	// Create multiple recipients with different algorithms
   597  	recipients := []struct {
   598  		name    string
   599  		keyPair interface{}
   600  		cert    *cert.Certificate
   601  	}{}
   602  
   603  	// Alice - RSA 2048
   604  	aliceKeyManager, _ := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048)
   605  	aliceKeyPair := aliceKeyManager.KeyPair()
   606  	aliceCert, _ := cert.CreateSelfSignedCertificate(aliceKeyPair, cert.CertificateRequest{
   607  		Subject:  pkix.Name{CommonName: "Alice (RSA-2048)"},
   608  		ValidFor: 365 * 24 * time.Hour,
   609  	})
   610  	recipients = append(recipients, struct {
   611  		name    string
   612  		keyPair interface{}
   613  		cert    *cert.Certificate
   614  	}{"Alice", aliceKeyPair, aliceCert})
   615  
   616  	// Bob - RSA 3072 (stronger)
   617  	bobKeyManager, _ := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize3072)
   618  	bobKeyPair := bobKeyManager.KeyPair()
   619  	bobCert, _ := cert.CreateSelfSignedCertificate(bobKeyPair, cert.CertificateRequest{
   620  		Subject:  pkix.Name{CommonName: "Bob (RSA-3072)"},
   621  		ValidFor: 365 * 24 * time.Hour,
   622  	})
   623  	recipients = append(recipients, struct {
   624  		name    string
   625  		keyPair interface{}
   626  		cert    *cert.Certificate
   627  	}{"Bob", bobKeyPair, bobCert})
   628  
   629  	// Charlie - RSA 2048 (for comparison)
   630  	charlieKeyManager, _ := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048)
   631  	charlieKeyPair := charlieKeyManager.KeyPair()
   632  	charlieCert, _ := cert.CreateSelfSignedCertificate(charlieKeyPair, cert.CertificateRequest{
   633  		Subject:  pkix.Name{CommonName: "Charlie (RSA-2048)"},
   634  		ValidFor: 365 * 24 * time.Hour,
   635  	})
   636  	recipients = append(recipients, struct {
   637  		name    string
   638  		keyPair interface{}
   639  		cert    *cert.Certificate
   640  	}{"Charlie", charlieKeyPair, charlieCert})
   641  
   642  	fmt.Printf("āœ“ Created %d recipients with different key strengths\n", len(recipients))
   643  
   644  	// Confidential message for multi-recipient encryption
   645  	message := []byte(`URGENT SECURITY NOTICE
   646  
   647  Subject: Critical Security Update Required
   648  Classification: Confidential
   649  Distribution: Management Team Only
   650  
   651  All authorized recipients must implement the following security
   652  measures by end of business today:
   653  
   654  1. Update all system passwords
   655  2. Enable two-factor authentication
   656  3. Review access permissions
   657  4. Verify backup procedures
   658  
   659  This message has been encrypted for multiple authorized recipients
   660  using their respective public key certificates.
   661  
   662  Time-sensitive: Action required within 24 hours.`)
   663  
   664  	fmt.Printf("āœ“ Message size: %d bytes\n", len(message))
   665  
   666  	// Encrypt for each recipient individually
   667  	multiRecipientData := map[string]interface{}{
   668  		"message":    base64.StdEncoding.EncodeToString(message),
   669  		"recipients": []map[string]interface{}{},
   670  	}
   671  
   672  	opts := encryption.DefaultEncryptOptions()
   673  	opts.Format = encryption.FormatCMS
   674  
   675  	for i, recipient := range recipients {
   676  		fmt.Printf("\nEncrypting for %s...\n", recipient.name)
   677  
   678  		startTime := time.Now()
   679  		encrypted, err := envelope.Encrypt(message, recipient.keyPair.(*algo.RSAKeyPair), opts)
   680  		if err != nil {
   681  			log.Printf("Failed to encrypt for %s: %v", recipient.name, err)
   682  			continue
   683  		}
   684  		encryptionTime := time.Since(startTime)
   685  
   686  		fmt.Printf("āœ“ Encrypted in %v using %s\n", encryptionTime, encrypted.Algorithm)
   687  		fmt.Printf("  Recipient: %s\n", recipient.cert.Certificate.Subject.CommonName)
   688  		fmt.Printf("  Encrypted size: %d bytes\n", len(encrypted.Data))
   689  		fmt.Printf("  Key material: %d bytes\n", len(encrypted.EncryptedKey))
   690  
   691  		// Test decryption
   692  		startTime = time.Now()
   693  		decryptOpts := encryption.DefaultDecryptOptions()
   694  		decrypted, err := envelope.Decrypt(encrypted, recipient.keyPair.(*algo.RSAKeyPair), decryptOpts)
   695  		if err != nil {
   696  			log.Printf("%s failed to decrypt: %v", recipient.name, err)
   697  			continue
   698  		}
   699  		decryptionTime := time.Since(startTime)
   700  
   701  		fmt.Printf("āœ“ %s decrypted in %v\n", recipient.name, decryptionTime)
   702  		fmt.Printf("  Message preview: %s...\n", string(decrypted[:min(50, len(decrypted))]))
   703  
   704  		// Save individual encrypted copies
   705  		_ = fmt.Sprintf("output/multirecipient_%s.bin", strings.ToLower(recipient.name))
   706  		saveEncryptionResult(fmt.Sprintf("multirecipient_%s", strings.ToLower(recipient.name)), encrypted, map[string]interface{}{
   707  			"recipient":       recipient.cert.Certificate.Subject.CommonName,
   708  			"algorithm":       string(encrypted.Algorithm),
   709  			"encryptionTime":  encryptionTime.String(),
   710  			"decryptionTime":  decryptionTime.String(),
   711  			"messageSize":     len(message),
   712  			"encryptedSize":   len(encrypted.Data),
   713  			"keyMaterialSize": len(encrypted.EncryptedKey),
   714  		})
   715  
   716  		// Add to multi-recipient summary
   717  		recipientData := map[string]interface{}{
   718  			"name":           recipient.name,
   719  			"commonName":     recipient.cert.Certificate.Subject.CommonName,
   720  			"algorithm":      string(encrypted.Algorithm),
   721  			"encryptedSize":  len(encrypted.Data),
   722  			"encryptionTime": encryptionTime.String(),
   723  			"decryptionTime": decryptionTime.String(),
   724  		}
   725  		multiRecipientData["recipients"] = append(
   726  			multiRecipientData["recipients"].([]map[string]interface{}),
   727  			recipientData,
   728  		)
   729  
   730  		fmt.Printf("šŸ’¾ Saved encrypted copy #%d\n", i+1)
   731  	}
   732  
   733  	// Save multi-recipient summary
   734  	saveJSON("output/multirecipient_summary.json", multiRecipientData)
   735  
   736  	fmt.Printf("\nāœ“ Multi-recipient encryption completed for %d recipients\n", len(recipients))
   737  	fmt.Println("  Each recipient can decrypt using their private key")
   738  	fmt.Println("  Encryption strength varies by recipient key size")
   739  	fmt.Println()
   740  }
   741  
   742  func demonstratePerformanceAnalysis() {
   743  	fmt.Println("1. Encryption Performance Comparison")
   744  	fmt.Println("------------------------------------")
   745  
   746  	// Test data sizes
   747  	dataSizes := []struct {
   748  		name string
   749  		size int
   750  	}{
   751  		{"Small (1KB)", 1024},
   752  		{"Medium (10KB)", 10 * 1024},
   753  		{"Large (100KB)", 100 * 1024},
   754  	}
   755  
   756  	// RSA key pair for testing
   757  	keyManager, _ := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048)
   758  	keyPair := keyManager.KeyPair()
   759  
   760  	fmt.Printf("Testing with RSA-2048 key pair\n")
   761  	fmt.Printf("%-12s %-10s %-12s %-12s %-8s\n", "Data Size", "Method", "Encrypt", "Decrypt", "Ratio")
   762  	fmt.Println(strings.Repeat("-", 60))
   763  
   764  	performanceResults := []map[string]interface{}{}
   765  
   766  	for _, dataSize := range dataSizes {
   767  		// Generate test data
   768  		testData := make([]byte, dataSize.size)
   769  		for i := range testData {
   770  			testData[i] = byte(i % 256)
   771  		}
   772  
   773  		// Test direct encryption (for small data)
   774  		if dataSize.size <= 200 { // RSA-2048 can encrypt ~190 bytes directly
   775  			startTime := time.Now()
   776  			opts := encryption.DefaultEncryptOptions()
   777  			encrypted, err := asymmetric.Encrypt(testData, keyPair, opts)
   778  			encryptTime := time.Since(startTime)
   779  
   780  			if err == nil {
   781  				startTime = time.Now()
   782  				decryptOpts := encryption.DefaultDecryptOptions()
   783  				_, err = asymmetric.Decrypt(encrypted, keyPair, decryptOpts)
   784  				decryptTime := time.Since(startTime)
   785  
   786  				if err == nil {
   787  					ratio := float64(len(encrypted.Data)) / float64(len(testData))
   788  					fmt.Printf("%-12s %-10s %-12v %-12v %-8.1fx\n",
   789  						dataSize.name, "Direct", encryptTime, decryptTime, ratio)
   790  
   791  					performanceResults = append(performanceResults, map[string]interface{}{
   792  						"dataSize":      dataSize.name,
   793  						"method":        "Direct RSA",
   794  						"encryptTime":   encryptTime.String(),
   795  						"decryptTime":   decryptTime.String(),
   796  						"ratio":         ratio,
   797  						"originalSize":  len(testData),
   798  						"encryptedSize": len(encrypted.Data),
   799  					})
   800  				}
   801  			}
   802  		}
   803  
   804  		// Test envelope encryption (for all data sizes)
   805  		startTime := time.Now()
   806  		opts := encryption.DefaultEncryptOptions()
   807  		encrypted, err := envelope.Encrypt(testData, keyPair, opts)
   808  		encryptTime := time.Since(startTime)
   809  
   810  		if err == nil {
   811  			startTime = time.Now()
   812  			decryptOpts := encryption.DefaultDecryptOptions()
   813  			_, err = envelope.Decrypt(encrypted, keyPair, decryptOpts)
   814  			decryptTime := time.Since(startTime)
   815  
   816  			if err == nil {
   817  				ratio := float64(len(encrypted.Data)) / float64(len(testData))
   818  				fmt.Printf("%-12s %-10s %-12v %-12v %-8.1fx\n",
   819  					dataSize.name, "Envelope", encryptTime, decryptTime, ratio)
   820  
   821  				performanceResults = append(performanceResults, map[string]interface{}{
   822  					"dataSize":        dataSize.name,
   823  					"method":          "Envelope",
   824  					"encryptTime":     encryptTime.String(),
   825  					"decryptTime":     decryptTime.String(),
   826  					"ratio":           ratio,
   827  					"originalSize":    len(testData),
   828  					"encryptedSize":   len(encrypted.Data),
   829  					"keyMaterialSize": len(encrypted.EncryptedKey),
   830  				})
   831  			}
   832  		}
   833  	}
   834  
   835  	// Save performance results
   836  	saveJSON("output/performance_analysis.json", map[string]interface{}{
   837  		"timestamp": time.Now().Format(time.RFC3339),
   838  		"keyType":   "RSA-2048",
   839  		"results":   performanceResults,
   840  		"notes": []string{
   841  			"Direct encryption only works for small data (<190 bytes for RSA-2048)",
   842  			"Envelope encryption works for any data size",
   843  			"Envelope encryption provides better performance for large data",
   844  			"Encryption ratio includes all overhead (keys, IV, padding, etc.)",
   845  		},
   846  	})
   847  
   848  	fmt.Printf("\nāœ“ Performance analysis completed\n")
   849  	fmt.Println("šŸ’¾ Detailed results saved to performance_analysis.json")
   850  	fmt.Println()
   851  }
   852  
   853  func demonstrateFileOperations() {
   854  	fmt.Println("1. File-based Encryption Operations")
   855  	fmt.Println("-----------------------------------")
   856  
   857  	// Generate key pair for file operations
   858  	keyManager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048)
   859  	if err != nil {
   860  		log.Fatal("Failed to generate RSA key pair:", err)
   861  	}
   862  	keyPair := keyManager.KeyPair()
   863  
   864  	// Create test files with different content types
   865  	testFiles := []struct {
   866  		name    string
   867  		content []byte
   868  	}{
   869  		{
   870  			"config.json",
   871  			[]byte(`{
   872  	"database": {
   873  		"host": "secure-db.example.com",
   874  		"port": 5432,
   875  		"username": "admin",
   876  		"password": "super-secret-password",
   877  		"ssl": true
   878  	},
   879  	"api": {
   880  		"key": "sk-1234567890abcdef",
   881  		"secret": "secret-key-for-api-access"
   882  	}
   883  }`),
   884  		},
   885  		{
   886  			"document.txt",
   887  			[]byte(`CONFIDENTIAL BUSINESS DOCUMENT
   888  
   889  This document contains proprietary information including:
   890  - Customer data and contact information
   891  - Financial projections and revenue targets
   892  - Strategic partnerships and vendor agreements
   893  - Technical specifications and trade secrets
   894  
   895  Access to this information is restricted to authorized personnel only.
   896  Distribution outside the organization is strictly prohibited.`),
   897  		},
   898  	}
   899  
   900  	// Create certificate for file encryption
   901  	cert, err := cert.CreateSelfSignedCertificate(keyPair, cert.CertificateRequest{
   902  		Subject: pkix.Name{
   903  			CommonName:   "File Security Officer",
   904  			Organization: []string{"Example Corp"},
   905  		},
   906  		ValidFor: 365 * 24 * time.Hour,
   907  	})
   908  	if err != nil {
   909  		log.Fatal("Failed to create certificate:", err)
   910  	}
   911  
   912  	fmt.Printf("āœ“ Created certificate: %s\n", cert.Certificate.Subject.CommonName)
   913  
   914  	// Encrypt each test file
   915  	for _, file := range testFiles {
   916  		fmt.Printf("\nProcessing file: %s (%d bytes)\n", file.name, len(file.content))
   917  
   918  		// Save original file
   919  		originalPath := fmt.Sprintf("output/original_%s", file.name)
   920  		os.WriteFile(originalPath, file.content, 0644)
   921  
   922  		// Encrypt file content
   923  		opts := encryption.DefaultEncryptOptions()
   924  		opts.Format = encryption.FormatCMS
   925  
   926  		encrypted, err := envelope.Encrypt(file.content, keyPair, opts)
   927  		if err != nil {
   928  			log.Printf("Failed to encrypt %s: %v", file.name, err)
   929  			continue
   930  		}
   931  
   932  		fmt.Printf("āœ“ Encrypted using %s\n", encrypted.Algorithm)
   933  		fmt.Printf("  Original size: %d bytes\n", len(file.content))
   934  		fmt.Printf("  Encrypted size: %d bytes\n", len(encrypted.Data))
   935  
   936  		// Save encrypted file in binary format (CMS encoding has specific requirements)
   937  		encryptedPath := fmt.Sprintf("output/encrypted_%s.bin", file.name)
   938  		encryptedBytes, err := json.Marshal(encrypted)
   939  		if err != nil {
   940  			log.Printf("Failed to serialize %s: %v", file.name, err)
   941  			continue
   942  		}
   943  		os.WriteFile(encryptedPath, encryptedBytes, 0644)
   944  
   945  		// Note: CMS encoding requires specific recipient certificate configuration
   946  		// For demonstration, we save in JSON format which preserves all encryption metadata
   947  
   948  		// Test decryption
   949  		decryptOpts := encryption.DefaultDecryptOptions()
   950  		decrypted, err := envelope.Decrypt(encrypted, keyPair, decryptOpts)
   951  		if err != nil {
   952  			log.Printf("Failed to decrypt %s: %v", file.name, err)
   953  			continue
   954  		}
   955  
   956  		fmt.Printf("āœ“ Decrypted successfully\n")
   957  		fmt.Printf("  Data integrity: %t\n", len(decrypted) == len(file.content))
   958  
   959  		// Save decrypted file for verification
   960  		decryptedPath := fmt.Sprintf("output/decrypted_%s", file.name)
   961  		os.WriteFile(decryptedPath, decrypted, 0644)
   962  
   963  		fmt.Printf("šŸ’¾ Files saved:\n")
   964  		fmt.Printf("  Original: %s\n", originalPath)
   965  		fmt.Printf("  Encrypted: %s\n", encryptedPath)
   966  		fmt.Printf("  Decrypted: %s\n", decryptedPath)
   967  	}
   968  
   969  	// Save key pair and certificate for file operations
   970  	keypair.ToPEMFiles(keyPair, "output/file_encryption_private.pem", "output/file_encryption_public.pem")
   971  	cert.SaveToFile("output/file_encryption_cert.pem")
   972  
   973  	fmt.Println("\nāœ“ File encryption operations completed")
   974  	fmt.Println("šŸ”‘ Keys and certificate saved for manual decryption testing")
   975  	fmt.Println()
   976  }
   977  
   978  // Helper functions
   979  
   980  func saveEncryptionResult(prefix string, encrypted *encryption.EncryptedData, metadata map[string]interface{}) {
   981  	// Save binary data
   982  	filename := fmt.Sprintf("output/%s.bin", prefix)
   983  	cmsData, err := encryption.EncodeData(encrypted)
   984  	if err == nil {
   985  		os.WriteFile(filename, cmsData, 0644)
   986  	}
   987  
   988  	// Save metadata
   989  	metadataFile := fmt.Sprintf("output/%s_metadata.json", prefix)
   990  	allMetadata := map[string]interface{}{
   991  		"timestamp": time.Now().Format(time.RFC3339),
   992  		"algorithm": string(encrypted.Algorithm),
   993  		"format":    string(encrypted.Format),
   994  		"dataSize":  len(encrypted.Data),
   995  	}
   996  
   997  	// Merge custom metadata
   998  	for k, v := range metadata {
   999  		allMetadata[k] = v
  1000  	}
  1001  
  1002  	saveJSON(metadataFile, allMetadata)
  1003  }
  1004  
  1005  func saveCMSExample(prefix string, metadata map[string]interface{}) {
  1006  	filename := fmt.Sprintf("output/%s_info.json", prefix)
  1007  	allMetadata := map[string]interface{}{
  1008  		"timestamp": time.Now().Format(time.RFC3339),
  1009  		"standard":  "RFC 5652 - Cryptographic Message Syntax (CMS)",
  1010  	}
  1011  
  1012  	// Merge custom metadata
  1013  	for k, v := range metadata {
  1014  		allMetadata[k] = v
  1015  	}
  1016  
  1017  	saveJSON(filename, allMetadata)
  1018  }
  1019  
  1020  func saveJSON(filename string, data interface{}) {
  1021  	jsonData, err := json.MarshalIndent(data, "", "  ")
  1022  	if err != nil {
  1023  		log.Printf("Failed to marshal JSON: %v", err)
  1024  		return
  1025  	}
  1026  
  1027  	err = os.WriteFile(filename, jsonData, 0644)
  1028  	if err != nil {
  1029  		log.Printf("Failed to save file %s: %v", filename, err)
  1030  		return
  1031  	}
  1032  }
  1033  
  1034  func min(a, b int) int {
  1035  	if a < b {
  1036  		return a
  1037  	}
  1038  	return b
  1039  }