github.com/jasoet/gopki@v1.15.0/examples/encryption/doc.md (about)

     1  # Encryption Module Documentation
     2  
     3  Complete documentation for the GoPKI Encryption module, demonstrating type-safe data encryption with multi-algorithm support and CMS format compliance.
     4  
     5  ## Table of Contents
     6  - [Overview](#overview)
     7  - [Core Features](#core-features)
     8  - [Encryption Methods](#encryption-methods)
     9  - [Supported Algorithms](#supported-algorithms)
    10  - [CMS Format Support](#cms-format-support)
    11  - [Security & Best Practices](#security--best-practices)
    12  - [Integration Examples](#integration-examples)
    13  
    14  ## Overview
    15  
    16  The Encryption module provides comprehensive data encryption and decryption capabilities using type-safe APIs with automatic algorithm selection based on key types. It supports direct encryption for small data, envelope encryption for large data, and industry-standard CMS (RFC 5652) format for enterprise compatibility.
    17  
    18  ### Key Design Principles
    19  - **Type Safety**: Compile-time type checking through Go generics from keypair module
    20  - **Algorithm Agnostic**: Automatic algorithm selection based on key type
    21  - **Standards Compliance**: RFC 5652 CMS format support for enterprise interoperability
    22  - **Performance Optimized**: Automatic method selection (direct vs. envelope encryption)
    23  - **Certificate Integration**: Seamless PKI workflows with certificate-based encryption
    24  
    25  ## Core Features
    26  
    27  ### 1. Multi-Algorithm Encryption
    28  ```go
    29  // RSA-OAEP encryption (direct for small data)
    30  rsaManager, _ := keypair.Generate[algo.KeySize, *algo.RSAKeyPair](algo.KeySize2048)
    31  encrypted, err := asymmetric.Encrypt(data, rsaManager.KeyPair(), encryption.DefaultEncryptOptions())
    32  
    33  // ECDSA + ECDH encryption (key agreement + AES-GCM)
    34  ecdsaManager, _ := keypair.Generate[algo.ECDSACurve, *algo.ECDSAKeyPair](algo.P256)
    35  encrypted, err := envelope.Encrypt(data, ecdsaManager.KeyPair(), encryption.DefaultEncryptOptions())
    36  
    37  // Ed25519 + X25519 encryption (modern high-performance)
    38  ed25519Manager, _ := keypair.Generate[algo.Ed25519Config, *algo.Ed25519KeyPair](algo.Ed25519Config{})
    39  encrypted, err := envelope.Encrypt(data, ed25519Manager.KeyPair(), encryption.DefaultEncryptOptions())
    40  ```
    41  
    42  ### 2. Envelope Encryption for Large Data
    43  ```go
    44  // Automatic envelope encryption for large data (hybrid encryption)
    45  opts := encryption.DefaultEncryptOptions()
    46  opts.Format = encryption.FormatCMS
    47  
    48  largeData := make([]byte, 1024*100) // 100KB data
    49  encrypted, err := envelope.Encrypt(largeData, keyPair, opts)
    50  // Uses AES-GCM for data + RSA/ECDH for key encryption
    51  ```
    52  
    53  ### 3. Certificate-based Encryption
    54  ```go
    55  // PKI certificate-based document encryption
    56  certificate, _ := cert.CreateSelfSignedCertificate(keyPair, certRequest)
    57  encrypted, err := certenc.EncryptDocument(document, certificate, encryption.DefaultEncryptOptions())
    58  
    59  // Decrypt using private key
    60  decrypted, err := certenc.DecryptDocument(encrypted, keyPair, encryption.DefaultDecryptOptions())
    61  ```
    62  
    63  ### 4. CMS Format Operations
    64  ```go
    65  // Encode to CMS format (RFC 5652)
    66  cmsData, err := encryption.EncodeData(encrypted)
    67  
    68  // Decode from CMS format with type-safe API
    69  decodedData, err := encryption.DecodeDataWithKey(cmsData, certificate, privateKey)
    70  ```
    71  
    72  ## Encryption Methods
    73  
    74  ### Method Selection Matrix
    75  
    76  | Data Size | RSA Key | ECDSA Key | Ed25519 Key | Method Used |
    77  |-----------|---------|-----------|-------------|-------------|
    78  | **≤190 bytes** | Direct RSA-OAEP | Envelope (ECDH+AES) | Envelope (X25519+AES) | Automatic |
    79  | **>190 bytes** | Envelope (RSA+AES) | Envelope (ECDH+AES) | Envelope (X25519+AES) | Automatic |
    80  | **Any size** | Envelope preferred | Envelope only | Envelope only | Manual |
    81  
    82  ### Direct Encryption
    83  - **Use Case**: Small data that fits within key constraints
    84  - **RSA Limit**: ~190 bytes for 2048-bit keys, ~318 bytes for 3072-bit keys
    85  - **Performance**: Single cryptographic operation
    86  - **Security**: Full asymmetric encryption strength
    87  
    88  ### Envelope Encryption (Hybrid)
    89  - **Use Case**: Any data size, especially large data
    90  - **Method**: AES-GCM for data + asymmetric encryption for AES key
    91  - **Performance**: Optimal for large data sets
    92  - **Security**: Combines symmetric and asymmetric encryption benefits
    93  
    94  ## Supported Algorithms
    95  
    96  ### RSA (Rivest-Shamir-Adleman)
    97  - **Key Sizes**: 2048, 3072, 4096 bits (minimum 2048 enforced)
    98  - **Encryption Method**: RSA-OAEP with SHA-256/SHA-384/SHA-512
    99  - **Direct Limit**: ~190 bytes (2048-bit), ~318 bytes (3072-bit)
   100  - **Use Cases**: Maximum compatibility, enterprise PKI environments
   101  
   102  ```go
   103  // RSA encryption examples
   104  rsaManager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair](algo.KeySize2048)
   105  keyPair := rsaManager.KeyPair()
   106  
   107  // Small data - direct encryption
   108  smallData := []byte("Short confidential message")
   109  encrypted, err := asymmetric.Encrypt(smallData, keyPair, encryption.DefaultEncryptOptions())
   110  
   111  // Large data - envelope encryption
   112  largeData := make([]byte, 10240) // 10KB
   113  encrypted, err = envelope.Encrypt(largeData, keyPair, encryption.DefaultEncryptOptions())
   114  ```
   115  
   116  ### ECDSA + ECDH (Elliptic Curve)
   117  - **Curves**: P-256, P-384, P-521
   118  - **Key Agreement**: ECDH for shared secret generation
   119  - **Symmetric Cipher**: AES-GCM with 256-bit keys
   120  - **Use Cases**: Modern PKI, efficient encryption, smaller key sizes
   121  
   122  ```go
   123  // ECDSA encryption examples
   124  ecdsaManager, err := keypair.Generate[algo.ECDSACurve, *algo.ECDSAKeyPair](algo.P256)
   125  keyPair := ecdsaManager.KeyPair()
   126  
   127  // Always uses envelope encryption (ECDH + AES-GCM)
   128  data := []byte("ECDSA message using ECDH key agreement")
   129  encrypted, err := envelope.Encrypt(data, keyPair, encryption.DefaultEncryptOptions())
   130  ```
   131  
   132  ### Ed25519 + X25519 (Modern Elliptic Curve)
   133  - **Key Size**: Fixed 256-bit keys
   134  - **Key Agreement**: X25519 (Curve25519 for ECDH)
   135  - **Symmetric Cipher**: AES-GCM with 256-bit keys
   136  - **Use Cases**: High performance, modern applications, maximum security
   137  
   138  ```go
   139  // Ed25519 encryption examples
   140  ed25519Manager, err := keypair.Generate[algo.Ed25519Config, *algo.Ed25519KeyPair](algo.Ed25519Config{})
   141  keyPair := ed25519Manager.KeyPair()
   142  
   143  // Always uses envelope encryption (X25519 + AES-GCM)
   144  data := []byte("Modern Ed25519 encryption with X25519 key agreement")
   145  encrypted, err := envelope.Encrypt(data, keyPair, encryption.DefaultEncryptOptions())
   146  ```
   147  
   148  ## CMS Format Support
   149  
   150  ### CMS (Cryptographic Message Syntax) - RFC 5652
   151  
   152  The encryption module provides full support for CMS format, the industry standard for cryptographic message syntax.
   153  
   154  #### CMS Features
   155  - **Standards Compliance**: Full RFC 5652 implementation
   156  - **Interoperability**: Compatible with OpenSSL, Microsoft CryptoAPI, Java
   157  - **Algorithm Agility**: Support for multiple encryption algorithms
   158  - **Extensible**: Support for custom attributes and metadata
   159  
   160  #### CMS Operations
   161  ```go
   162  // Create encrypted data
   163  encrypted, err := asymmetric.Encrypt(data, keyPair, encryption.DefaultEncryptOptions())
   164  
   165  // Encode to CMS format
   166  cmsData, err := encryption.EncodeData(encrypted)
   167  
   168  // Decode from CMS format (type-safe)
   169  decodedData, err := encryption.DecodeDataWithKey(cmsData, certificate, privateKey)
   170  
   171  // Alternative generic decode (requires type parameter)
   172  decodedData, err := encryption.DecodeFromCMS[*rsa.PrivateKey](cmsData, certificate, privateKey)
   173  ```
   174  
   175  #### CMS Structure
   176  ```
   177  CMS EnvelopedData ::= SEQUENCE {
   178      version CMSVersion,
   179      recipientInfos RecipientInfos,
   180      encryptedContentInfo EncryptedContentInfo,
   181      unprotectedAttrs [1] IMPLICIT UnprotectedAttributes OPTIONAL
   182  }
   183  ```
   184  
   185  ## Security & Best Practices
   186  
   187  ### Algorithm Selection Guidelines
   188  
   189  | Use Case | Recommended Algorithm | Key Size | Method |
   190  |----------|----------------------|----------|--------|
   191  | **New Applications** | Ed25519 + X25519 | 256-bit (fixed) | Envelope |
   192  | **Enterprise PKI** | RSA 3072+ | 3072+ bits | Envelope |
   193  | **Modern Standards** | ECDSA P-256+ | P-256+ | Envelope |
   194  | **Legacy Compatibility** | RSA 2048+ | 2048+ bits | Direct/Envelope |
   195  | **High Performance** | Ed25519 + X25519 | 256-bit (fixed) | Envelope |
   196  
   197  ### Encryption Method Selection
   198  ```go
   199  // Automatic method selection based on data size and key type
   200  func selectEncryptionMethod(dataSize int, keyType string) string {
   201      switch keyType {
   202      case "RSA":
   203          if dataSize <= getDirectEncryptionLimit(keyType) {
   204              return "Direct RSA-OAEP"
   205          }
   206          return "Envelope (RSA + AES-GCM)"
   207      case "ECDSA", "Ed25519":
   208          return "Envelope (ECDH/X25519 + AES-GCM)"
   209      }
   210  }
   211  ```
   212  
   213  ### Security Considerations
   214  - **Key Size**: Use minimum recommended key sizes for each algorithm
   215  - **Random Numbers**: All encryption uses cryptographically secure random number generation
   216  - **Forward Secrecy**: Envelope encryption provides forward secrecy through ephemeral keys
   217  - **Authenticated Encryption**: AES-GCM provides both confidentiality and authenticity
   218  - **Side-Channel Resistance**: Constant-time operations where possible
   219  
   220  ### Performance Optimization
   221  ```go
   222  // Performance characteristics (relative, 1KB data)
   223  Performance Rankings:
   224  1. Ed25519 + X25519 + AES-GCM    ~1.0x (fastest)
   225  2. ECDSA P-256 + ECDH + AES-GCM  ~1.2x
   226  3. ECDSA P-384 + ECDH + AES-GCM  ~1.5x
   227  4. RSA-2048 + AES-GCM            ~3.0x
   228  5. RSA-3072 + AES-GCM            ~6.0x
   229  6. RSA-4096 + AES-GCM            ~12.0x (slowest)
   230  ```
   231  
   232  ## Integration Examples
   233  
   234  ### Certificate Module Integration
   235  ```go
   236  // Generate key pair for encryption
   237  keyManager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair](algo.KeySize2048)
   238  keyPair := keyManager.KeyPair()
   239  
   240  // Create certificate for recipient
   241  certificate, err := cert.CreateSelfSignedCertificate(keyPair, cert.CertificateRequest{
   242      Subject: pkix.Name{CommonName: "Document Recipient"},
   243      ValidFor: 365 * 24 * time.Hour,
   244  })
   245  
   246  // Encrypt document for certificate holder
   247  document := []byte("Confidential business document")
   248  encrypted, err := certenc.EncryptDocument(document, certificate, encryption.DefaultEncryptOptions())
   249  
   250  // Decrypt using private key
   251  decrypted, err := certenc.DecryptDocument(encrypted, keyPair, encryption.DefaultDecryptOptions())
   252  ```
   253  
   254  ### Multi-Recipient Encryption
   255  ```go
   256  // Create multiple recipients with different algorithms
   257  recipients := []struct {
   258      name    string
   259      keyPair interface{}
   260      cert    *cert.Certificate
   261  }{
   262      {"Alice", rsaKeyPair, rsaCert},       // RSA-2048
   263      {"Bob", ecdsaKeyPair, ecdsaCert},     // ECDSA P-256
   264      {"Charlie", ed25519KeyPair, ed25519Cert}, // Ed25519
   265  }
   266  
   267  // Encrypt for each recipient separately
   268  message := []byte("Multi-recipient confidential message")
   269  for _, recipient := range recipients {
   270      encrypted, err := envelope.Encrypt(message, recipient.keyPair, encryption.DefaultEncryptOptions())
   271      // Each recipient gets their own encrypted copy
   272      saveForRecipient(encrypted, recipient.name)
   273  }
   274  ```
   275  
   276  ### File Encryption Workflow
   277  ```go
   278  // File encryption with CMS format
   279  fileData, err := os.ReadFile("confidential.pdf")
   280  if err != nil {
   281      log.Fatal(err)
   282  }
   283  
   284  // Encrypt file data
   285  opts := encryption.DefaultEncryptOptions()
   286  opts.Format = encryption.FormatCMS
   287  encrypted, err := envelope.Encrypt(fileData, keyPair, opts)
   288  
   289  // Save encrypted file in CMS format
   290  cmsData, err := encryption.EncodeData(encrypted)
   291  err = os.WriteFile("confidential.pdf.cms", cmsData, 0644)
   292  
   293  // Later: decrypt the file
   294  decodedData, err := encryption.DecodeDataWithKey(cmsData, certificate, privateKey)
   295  decrypted, err := envelope.Decrypt(decodedData, keyPair, encryption.DefaultDecryptOptions())
   296  err = os.WriteFile("decrypted.pdf", decrypted, 0644)
   297  ```
   298  
   299  ### Performance Testing Integration
   300  ```go
   301  // Benchmark different encryption methods
   302  algorithms := []struct {
   303      name    string
   304      keyPair interface{}
   305  }{
   306      {"RSA-2048", rsaKeyPair},
   307      {"ECDSA-P256", ecdsaKeyPair},
   308      {"Ed25519", ed25519KeyPair},
   309  }
   310  
   311  testData := make([]byte, 100*1024) // 100KB test data
   312  
   313  for _, alg := range algorithms {
   314      // Measure encryption performance
   315      startTime := time.Now()
   316      encrypted, err := envelope.Encrypt(testData, alg.keyPair, encryption.DefaultEncryptOptions())
   317      encryptTime := time.Since(startTime)
   318  
   319      // Measure decryption performance
   320      startTime = time.Now()
   321      decrypted, err := envelope.Decrypt(encrypted, alg.keyPair, encryption.DefaultDecryptOptions())
   322      decryptTime := time.Since(startTime)
   323  
   324      fmt.Printf("%-12s Encrypt: %-8v Decrypt: %-8v Size: %d bytes\n",
   325          alg.name, encryptTime, decryptTime, len(encrypted.Data))
   326  }
   327  ```
   328  
   329  ## Error Handling
   330  
   331  ### Common Error Patterns
   332  ```go
   333  // Encryption with proper error handling
   334  encrypted, err := asymmetric.Encrypt(data, keyPair, opts)
   335  if err != nil {
   336      if errors.Is(err, encryption.ErrDataTooLarge) {
   337          // Try envelope encryption for large data
   338          encrypted, err = envelope.Encrypt(data, keyPair, opts)
   339      }
   340      if errors.Is(err, encryption.ErrUnsupportedAlgorithm) {
   341          return fmt.Errorf("algorithm not supported: %w", err)
   342      }
   343      return fmt.Errorf("encryption failed: %w", err)
   344  }
   345  
   346  // Decryption with error handling
   347  decrypted, err := asymmetric.Decrypt(encrypted, keyPair, decryptOpts)
   348  if err != nil {
   349      if errors.Is(err, encryption.ErrDecryptionFailed) {
   350          return fmt.Errorf("decryption failed - wrong key?: %w", err)
   351      }
   352      if errors.Is(err, encryption.ErrInvalidFormat) {
   353          return fmt.Errorf("invalid encrypted data format: %w", err)
   354      }
   355      return fmt.Errorf("decryption error: %w", err)
   356  }
   357  ```
   358  
   359  ### Error Types
   360  - `encryption.ErrDataTooLarge`: Data exceeds direct encryption limits
   361  - `encryption.ErrUnsupportedAlgorithm`: Algorithm not supported
   362  - `encryption.ErrDecryptionFailed`: Cryptographic decryption failure
   363  - `encryption.ErrInvalidFormat`: Malformed encrypted data
   364  - `encryption.ErrMissingPrivateKey`: Private key required but not provided
   365  - `encryption.ErrInvalidCertificate`: Certificate validation failed
   366  - `encryption.ErrCMSFormatError`: CMS format parsing error
   367  
   368  ## Performance Benchmarks
   369  
   370  ### Encryption Performance (100KB document)
   371  ```
   372  Algorithm           Encrypt Time  Decrypt Time  Encrypted Size  Method
   373  RSA-2048           ~8ms          ~2ms          ~100KB + 256B   Envelope
   374  RSA-3072           ~15ms         ~4ms          ~100KB + 384B   Envelope
   375  RSA-4096           ~30ms         ~8ms          ~100KB + 512B   Envelope
   376  ECDSA-P256         ~3ms          ~5ms          ~100KB + 64B    Envelope
   377  ECDSA-P384         ~5ms          ~8ms          ~100KB + 96B    Envelope
   378  Ed25519            ~2ms          ~3ms          ~100KB + 64B    Envelope
   379  ```
   380  
   381  ### Direct Encryption Limits
   382  ```
   383  RSA-2048:  ~190 bytes maximum
   384  RSA-3072:  ~318 bytes maximum
   385  RSA-4096:  ~446 bytes maximum
   386  ECDSA:     Not supported (uses envelope)
   387  Ed25519:   Not supported (uses envelope)
   388  ```
   389  
   390  ### CMS Format Overhead
   391  ```
   392  Base encrypted data:     Variable (depends on content)
   393  CMS structure overhead:  ~50-200 bytes
   394  Certificate embedding:   ~800-2000 bytes (optional)
   395  Metadata attributes:     ~20-100 bytes (optional)
   396  ```
   397  
   398  ### Key Performance Insights
   399  - **Ed25519**: Best overall performance with modern security
   400  - **ECDSA**: Good balance of performance and standards compliance
   401  - **RSA**: Maximum compatibility but higher computational cost
   402  - **Envelope Encryption**: Consistently good performance for any data size
   403  - **CMS Format**: Minimal overhead with maximum interoperability
   404  
   405  ---
   406  
   407  For complete working examples, see the `main.go` file in this directory.
   408  For integration with other modules, see the main project [README](../../README.md).