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

     1  # Signing Module Documentation
     2  
     3  Complete documentation for the GoPKI Signing module, demonstrating hybrid approach document signing and signature verification with multi-algorithm support.
     4  
     5  ## Table of Contents
     6  - [Overview](#overview)
     7  - [Core Features](#core-features)
     8  - [Hybrid Architecture](#hybrid-architecture)
     9  - [Supported Algorithms](#supported-algorithms)
    10  - [Signature Formats](#signature-formats)
    11  - [Security & Best Practices](#security--best-practices)
    12  - [Integration Examples](#integration-examples)
    13  
    14  ## Overview
    15  
    16  The Signing module provides comprehensive document signing and signature verification using a hybrid approach that maximizes compatibility and performance. It supports RSA, ECDSA, and Ed25519 algorithms with industry-standard PKCS#7/CMS format for RSA/ECDSA and optimized raw signatures for Ed25519.
    17  
    18  ### Key Design Principles
    19  - **Hybrid Approach**: PKCS#7/CMS for RSA/ECDSA, raw signatures for Ed25519
    20  - **Type Safety**: Compile-time type checking through Go generics
    21  - **Standards Compliance**: Industry-standard PKCS#7/CMS using Smallstep library
    22  - **Performance Optimized**: Algorithm-specific optimizations for maximum speed
    23  - **Certificate Integration**: Seamless integration with certificate module
    24  
    25  ## Core Features
    26  
    27  ### 1. Multi-Algorithm Signing
    28  ```go
    29  // RSA signing with PKCS#7 format
    30  rsaManager, _ := keypair.Generate[algo.KeySize, *algo.RSAKeyPair](algo.KeySize2048)
    31  signature, err := signing.SignData(data, rsaManager.KeyPair(), certificate)
    32  
    33  // ECDSA signing with PKCS#7 format
    34  ecdsaManager, _ := keypair.Generate[algo.ECDSACurve, *algo.ECDSAKeyPair](algo.P256)
    35  signature, err := signing.SignData(data, ecdsaManager.KeyPair(), certificate)
    36  
    37  // Ed25519 signing with raw format (hybrid approach)
    38  ed25519Manager, _ := keypair.Generate[algo.Ed25519Config, *algo.Ed25519KeyPair](algo.Ed25519Config{})
    39  signature, err := signing.SignData(data, ed25519Manager.KeyPair(), certificate)
    40  ```
    41  
    42  ### 2. Advanced Signing Options
    43  ```go
    44  opts := signing.SignOptions{
    45      HashAlgorithm:      crypto.SHA256,
    46      Format:             signing.FormatPKCS7Detached,
    47      IncludeCertificate: true,
    48      IncludeChain:       true,
    49      ExtraCertificates:  []*x509.Certificate{intermediateCert},
    50      Attributes: map[string]interface{}{
    51          "version": "1.0",
    52          "author":  "John Doe",
    53      },
    54  }
    55  signature, err := signing.SignDocument(data, keyPair, certificate, opts)
    56  ```
    57  
    58  ### 3. Comprehensive Verification
    59  ```go
    60  // Standard verification
    61  err := signing.VerifySignature(data, signature, signing.DefaultVerifyOptions())
    62  
    63  // Chain verification with trusted roots
    64  verifyOpts := signing.DefaultVerifyOptions()
    65  verifyOpts.VerifyChain = true
    66  verifyOpts.Roots = rootCertPool
    67  err := signing.VerifySignature(data, signature, verifyOpts)
    68  
    69  // Detached signature verification
    70  err := signing.VerifyDetachedSignature(data, sigBytes, certificate, crypto.SHA256)
    71  ```
    72  
    73  ### 4. File Operations
    74  ```go
    75  // Sign file directly
    76  signature, err := signing.SignFile("document.pdf", keyPair, certificate)
    77  
    78  // Stream signing for large files
    79  signature, err := signing.SignStream(fileReader, keyPair, certificate)
    80  ```
    81  
    82  ## Hybrid Architecture
    83  
    84  ### Architecture Overview
    85  ```
    86  ┌─────────────────────┐    ┌──────────────────────┐    ┌─────────────────────┐
    87  │   RSA Signing       │    │   ECDSA Signing      │    │   Ed25519 Signing   │
    88  │                     │    │                      │    │                     │
    89  │ ✓ PKCS#7 Attached   │    │ ✓ PKCS#7 Attached    │    │ ✓ Raw Signatures    │
    90  │ ✓ PKCS#7 Detached   │    │ ✓ PKCS#7 Detached    │    │ ✓ Direct Verify     │
    91  │ ✓ Certificate Chain │    │ ✓ Certificate Chain  │    │ ✓ High Performance  │
    92  │ ✓ Industry Standard │    │ ✓ Smaller Signatures │    │ ✓ Modern Crypto     │
    93  └─────────────────────┘    └──────────────────────┘    └─────────────────────┘
    94                           │
    95                           ▼
    96             ┌────────────────────────────────────┐
    97             │        Unified Signing API          │
    98             │                                    │
    99             │  • SignData()                      │
   100             │  • SignDocument()                  │
   101             │  • SignFile()                      │
   102             │  • VerifySignature()               │
   103             │  • VerifyWithCertificate()         │
   104             └────────────────────────────────────┘
   105  ```
   106  
   107  ### Format Selection Logic
   108  - **RSA & ECDSA**: Automatic PKCS#7/CMS format selection
   109  - **Ed25519**: Raw signature format (RFC 8419 not yet implemented in libraries)
   110  - **API Transparency**: Same function calls for all algorithms
   111  - **Format Detection**: Automatic format detection during verification
   112  
   113  ## Supported Algorithms
   114  
   115  ### RSA (Rivest-Shamir-Adleman)
   116  - **Key Sizes**: 2048, 3072, 4096 bits (minimum 2048 enforced)
   117  - **Hash Algorithms**: SHA-256, SHA-384, SHA-512 (auto-selected based on key size)
   118  - **Format**: PKCS#7/CMS (attached and detached)
   119  - **Library**: Smallstep PKCS#7
   120  - **Use Cases**: Maximum compatibility, legacy systems, enterprise PKI
   121  
   122  ```go
   123  // RSA signing examples
   124  rsaManager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair](algo.KeySize2048)
   125  signature, err := signing.SignData(data, rsaManager.KeyPair(), certificate)
   126  // Automatically uses PKCS#7 format with SHA-256
   127  ```
   128  
   129  ### ECDSA (Elliptic Curve Digital Signature Algorithm)
   130  - **Curves**: P-256, P-384, P-521
   131  - **Hash Algorithms**: SHA-256 (P-256), SHA-384 (P-384), SHA-512 (P-521)
   132  - **Format**: PKCS#7/CMS (attached and detached)
   133  - **Library**: Smallstep PKCS#7
   134  - **Use Cases**: Modern PKI, TLS certificates, smaller signature sizes
   135  
   136  ```go
   137  // ECDSA signing examples
   138  ecdsaManager, err := keypair.Generate[algo.ECDSACurve, *algo.ECDSAKeyPair](algo.P256)
   139  signature, err := signing.SignData(data, ecdsaManager.KeyPair(), certificate)
   140  // Automatically uses PKCS#7 format with appropriate hash algorithm
   141  ```
   142  
   143  ### Ed25519 (Edwards-curve Digital Signature Algorithm)
   144  - **Key Size**: Fixed 256-bit keys
   145  - **Hash Algorithm**: SHA-512 (internal to Ed25519)
   146  - **Format**: Raw signatures (hybrid approach)
   147  - **Library**: Native Go crypto/ed25519
   148  - **Use Cases**: High performance, modern applications, SSH keys
   149  
   150  ```go
   151  // Ed25519 signing examples
   152  ed25519Manager, err := keypair.Generate[algo.Ed25519Config, *algo.Ed25519KeyPair](algo.Ed25519Config{})
   153  signature, err := signing.SignData(data, ed25519Manager.KeyPair(), certificate)
   154  // Automatically uses raw signature format for maximum performance
   155  ```
   156  
   157  ## Signature Formats
   158  
   159  ### Format Comparison Matrix
   160  
   161  | Algorithm | Format | Library | Standards | Certificate Embedding | Chain Support |
   162  |-----------|--------|---------|-----------|----------------------|---------------|
   163  | **RSA** | PKCS#7/CMS | Smallstep | ✅ RFC 2315/5652 | ✅ Yes | ✅ Yes |
   164  | **ECDSA** | PKCS#7/CMS | Smallstep | ✅ RFC 2315/5652 | ✅ Yes | ✅ Yes |
   165  | **Ed25519** | Raw | Native Go | ⚠️ RFC 8419 pending | ❌ No | ❌ No |
   166  
   167  ### PKCS#7/CMS Format (RSA & ECDSA)
   168  - **Standard**: RFC 2315 (PKCS#7) and RFC 5652 (CMS)
   169  - **Library**: Smallstep actively maintained fork
   170  - **Features**: Certificate embedding, chain support, metadata attributes
   171  - **Modes**: Attached (data included) and detached (data separate)
   172  
   173  ```go
   174  // Attached PKCS#7 (data included in signature)
   175  opts := signing.SignOptions{
   176      Format:             signing.FormatPKCS7,
   177      IncludeCertificate: true,
   178      Detached:           false,
   179  }
   180  
   181  // Detached PKCS#7 (data separate from signature)
   182  opts := signing.SignOptions{
   183      Format:             signing.FormatPKCS7Detached,
   184      IncludeCertificate: true,
   185      Detached:           true,
   186  }
   187  ```
   188  
   189  ### Raw Format (Ed25519)
   190  - **Reason**: RFC 8419 (Ed25519 in CMS) not implemented by available libraries
   191  - **Format**: Direct signature bytes (64 bytes)
   192  - **Performance**: Maximum speed with minimal overhead
   193  - **Verification**: Direct Ed25519 signature verification
   194  
   195  ```go
   196  // Ed25519 automatically uses raw format
   197  signature, err := signing.SignData(data, ed25519KeyPair, certificate)
   198  // signature.Format will be signing.FormatPKCS7Detached (for API consistency)
   199  // But signature.Data contains raw 64-byte Ed25519 signature
   200  ```
   201  
   202  ## Security & Best Practices
   203  
   204  ### Algorithm Selection Guidelines
   205  
   206  | Use Case | Recommended Algorithm | Reason |
   207  |----------|----------------------|--------|
   208  | **New Applications** | Ed25519 | Best performance and security |
   209  | **Enterprise PKI** | RSA 3072+ or ECDSA P-256+ | Standards compliance |
   210  | **Legacy Compatibility** | RSA 2048+ | Maximum compatibility |
   211  | **High Security** | ECDSA P-384+ or RSA 4096+ | Enhanced security |
   212  
   213  ### Hash Algorithm Selection
   214  The module automatically selects appropriate hash algorithms:
   215  
   216  ```go
   217  // Automatic hash selection based on algorithm and key size
   218  func GetHashAlgorithm(algo SignatureAlgorithm, keySize int) crypto.Hash {
   219      switch algo {
   220      case AlgorithmRSA:
   221          if keySize >= 3072 {
   222              return crypto.SHA384  // RSA 3072+ uses SHA-384
   223          }
   224          return crypto.SHA256      // RSA 2048 uses SHA-256
   225      case AlgorithmECDSA:
   226          if keySize >= 384 {
   227              return crypto.SHA384  // P-384+ uses SHA-384
   228          }
   229          return crypto.SHA256      // P-256 uses SHA-256
   230      case AlgorithmEd25519:
   231          return crypto.SHA512      // Ed25519 uses SHA-512 internally
   232      }
   233  }
   234  ```
   235  
   236  ### Verification Security
   237  ```go
   238  // Comprehensive verification options
   239  verifyOpts := signing.VerifyOptions{
   240      RequiredKeyUsage:    x509.KeyUsageDigitalSignature,
   241      RequiredExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageCodeSigning},
   242      VerifyChain:         true,
   243      Roots:              trustedRootCerts,
   244      Intermediates:      intermediateCerts,
   245      VerifyTime:         time.Now(),
   246  }
   247  ```
   248  
   249  ### Tamper Detection
   250  The module provides comprehensive tamper detection:
   251  - **Data Integrity**: Any modification to signed data is detected
   252  - **Signature Integrity**: Signature tampering is immediately detected
   253  - **Certificate Validation**: Wrong certificate usage is prevented
   254  - **Chain Validation**: Complete certificate chain verification
   255  
   256  ## Integration Examples
   257  
   258  ### Certificate Module Integration
   259  ```go
   260  // Generate key pair for signing
   261  keyManager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair](algo.KeySize2048)
   262  keyPair := keyManager.KeyPair()
   263  
   264  // Create signing certificate
   265  certificate, err := cert.CreateSelfSignedCertificate(keyPair, cert.CertificateRequest{
   266      Subject: pkix.Name{CommonName: "Document Signer"},
   267      ValidFor: 365 * 24 * time.Hour,
   268  })
   269  
   270  // Sign document
   271  signature, err := signing.SignData(document, keyPair, certificate)
   272  ```
   273  
   274  ### Multi-Party Signing Workflow
   275  ```go
   276  // Create multiple signers with different algorithms
   277  signers := []struct {
   278      name    string
   279      keyPair interface{}
   280      cert    *cert.Certificate
   281  }{
   282      {"Alice", rsaKeyPair, rsaCert},       // RSA with PKCS#7
   283      {"Bob", ecdsaKeyPair, ecdsaCert},     // ECDSA with PKCS#7
   284      {"Charlie", ed25519KeyPair, ed25519Cert}, // Ed25519 with raw
   285  }
   286  
   287  // Collect signatures from all parties
   288  var signatures []*signing.Signature
   289  for _, signer := range signers {
   290      sig, err := signing.SignData(document, signer.keyPair, signer.cert)
   291      signatures = append(signatures, sig)
   292  }
   293  
   294  // Verify all signatures
   295  for _, sig := range signatures {
   296      err := signing.VerifySignature(document, sig, signing.DefaultVerifyOptions())
   297      // Each signature verified using appropriate format automatically
   298  }
   299  ```
   300  
   301  ### Certificate Chain Signing
   302  ```go
   303  // Create CA certificate
   304  caKeyPair, _ := keypair.Generate[algo.KeySize, *algo.RSAKeyPair](algo.KeySize3072)
   305  caCert, err := cert.CreateCACertificate(caKeyPair, cert.CertificateRequest{
   306      Subject: pkix.Name{CommonName: "Example CA"},
   307      MaxPathLen: 1,
   308      ValidFor: 10 * 365 * 24 * time.Hour,
   309  })
   310  
   311  // Create signing certificate signed by CA
   312  signerKeyPair, _ := keypair.Generate[algo.KeySize, *algo.RSAKeyPair](algo.KeySize2048)
   313  signerCert, err := cert.SignCertificate(caCert, caKeyPair, cert.CertificateRequest{
   314      Subject: pkix.Name{CommonName: "Document Signer"},
   315      ValidFor: 2 * 365 * 24 * time.Hour,
   316  }, signerKeyPair.PublicKey)
   317  
   318  // Sign with certificate chain
   319  opts := signing.SignOptions{
   320      IncludeCertificate: true,
   321      IncludeChain:       true,
   322      ExtraCertificates:  []*x509.Certificate{caCert.Certificate},
   323  }
   324  signature, err := signing.SignDocument(document, signerKeyPair, signerCert, opts)
   325  
   326  // Verify with chain validation
   327  verifyOpts := signing.DefaultVerifyOptions()
   328  verifyOpts.VerifyChain = true
   329  verifyOpts.Roots = x509.NewCertPool()
   330  verifyOpts.Roots.AddCert(caCert.Certificate)
   331  err = signing.VerifySignature(document, signature, verifyOpts)
   332  ```
   333  
   334  ### Performance Testing Integration
   335  ```go
   336  // Algorithm performance comparison
   337  algorithms := []struct {
   338      name    string
   339      keyPair interface{}
   340      cert    *cert.Certificate
   341  }{
   342      {"RSA-2048", rsaKeyPair, rsaCert},
   343      {"ECDSA-P256", ecdsaKeyPair, ecdsaCert},
   344      {"Ed25519", ed25519KeyPair, ed25519Cert},
   345  }
   346  
   347  testData := make([]byte, 100*1024) // 100KB test document
   348  
   349  for _, alg := range algorithms {
   350      // Measure signing time
   351      startTime := time.Now()
   352      signature, err := signing.SignData(testData, alg.keyPair, alg.cert)
   353      signTime := time.Since(startTime)
   354  
   355      // Measure verification time
   356      startTime = time.Now()
   357      err = signing.VerifySignature(testData, signature, signing.DefaultVerifyOptions())
   358      verifyTime := time.Since(startTime)
   359  
   360      fmt.Printf("%-12s Sign: %-8v Verify: %-8v Size: %d bytes\n",
   361          alg.name, signTime, verifyTime, len(signature.Data))
   362  }
   363  ```
   364  
   365  ## Error Handling
   366  
   367  ### Common Error Patterns
   368  ```go
   369  // Signing with proper error handling
   370  signature, err := signing.SignData(data, keyPair, certificate)
   371  if err != nil {
   372      if errors.Is(err, signing.ErrMissingPrivateKey) {
   373          return fmt.Errorf("private key required: %w", err)
   374      }
   375      if errors.Is(err, signing.ErrMissingCertificate) {
   376          return fmt.Errorf("certificate required: %w", err)
   377      }
   378      return fmt.Errorf("signing failed: %w", err)
   379  }
   380  
   381  // Verification with error handling
   382  err = signing.VerifySignature(data, signature, opts)
   383  if err != nil {
   384      if errors.Is(err, signing.ErrVerificationFailed) {
   385          return fmt.Errorf("signature verification failed: %w", err)
   386      }
   387      if errors.Is(err, signing.ErrCertificateExpired) {
   388          return fmt.Errorf("certificate expired: %w", err)
   389      }
   390      return fmt.Errorf("verification error: %w", err)
   391  }
   392  ```
   393  
   394  ### Error Types
   395  - `signing.ErrInvalidSignature`: Malformed signature data
   396  - `signing.ErrMissingPrivateKey`: Private key not provided
   397  - `signing.ErrMissingCertificate`: Certificate not provided
   398  - `signing.ErrVerificationFailed`: Cryptographic verification failed
   399  - `signing.ErrCertificateExpired`: Certificate validity period expired
   400  - `signing.ErrCertificateNotYetValid`: Certificate not yet valid
   401  - `signing.ErrUnsupportedAlgorithm`: Unsupported signature algorithm
   402  - `signing.ErrUnsupportedFormat`: Unsupported signature format
   403  
   404  ## Performance Benchmarks
   405  
   406  ### Signing Performance (100KB document)
   407  ```
   408  Algorithm     Sign Time    Verify Time   Signature Size
   409  Ed25519       ~0.5ms      ~1.0ms        64 bytes
   410  ECDSA-P256    ~2.0ms      ~3.0ms        ~64 bytes + PKCS#7 overhead
   411  ECDSA-P384    ~3.0ms      ~4.0ms        ~96 bytes + PKCS#7 overhead
   412  RSA-2048      ~5.0ms      ~1.0ms        ~256 bytes + PKCS#7 overhead
   413  RSA-3072      ~12.0ms     ~2.0ms        ~384 bytes + PKCS#7 overhead
   414  RSA-4096      ~25.0ms     ~3.0ms        ~512 bytes + PKCS#7 overhead
   415  ```
   416  
   417  ### Key Performance Insights
   418  - **Ed25519**: Fastest overall performance with smallest signatures
   419  - **ECDSA**: Good balance of security, speed, and standards compliance
   420  - **RSA**: Maximum compatibility but slower performance
   421  - **PKCS#7 Overhead**: ~200-500 bytes additional metadata and structure
   422  
   423  ### Format Performance
   424  ```
   425  Operation              Time      Note
   426  PKCS#7 Creation       ~1ms      RSA/ECDSA format generation
   427  PKCS#7 Parsing        ~0.5ms    Signature format parsing
   428  Raw Ed25519 Sign      ~0.1ms    Direct signature generation
   429  Raw Ed25519 Verify    ~0.3ms    Direct signature verification
   430  Certificate Chain     +2ms      Additional chain validation time
   431  ```
   432  
   433  ---
   434  
   435  For complete working examples, see the `main.go` file in this directory.
   436  For integration with other modules, see the main project [README](../../README.md).