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

     1  # KeyPair Module Documentation
     2  
     3  Complete documentation for the GoPKI KeyPair module, demonstrating type-safe cryptographic key pair generation and management.
     4  
     5  ## Table of Contents
     6  - [Overview](#overview)
     7  - [Core Features](#core-features)
     8  - [API Approaches](#api-approaches)
     9  - [Supported Algorithms](#supported-algorithms)
    10  - [Format Conversion](#format-conversion)
    11  - [Security & Best Practices](#security--best-practices)
    12  - [Integration Examples](#integration-examples)
    13  
    14  ## Overview
    15  
    16  The KeyPair module provides type-safe cryptographic key pair generation and management through Go generics. It supports multiple algorithms with both algorithm-specific and generic APIs, ensuring compile-time type safety and consistent interfaces.
    17  
    18  ### Key Design Principles
    19  - **Type Safety**: Compile-time type checking through Go generics
    20  - **Algorithm Agnostic**: Unified interfaces across RSA, ECDSA, and Ed25519
    21  - **Format Flexibility**: Support for PEM, DER, SSH, and PKCS#12 formats
    22  - **Security First**: Enforced minimum key sizes and secure file permissions
    23  - **Performance Optimized**: Efficient key generation and format conversion
    24  
    25  ## Core Features
    26  
    27  ### 1. Type-Safe Key Generation
    28  ```go
    29  // Algorithm-specific API
    30  rsaKeys, err := algo.GenerateRSAKeyPair(algo.KeySize2048)
    31  ecdsaKeys, err := algo.GenerateECDSAKeyPair(algo.P256)
    32  ed25519Keys, err := algo.GenerateEd25519KeyPair()
    33  
    34  // Generic API with type constraints
    35  rsaKeys, err := keypair.GenerateKeyPair[algo.KeySize, *algo.RSAKeyPair](algo.KeySize2048)
    36  ```
    37  
    38  ### 2. Unified Manager Pattern
    39  ```go
    40  manager := keypair.NewManager()
    41  
    42  // All algorithms through single interface
    43  rsaKeys, err := manager.GenerateKeyPair("RSA", algo.KeySize2048)
    44  ecdsaKeys, err := manager.GenerateKeyPair("ECDSA", algo.P256)
    45  ed25519Keys, err := manager.GenerateKeyPair("Ed25519", algo.Ed25519Default)
    46  ```
    47  
    48  ### 3. Comprehensive Format Support
    49  - **PEM**: Standard ASCII armor format
    50  - **DER**: Binary ASN.1 encoding
    51  - **SSH**: OpenSSH public key format with optional passphrase protection
    52  - **PKCS#12**: Password-protected key and certificate bundles
    53  
    54  ### 4. Advanced Security Features
    55  - Enforced minimum key sizes (RSA ≥2048 bits)
    56  - Secure file permissions (0600 for private keys)
    57  - Constant-time key comparison
    58  - Memory clearing for sensitive data
    59  
    60  ## API Approaches
    61  
    62  ### Algorithm-Specific APIs
    63  Direct algorithm implementations for maximum performance and type safety:
    64  
    65  ```go
    66  import "github.com/jasoet/gopki/keypair/algo"
    67  
    68  // RSA with explicit key sizes
    69  rsaKeys, err := algo.GenerateRSAKeyPair(algo.KeySize2048)  // 2048 bits
    70  rsaKeys, err := algo.GenerateRSAKeyPair(algo.KeySize3072)  // 3072 bits
    71  rsaKeys, err := algo.GenerateRSAKeyPair(algo.KeySize4096)  // 4096 bits
    72  
    73  // ECDSA with standard curves
    74  ecdsaKeys, err := algo.GenerateECDSAKeyPair(algo.P224)    // P-224 curve
    75  ecdsaKeys, err := algo.GenerateECDSAKeyPair(algo.P256)    // P-256 curve
    76  ecdsaKeys, err := algo.GenerateECDSAKeyPair(algo.P384)    // P-384 curve
    77  ecdsaKeys, err := algo.GenerateECDSAKeyPair(algo.P521)    // P-521 curve
    78  
    79  // Ed25519 (fixed 256-bit)
    80  ed25519Keys, err := algo.GenerateEd25519KeyPair()
    81  ```
    82  
    83  ### Generic APIs with Type Constraints
    84  Generic functions using Go's type constraint system:
    85  
    86  ```go
    87  import "github.com/jasoet/gopki/keypair"
    88  
    89  // Generic key generation with compile-time type safety
    90  rsaKeys, err := keypair.GenerateKeyPair[algo.KeySize, *algo.RSAKeyPair](algo.KeySize2048)
    91  ecdsaKeys, err := keypair.GenerateKeyPair[algo.ECDSACurve, *algo.ECDSAKeyPair](algo.P256)
    92  ed25519Keys, err := keypair.GenerateKeyPair[algo.Ed25519Config, *algo.Ed25519KeyPair](algo.Ed25519Default)
    93  ```
    94  
    95  ### Manager Pattern
    96  Unified interface for runtime algorithm selection:
    97  
    98  ```go
    99  manager := keypair.NewManager()
   100  
   101  // Runtime algorithm selection with type safety
   102  rsaKeys, err := manager.GenerateKeyPair("RSA", algo.KeySize2048)
   103  ecdsaKeys, err := manager.GenerateKeyPair("ECDSA", algo.P256)
   104  ed25519Keys, err := manager.GenerateKeyPair("Ed25519", algo.Ed25519Default)
   105  
   106  // List supported algorithms
   107  algorithms := manager.SupportedAlgorithms()
   108  // Returns: ["RSA", "ECDSA", "Ed25519"]
   109  ```
   110  
   111  ## Supported Algorithms
   112  
   113  ### RSA (Rivest-Shamir-Adleman)
   114  - **Key Sizes**: 2048, 3072, 4096 bits (minimum 2048 enforced)
   115  - **Security**: Based on integer factorization difficulty
   116  - **Use Cases**: Digital signatures, key exchange, legacy compatibility
   117  - **Performance**: Slower than elliptic curve algorithms
   118  
   119  ```go
   120  // Available key sizes
   121  algo.KeySize2048  // 2048 bits (minimum)
   122  algo.KeySize3072  // 3072 bits (recommended)
   123  algo.KeySize4096  // 4096 bits (high security)
   124  ```
   125  
   126  ### ECDSA (Elliptic Curve Digital Signature Algorithm)
   127  - **Curves**: NIST P-224, P-256, P-384, P-521
   128  - **Security**: Based on elliptic curve discrete logarithm problem
   129  - **Use Cases**: Digital signatures, TLS certificates, modern PKI
   130  - **Performance**: Faster than RSA with smaller key sizes
   131  
   132  ```go
   133  // Available curves
   134  algo.P224  // P-224 curve (224-bit, ~2048-bit RSA equivalent)
   135  algo.P256  // P-256 curve (256-bit, ~3072-bit RSA equivalent)
   136  algo.P384  // P-384 curve (384-bit, ~7680-bit RSA equivalent)
   137  algo.P521  // P-521 curve (521-bit, ~15360-bit RSA equivalent)
   138  ```
   139  
   140  ### Ed25519 (Edwards-curve Digital Signature Algorithm)
   141  - **Key Size**: Fixed 256-bit keys
   142  - **Security**: High security with excellent performance
   143  - **Use Cases**: SSH keys, modern TLS, secure messaging
   144  - **Performance**: Fastest signing and verification
   145  
   146  ```go
   147  // Ed25519 uses empty string as config parameter
   148  ed25519Keys, err := algo.GenerateEd25519KeyPair()
   149  ```
   150  
   151  ## Format Conversion
   152  
   153  ### Format Conversion Matrix
   154  The module supports comprehensive format conversion between all supported formats:
   155  
   156  | Source Format | Target Formats | Function |
   157  |---------------|----------------|----------|
   158  | KeyPair | PEM | `keypair.ToPEMFiles()` |
   159  | KeyPair | DER | `keypair.ToDERFiles()` |
   160  | KeyPair | SSH | `keypair.ToSSHFiles()` |
   161  | KeyPair | PKCS#12 | `keypair.ToPKCS12File()` |
   162  | PEM | DER | `format.PEMToDER()` |
   163  | PEM | SSH | `format.PEMToSSH()` |
   164  | DER | PEM | `format.DERToPEM()` |
   165  | DER | SSH | `format.DERToSSH()` |
   166  | SSH | PEM | `format.SSHToPEM()` |
   167  
   168  ### Format-Specific Features
   169  
   170  #### PEM (Privacy-Enhanced Mail)
   171  - ASCII armor format with Base64 encoding
   172  - Standard format for certificates and keys
   173  - Human-readable with clear boundaries
   174  
   175  ```go
   176  // Save key pair to PEM files
   177  err := keypair.ToPEMFiles(keyPair, "private.pem", "public.pem")
   178  
   179  // Convert between formats
   180  pemData, err := format.DERToPEM(derData)
   181  ```
   182  
   183  #### DER (Distinguished Encoding Rules)
   184  - Binary ASN.1 encoding
   185  - Compact format for certificates and keys
   186  - Used in many cryptographic protocols
   187  
   188  ```go
   189  // Save key pair to DER files
   190  err := keypair.ToDERFiles(keyPair, "private.der", "public.der")
   191  
   192  // Convert to DER
   193  derData, err := format.PEMToDER(pemData)
   194  ```
   195  
   196  #### SSH (Secure Shell)
   197  - OpenSSH public key format
   198  - Includes algorithm identifier and comment
   199  - Optional passphrase protection
   200  
   201  ```go
   202  // Save to SSH format with custom comment
   203  err := keypair.ToSSHFiles(keyPair, "private_ssh", "public.ssh", "user@example.com")
   204  
   205  // Convert PEM to SSH format
   206  sshData, err := format.PEMToSSH(pemData, "converted@example.com")
   207  ```
   208  
   209  #### PKCS#12
   210  - Password-protected format
   211  - Can contain both keys and certificates
   212  - Industry standard for key distribution
   213  
   214  ```go
   215  // Save to PKCS#12 with password protection
   216  err := keypair.ToPKCS12File(keyPair, "keystore.p12", "secure-password")
   217  ```
   218  
   219  ## Security & Best Practices
   220  
   221  ### Key Size Recommendations
   222  
   223  | Algorithm | Minimum | Recommended | High Security |
   224  |-----------|---------|-------------|---------------|
   225  | RSA | 2048 bits | 3072 bits | 4096 bits |
   226  | ECDSA | P-256 | P-256 | P-384/P-521 |
   227  | Ed25519 | 256 bits (fixed) | 256 bits | 256 bits |
   228  
   229  ### File Security
   230  - Private key files: 0600 permissions (owner read/write only)
   231  - Public key files: 0644 permissions (world readable)
   232  - PKCS#12 files: 0600 permissions with strong passwords
   233  
   234  ### Performance Considerations
   235  ```go
   236  // Performance ranking (fastest to slowest)
   237  // 1. Ed25519 - Best overall performance
   238  // 2. ECDSA P-256 - Good balance of security and speed
   239  // 3. ECDSA P-384/P-521 - Higher security, slower
   240  // 4. RSA 2048 - Acceptable for compatibility
   241  // 5. RSA 3072/4096 - Slow but very secure
   242  ```
   243  
   244  ### Key Comparison and Validation
   245  ```go
   246  // Constant-time key comparison
   247  same := keypair.CompareKeys(key1, key2)
   248  
   249  // Key validation
   250  valid := keypair.ValidateKeyPair(keyPair)
   251  
   252  // Algorithm detection from PEM
   253  algorithm := keypair.DetectAlgorithm(pemData)
   254  ```
   255  
   256  ## Integration Examples
   257  
   258  ### Certificate Integration
   259  ```go
   260  // Generate key pair for certificate
   261  keyPair, err := algo.GenerateRSAKeyPair(algo.KeySize2048)
   262  
   263  // Create certificate request
   264  request := cert.CertificateRequest{
   265      Subject: pkix.Name{
   266          CommonName: "example.com",
   267      },
   268      KeyPair: keyPair,
   269      ValidFor: 365 * 24 * time.Hour,
   270  }
   271  
   272  // Create self-signed certificate
   273  certificate, err := cert.CreateSelfSignedCertificate(request)
   274  ```
   275  
   276  ### Document Signing Integration
   277  ```go
   278  // Generate signing key
   279  keyPair, err := algo.GenerateECDSAKeyPair(algo.P256)
   280  
   281  // Create signature
   282  signature, err := signing.SignDocument(data, keyPair, signing.SignOptions{
   283      Algorithm: signing.AlgorithmECDSA,
   284      Format:    signing.FormatPKCS7,
   285  })
   286  
   287  // Verify signature
   288  valid, err := signing.VerifySignature(data, signature, keyPair.PublicKey)
   289  ```
   290  
   291  ### Encryption Integration
   292  ```go
   293  // Generate encryption key pair
   294  keyPair, err := algo.GenerateRSAKeyPair(algo.KeySize2048)
   295  
   296  // Encrypt data
   297  encryptedData, err := encryption.EncryptData(data, keyPair.PublicKey)
   298  
   299  // Decrypt data
   300  decryptedData, err := encryption.DecryptData(encryptedData, keyPair.PrivateKey)
   301  ```
   302  
   303  ### Cross-Algorithm Compatibility
   304  ```go
   305  // Test compatibility between different algorithms
   306  algorithms := []string{"RSA", "ECDSA", "Ed25519"}
   307  manager := keypair.NewManager()
   308  
   309  for _, alg1 := range algorithms {
   310      for _, alg2 := range algorithms {
   311          key1, _ := manager.GenerateKeyPair(alg1, getDefaultParam(alg1))
   312          key2, _ := manager.GenerateKeyPair(alg2, getDefaultParam(alg2))
   313  
   314          compatible := keypair.TestCompatibility(key1, key2)
   315          fmt.Printf("%s ↔ %s: %v\n", alg1, alg2, compatible)
   316      }
   317  }
   318  ```
   319  
   320  ## Error Handling
   321  
   322  ### Common Error Patterns
   323  ```go
   324  // Key generation with proper error handling
   325  keyPair, err := algo.GenerateRSAKeyPair(algo.KeySize2048)
   326  if err != nil {
   327      if errors.Is(err, keypair.ErrInvalidKeySize) {
   328          return fmt.Errorf("invalid key size: %w", err)
   329      }
   330      return fmt.Errorf("key generation failed: %w", err)
   331  }
   332  
   333  // File operations with error handling
   334  err = keypair.ToPEMFiles(keyPair, "private.pem", "public.pem")
   335  if err != nil {
   336      if errors.Is(err, os.ErrPermission) {
   337          return fmt.Errorf("permission denied: %w", err)
   338      }
   339      return fmt.Errorf("file save failed: %w", err)
   340  }
   341  ```
   342  
   343  ### Error Types
   344  - `keypair.ErrInvalidKeySize`: Key size below minimum requirements
   345  - `keypair.ErrUnsupportedAlgorithm`: Algorithm not supported
   346  - `keypair.ErrInvalidFormat`: Invalid key format
   347  - `keypair.ErrKeyMismatch`: Public/private key pair mismatch
   348  
   349  ## Performance Benchmarks
   350  
   351  ### Key Generation Performance (relative)
   352  ```
   353  Ed25519:    1.0x (fastest)
   354  ECDSA P-256: 1.2x
   355  ECDSA P-384: 1.5x
   356  RSA 2048:   15.0x
   357  RSA 3072:   35.0x
   358  RSA 4096:   80.0x (slowest)
   359  ```
   360  
   361  ### Format Conversion Performance
   362  ```
   363  PEM ↔ DER:   ~1ms
   364  PEM ↔ SSH:   ~2ms
   365  DER ↔ SSH:   ~3ms
   366  Any ↔ PKCS#12: ~5ms
   367  ```
   368  
   369  ---
   370  
   371  For complete working examples, see the `main.go` file in this directory.
   372  For integration with other modules, see the main project [README](../../README.md).