github.com/jasoet/gopki@v1.15.0/README.md (about)

     1  # GoPKI
     2  
     3  [![Go Version](https://img.shields.io/badge/Go-1.24.5+-blue.svg)](https://golang.org)
     4  [![Test Coverage](https://img.shields.io/badge/Coverage-80.3%25-green.svg)](https://github.com/jasoet/gopki)
     5  [![Go Report Card](https://goreportcard.com/badge/github.com/jasoet/gopki)](https://goreportcard.com/report/github.com/jasoet/gopki)
     6  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
     7  
     8  A **production-ready Go library for PKI (Public Key Infrastructure) operations** that emphasizes **type-safe cryptography through Go generics**. GoPKI provides comprehensive cryptographic functionality with 80.3% test coverage across 844+ tests and strict type safety throughout all APIs.
     9  
    10  ## ๐Ÿš€ Key Features
    11  
    12  - **๐Ÿ”’ Type-Safe Cryptography**: Go generics eliminate `any`/`interface{}` types in core APIs
    13  - **๐Ÿ›ก๏ธ Security-First Design**: Enforced minimum key sizes, secure file permissions, cryptographic best practices
    14  - **๐Ÿ“œ Standards Compliant**: Full support for X.509, PKCS#7/CMS, PKCS#12, SSH formats
    15  - **๐Ÿงช Production Ready**: 80.3% test coverage, comprehensive CI/CD pipeline, semantic versioning
    16  - **โšก High Performance**: Zero runtime overhead from generics, optimized algorithms
    17  - **๐Ÿ”ง Developer Friendly**: Comprehensive Taskfile, extensive examples, excellent documentation
    18  
    19  ## ๐Ÿ“ฆ Installation
    20  
    21  ```bash
    22  go get github.com/jasoet/gopki
    23  ```
    24  
    25  **Requirements**: Go 1.24.5 or later
    26  
    27  ## ๐Ÿ“‘ Table of Contents
    28  
    29  - [๐Ÿš€ Key Features](#-key-features)
    30  - [๐Ÿ“ฆ Installation](#-installation)
    31  - [๐Ÿ—๏ธ Architecture](#-architecture)
    32  - [๐Ÿš€ Quick Start](#-quick-start)
    33    - [Generate RSA Key Pairs](#generate-rsa-key-pairs)
    34    - [Create Self-Signed Certificate](#create-self-signed-certificate)
    35    - [Sign Documents](#sign-documents)
    36    - [Encrypt Data](#encrypt-data)
    37  - [๐Ÿ“š Comprehensive Examples](#-comprehensive-examples)
    38  - [๐Ÿ”ง Core Modules](#-core-modules)
    39    - [1. keypair/ - Foundation Module](#1-keypair---foundation-module)
    40    - [2. cert/ - X.509 Certificate Management](#2-cert---x509-certificate-management)
    41    - [3. signing/ - Digital Signatures](#3-signing---digital-signatures)
    42    - [4. encryption/ - Data Encryption](#4-encryption---data-encryption)
    43    - [5. pkcs12/ - PKCS#12 File Management](#5-pkcs12---pkcs12-file-management)
    44  - [๐Ÿ”ข Algorithm Feature Matrix](#-algorithm-feature-matrix)
    45  - [๐Ÿ”„ Format Support Matrix](#-format-support-matrix)
    46  - [๐Ÿ›ก๏ธ Security Features](#-security-features)
    47  - [๐Ÿงช Testing and Quality Assurance](#-testing-and-quality-assurance)
    48  - [๐Ÿ“– Standards Compliance](#-standards-compliance)
    49  - [๐Ÿ”— Dependencies](#-dependencies)
    50  - [๐Ÿ’ป Development](#-development)
    51  - [๐Ÿค Contributing](#-contributing)
    52  - [๐Ÿ“„ License](#-license)
    53  - [๐Ÿ™ Acknowledgments](#-acknowledgments)
    54  - [๐Ÿ“ž Support](#-support)
    55  - [๐Ÿ—‚๏ธ Project Structure](#-project-structure)
    56  - [๐Ÿš€ Production Usage](#-production-usage)
    57  
    58  ## ๐Ÿ—๏ธ Architecture
    59  
    60  GoPKI is structured as **five core modules** with strong type relationships:
    61  
    62  ```
    63  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
    64  โ”‚   keypair/      โ”‚โ—„โ”€โ”€โ”€โ”ค     cert/        โ”‚โ—„โ”€โ”€โ”€โ”ค   signing/      โ”‚
    65  โ”‚ Core Key Mgmt   โ”‚    โ”‚ X.509 Certs      โ”‚    โ”‚ Digital Sigs    โ”‚
    66  โ”‚ (75.3% coverage)โ”‚    โ”‚ (74.3% coverage) โ”‚    โ”‚ (79.8% coverage)โ”‚
    67  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
    68           โ–ฒ                        โ–ฒ                       โ–ฒ
    69           โ”‚                        โ”‚                       โ”‚
    70           โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
    71                    โ–ผ                โ–ผ
    72           โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
    73           โ”‚  encryption/    โ”‚    โ”‚    pkcs12/       โ”‚
    74           โ”‚ Data Encryption โ”‚    โ”‚ PKCS#12 Files    โ”‚
    75           โ”‚ (89.1% coverage)โ”‚    โ”‚ (79.1% coverage) โ”‚
    76           โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
    77  ```
    78  
    79  ## ๐Ÿš€ Quick Start
    80  
    81  ### Generate RSA Key Pairs
    82  
    83  ```go
    84  package main
    85  
    86  import (
    87      "crypto/rsa"
    88      "fmt"
    89      "github.com/jasoet/gopki/keypair"
    90      "github.com/jasoet/gopki/keypair/algo"
    91  )
    92  
    93  func main() {
    94      // Method 1: Direct key generation
    95      keyPair, err := algo.GenerateRSAKeyPair(algo.KeySize2048)
    96      if err != nil {
    97          panic(err)
    98      }
    99      fmt.Printf("Generated %d-bit RSA key pair\n", keyPair.PrivateKey.Size()*8)
   100  
   101      // Method 2: Using KeyPair Manager (Recommended)
   102      manager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048)
   103      if err != nil {
   104          panic(err)
   105      }
   106  
   107      // Extract keys with type safety
   108      privateKey := manager.PrivateKey()
   109      publicKey := manager.PublicKey()
   110  
   111      // Convert to PEM format
   112      privatePEM, publicPEM, err := manager.ToPEM()
   113      if err != nil {
   114          panic(err)
   115      }
   116  
   117      // Save to files with secure permissions
   118      err = manager.SaveToPEM("private.pem", "public.pem")
   119      if err != nil {
   120          panic(err)
   121      }
   122  
   123      fmt.Printf("Generated and saved %d-bit RSA key pair\n", privateKey.Size()*8)
   124  }
   125  ```
   126  
   127  ### Create Self-Signed Certificate
   128  
   129  ```go
   130  package main
   131  
   132  import (
   133      "crypto/x509/pkix"
   134      "fmt"
   135      "time"
   136  
   137      "github.com/jasoet/gopki/cert"
   138      "github.com/jasoet/gopki/keypair/algo"
   139  )
   140  
   141  func main() {
   142      // Generate key pair
   143      keyPair, _ := algo.GenerateRSAKeyPair(algo.KeySize2048)
   144  
   145      // Create certificate
   146      certificate, err := cert.CreateSelfSignedCertificate(keyPair, cert.CertificateRequest{
   147          Subject: pkix.Name{
   148              CommonName:   "example.com",
   149              Organization: []string{"My Organization"},
   150              Country:      []string{"US"},
   151          },
   152          DNSNames: []string{"example.com", "www.example.com"},
   153          ValidFor: 365 * 24 * time.Hour, // 1 year
   154      })
   155  
   156      if err != nil {
   157          panic(err)
   158      }
   159  
   160      fmt.Printf("Created certificate for: %s\n", certificate.Certificate.Subject.CommonName)
   161  }
   162  ```
   163  
   164  ### Sign Documents
   165  
   166  ```go
   167  package main
   168  
   169  import (
   170      "fmt"
   171  
   172      "github.com/jasoet/gopki/signing"
   173      "github.com/jasoet/gopki/keypair/algo"
   174      "github.com/jasoet/gopki/cert"
   175  )
   176  
   177  func main() {
   178      // Setup key pair and certificate
   179      keyPair, _ := algo.GenerateRSAKeyPair(algo.KeySize2048)
   180      certificate, _ := cert.CreateSelfSignedCertificate(keyPair, cert.CertificateRequest{
   181          Subject: pkix.Name{CommonName: "Document Signer"},
   182          ValidFor: 365 * 24 * time.Hour,
   183      })
   184  
   185      // Sign document
   186      document := []byte("Important contract")
   187      signature, err := signing.SignDocument(document, keyPair, certificate)
   188      if err != nil {
   189          panic(err)
   190      }
   191  
   192      // Verify signature
   193      err = signing.VerifySignature(document, signature, signing.DefaultVerifyOptions())
   194      if err != nil {
   195          panic(err)
   196      }
   197  
   198      fmt.Println("Document signed and verified successfully!")
   199  }
   200  ```
   201  
   202  ### Encrypt Data
   203  
   204  ```go
   205  package main
   206  
   207  import (
   208      "fmt"
   209  
   210      "github.com/jasoet/gopki/encryption"
   211      "github.com/jasoet/gopki/keypair/algo"
   212      "github.com/jasoet/gopki/cert"
   213  )
   214  
   215  func main() {
   216      // Setup recipient
   217      keyPair, _ := algo.GenerateRSAKeyPair(algo.KeySize2048)
   218      certificate, _ := cert.CreateSelfSignedCertificate(keyPair, cert.CertificateRequest{
   219          Subject: pkix.Name{CommonName: "Recipient"},
   220          ValidFor: 365 * 24 * time.Hour,
   221      })
   222  
   223      // Encrypt data
   224      data := []byte("Secret message")
   225      encrypted, err := encryption.EncryptForCertificate(data, certificate.Certificate,
   226          encryption.DefaultEncryptOptions())
   227      if err != nil {
   228          panic(err)
   229      }
   230  
   231      // Decrypt data
   232      decrypted, err := encryption.DecryptWithKeyPair(encrypted, keyPair)
   233      if err != nil {
   234          panic(err)
   235      }
   236  
   237      fmt.Printf("Original: %s\n", data)
   238      fmt.Printf("Decrypted: %s\n", decrypted)
   239  }
   240  ```
   241  
   242  ## ๐Ÿ“š Comprehensive Examples
   243  
   244  GoPKI includes extensive examples demonstrating all features with complete source code, documentation, and test files:
   245  
   246  ### ๐Ÿ”ง Running Examples
   247  
   248  ```bash
   249  # Install Task runner (recommended)
   250  go install github.com/go-task/task/v3/cmd/task@latest
   251  
   252  # Run all examples
   253  task examples:run
   254  
   255  # Run specific examples
   256  task examples:keypair      # Key generation and format conversion
   257  task examples:certificates # CA hierarchies and certificate chains
   258  task examples:signing      # Document signing with multiple algorithms
   259  task examples:encryption   # Data encryption with various methods
   260  ```
   261  
   262  ### ๐Ÿ“‚ Example Files & Documentation
   263  
   264  | **Module** | **Source Code** | **Documentation** | **Key Test Files** |
   265  |------------|-----------------|-------------------|-------------------|
   266  | **Key Management** | [`examples/keypair/main.go`](examples/keypair/main.go) | [`examples/keypair/doc.md`](examples/keypair/doc.md) | [`keypair/algo/*_test.go`](keypair/algo/) |
   267  | **Certificates** | [`examples/certificates/main.go`](examples/certificates/main.go) | [`examples/certificates/doc.md`](examples/certificates/doc.md) | [`cert/cert_test.go`](cert/cert_test.go) |
   268  | **Digital Signing** | [`examples/signing/main.go`](examples/signing/main.go) | [`examples/signing/doc.md`](examples/signing/doc.md) | [`signing/signing_test.go`](signing/signing_test.go) |
   269  | **Data Encryption** | [`examples/encryption/main.go`](examples/encryption/main.go) | [`examples/encryption/doc.md`](examples/encryption/doc.md) | [`encryption/*/test.go`](encryption/) |
   270  | **PKCS#12 Bundles** | [`examples/pkcs12/main.go`](examples/pkcs12/main.go) | [`examples/pkcs12/doc.md`](examples/pkcs12/doc.md) | [`pkcs12/pkcs12_test.go`](pkcs12/pkcs12_test.go) |
   271  
   272  ### ๐ŸŽฏ Example Features by Module
   273  
   274  **๐Ÿ” Key Management Examples** ([`examples/keypair/`](examples/keypair/))
   275  - **KeyPair Manager**: Unified interface for all algorithms with type safety
   276  - RSA, ECDSA, Ed25519 key generation with compile-time type constraints
   277  - PEM/DER/SSH format conversions with automatic format detection
   278  - File operations with secure permissions (0600 for private keys, 0700 for directories)
   279  - Key validation, comparison, and metadata extraction
   280  - Loading existing keys from various formats into Manager
   281  - Cross-algorithm compatibility testing and benchmarking
   282  
   283  **๐Ÿ“œ Certificate Examples** ([`examples/certificates/`](examples/certificates/))
   284  - Self-signed certificate creation
   285  - CA certificate hierarchies with path length constraints
   286  - Intermediate CA signing workflows
   287  - Certificate chain verification
   288  - Subject Alternative Names (DNS, IP, Email)
   289  
   290  **โœ๏ธ Signing Examples** ([`examples/signing/`](examples/signing/))
   291  - Multi-algorithm document signing (RSA, ECDSA, Ed25519)
   292  - PKCS#7/CMS format support (attached/detached)
   293  - Certificate chain inclusion in signatures
   294  - Signature verification with certificate validation
   295  - Performance benchmarking across algorithms
   296  
   297  **๐Ÿ”’ Encryption Examples** ([`examples/encryption/`](examples/encryption/))
   298  - Multi-algorithm encryption (RSA-OAEP, ECDH+AES-GCM, X25519+AES-GCM)
   299  - Envelope encryption for large data sets
   300  - Multi-recipient encryption workflows
   301  - Certificate-based encryption with PKI integration
   302  - CMS format compliance (RFC 5652)
   303  - Performance analysis and file-based operations
   304  
   305  **๐Ÿ“ฆ PKCS#12 Bundle Examples** ([`examples/pkcs12/`](examples/pkcs12/))
   306  - **Multi-Algorithm P12 Creation**: RSA, ECDSA, Ed25519 certificate bundles
   307  - **Certificate Chain Bundling**: Complete CA hierarchies in P12 format
   308  - **Real-World Scenarios**: Web server, client auth, code signing certificates
   309  - **Security Options**: Password protection, custom iterations, friendly names
   310  - **Cross-Platform Migration**: Import/export workflows for different systems
   311  - **Integration Workflows**: Seamless integration with keypair Manager and cert modules
   312  - **Validation & Security**: Container validation and security best practices
   313  
   314  ## ๐Ÿ”ง Core Modules
   315  
   316  ### 1. **keypair/** - Foundation Module
   317  
   318  **Type-safe key generation and management with KeyPair Manager**
   319  
   320  ```go
   321  // Method 1: Direct algorithm usage
   322  rsaKeys, _ := algo.GenerateRSAKeyPair(algo.KeySize2048)       // RSA 2048/3072/4096-bit
   323  ecdsaKeys, _ := algo.GenerateECDSAKeyPair(algo.P256)         // ECDSA P-224/256/384/521
   324  ed25519Keys, _ := algo.GenerateEd25519KeyPair()              // Ed25519
   325  
   326  // Method 2: KeyPair Manager (Recommended) - provides unified interface
   327  import "crypto/rsa"
   328  import "crypto/ecdsa"
   329  import "crypto/ed25519"
   330  
   331  // Generate with Manager
   332  rsaManager, _ := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048)
   333  ecdsaManager, _ := keypair.Generate[algo.ECDSACurve, *algo.ECDSAKeyPair, *ecdsa.PrivateKey, *ecdsa.PublicKey](algo.P256)
   334  ed25519Manager, _ := keypair.Generate[algo.Ed25519Config, *algo.Ed25519KeyPair, ed25519.PrivateKey, ed25519.PublicKey]("")
   335  
   336  // Extract keys with type safety
   337  privateKey := rsaManager.PrivateKey()
   338  publicKey := rsaManager.PublicKey()
   339  
   340  // Unified format conversions with Manager
   341  privatePEM, publicPEM, _ := rsaManager.ToPEM()              // PEM format
   342  privateDER, publicDER, _ := rsaManager.ToDER()              // DER format
   343  privateSSH, publicSSH, _ := rsaManager.ToSSH("user@host", "") // SSH format
   344  
   345  // Unified file operations with secure permissions
   346  rsaManager.SaveToPEM("private.pem", "public.pem")           // Save PEM files
   347  rsaManager.SaveToDER("private.der", "public.der")           // Save DER files
   348  rsaManager.SaveToSSH("id_rsa", "id_rsa.pub", "user@host", "") // Save SSH files
   349  
   350  // Load existing keys into Manager
   351  loadedManager, _ := keypair.LoadFromPEM[*algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey]("private.pem")
   352  
   353  // Validation and key information
   354  info, _ := rsaManager.GetInfo()                             // Get algorithm metadata
   355  err := rsaManager.Validate()                               // Validate key pair integrity
   356  isValid := rsaManager.IsValid()                            // Check manager state
   357  ```
   358  
   359  **KeyPair Manager Benefits:**
   360  - โœ… **Unified Interface**: Same API across RSA, ECDSA, and Ed25519 algorithms
   361  - โœ… **Type Safety**: Generic constraints prevent runtime type errors
   362  - โœ… **Format Agnostic**: Automatic conversion between PEM/DER/SSH formats
   363  - โœ… **Secure File I/O**: Built-in secure permissions (0600/0700) and atomic operations
   364  - โœ… **Validation**: Comprehensive key pair integrity and security validation
   365  - โœ… **Metadata**: Algorithm detection and key information extraction
   366  - โœ… **Loading**: Support for loading existing keys from any format into Manager
   367  
   368  **Security Features:**
   369  - โœ… Enforced minimum RSA key sizes (โ‰ฅ2048 bits)
   370  - โœ… Secure file permissions (0600 for private keys, 0700 for directories)
   371  - โœ… Memory-safe key handling with zero runtime overhead
   372  - โœ… Format validation and compile-time type safety
   373  
   374  ### 2. **cert/** - X.509 Certificate Management
   375  
   376  **Certificate creation, CA operations, and chain management**
   377  
   378  ```go
   379  // Create CA certificate
   380  caCert, _ := cert.CreateCACertificate(caKeys, cert.CertificateRequest{
   381      Subject: pkix.Name{CommonName: "My Root CA"},
   382      ValidFor: 10 * 365 * 24 * time.Hour,
   383      IsCA: true,
   384      MaxPathLen: 2,  // Path length constraint
   385  })
   386  
   387  // Sign server certificate with CA
   388  serverCert, _ := cert.SignCertificate(caCert, caKeys, cert.CertificateRequest{
   389      Subject: pkix.Name{CommonName: "server.example.com"},
   390      DNSNames: []string{"server.example.com", "api.example.com"},
   391      IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1)},
   392      ValidFor: 365 * 24 * time.Hour,
   393  }, serverKeys.PublicKey)
   394  
   395  // Verify certificate chain
   396  err := cert.VerifyCertificate(serverCert, caCert)
   397  ```
   398  
   399  **CA Features:**
   400  - โœ… Path length constraints for intermediate CAs
   401  - โœ… Subject Alternative Names (DNS, IP, Email)
   402  - โœ… Certificate chain verification
   403  - โœ… BasicConstraints and KeyUsage extensions
   404  
   405  ### 3. **signing/** - Digital Signatures
   406  
   407  **Document signing with multiple formats and algorithms**
   408  
   409  ```go
   410  // Advanced signing with options
   411  signature, _ := signing.SignData(document, keyPair, certificate, signing.SignOptions{
   412      HashAlgorithm:      crypto.SHA256,
   413      Format:             signing.FormatPKCS7Detached,
   414      IncludeCertificate: true,
   415      IncludeChain:       true,
   416      TimestampURL:       "http://timestamp.example.com",
   417  })
   418  
   419  // PKCS#7/CMS format support
   420  pkcs7Data, _ := signing.CreatePKCS7Signature(document, keyPair, certificate, true)
   421  info, _ := signing.VerifyPKCS7Signature(document, pkcs7Data)
   422  ```
   423  
   424  **Signature Formats:**
   425  - โœ… Raw signatures (smallest size)
   426  - โœ… PKCS#7 attached (signature + document)
   427  - โœ… PKCS#7 detached (signature only, recommended)
   428  - โœ… Certificate chain inclusion
   429  - โœ… RFC 3161 timestamp support
   430  
   431  ### 4. **encryption/** - Data Encryption
   432  
   433  **Type-safe encryption with multiple algorithms and CMS support**
   434  
   435  ```go
   436  // Multiple encryption algorithms
   437  rsaEncrypted, _ := encryption.EncryptRSA(smallData, publicKey)           // RSA-OAEP (โ‰ค190 bytes)
   438  ecdhEncrypted, _ := encryption.EncryptECDH(largeData, ecdsaPublicKey)   // ECDH + AES-GCM
   439  x25519Encrypted, _ := encryption.EncryptX25519(largeData, ed25519Key)   // X25519 + AES-GCM
   440  
   441  // Envelope encryption for large data/multiple recipients
   442  envelope, _ := encryption.CreateEnvelope(largeData, []*x509.Certificate{cert1, cert2, cert3})
   443  cmsData, _ := encryption.EncodeToCMS(envelope)  // Standards-compliant CMS format
   444  
   445  // Type-safe decryption
   446  decrypted, _ := encryption.DecodeFromCMS(cmsData, recipientCert, privateKey)
   447  ```
   448  
   449  **Encryption Features:**
   450  - โœ… Multiple algorithms (RSA-OAEP, ECDH+AES-GCM, X25519+AES-GCM)
   451  - โœ… Envelope encryption for large data
   452  - โœ… Multi-recipient support
   453  - โœ… CMS (RFC 5652) format compliance
   454  - โœ… Type-safe APIs with generic constraints
   455  
   456  ## ๐Ÿ”ข Algorithm Feature Matrix
   457  
   458  | **Encryption Operation** | **RSA** | **ECDSA** | **Ed25519** | **Notes** |
   459  |---------------------------|---------|-----------|-------------|-----------|
   460  | **Direct Data Encryption** | โœ… | โœ… | โœ… | All algorithms supported for key-pair encryption |
   461  | **Public Key Only Encryption** | โœ… | โœ… | โŒ | Ed25519 requires full key pair due to key derivation limitations |
   462  | **Certificate-Based Encryption** | โœ… | โœ… | โŒ | Ed25519 limited by public-key-only requirement |
   463  | **Envelope Large Data** | โœ… | โœ… | โœ…* | Ed25519 works with key pairs, not with certificates |
   464  | **CMS Format Support** | โœ… | โœ… | โœ…* | Ed25519 limited to key-pair workflows |
   465  
   466  **Legend:**
   467  - โœ… **Full Support**: Complete implementation with all features
   468  - โŒ **Not Supported**: Technical limitations prevent implementation
   469  - โœ…* **Partial Support**: Works with restrictions (see notes)
   470  
   471  **Ed25519 Limitations:**
   472  - **Root Cause**: Key derivation incompatibility between Ed25519โ†’X25519 public key conversion (RFC 7748) and Ed25519โ†’X25519 private key conversion (Go standard method)
   473  - **Impact**: Public-key-only encryption fails, requiring full key pair for encryption operations
   474  - **Workaround**: Use `EncryptWithEd25519()` with complete key pairs instead of certificate-based encryption
   475  - **Certificate Encryption**: Not supported - returns clear error with guidance to use RSA or ECDSA for certificate-based workflows
   476  
   477  **Algorithm Recommendations:**
   478  - **RSA**: Best for certificate-based encryption, maximum compatibility
   479  - **ECDSA**: Modern choice with smaller keys and full feature support
   480  - **Ed25519**: High performance signing, limited to key-pair encryption workflows
   481  
   482  ### 5. **pkcs12/** - PKCS#12 File Management
   483  
   484  **Complete PKI material bundling and storage with RFC 7292 compliance**
   485  
   486  ```go
   487  // Method 1: Quick P12 creation for simple use cases
   488  err := pkcs12.QuickCreateP12("basic.p12", "password123", privateKey, certificate)
   489  
   490  // Method 2: Advanced P12 creation with full control
   491  opts := pkcs12.CreateOptions{
   492      Password:     "secure_password_2024",
   493      FriendlyName: "Production Web Server Certificate",
   494      Iterations:   8192, // High security iterations
   495  }
   496  err := pkcs12.CreateP12File("webserver.p12", serverKey, serverCert,
   497      []*x509.Certificate{intermediateCert, rootCert}, opts)
   498  
   499  // Integration with KeyPair Manager
   500  manager, _ := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048)
   501  err := pkcs12.QuickCreateP12("from_manager.p12", "password", manager.PrivateKey(), certificate)
   502  
   503  // Loading and validation
   504  container, _ := pkcs12.LoadFromP12File("certificate.p12", pkcs12.LoadOptions{
   505      Password: "secure123",
   506      TrustedCerts: []*x509.Certificate{rootCert},
   507  })
   508  
   509  // Container operations
   510  keyType := container.GetKeyType()                    // "RSA", "ECDSA", "Ed25519"
   511  chain := container.ExtractCertificateChain()        // Get full certificate chain
   512  err := container.Validate()                         // Validate container integrity
   513  
   514  // Quick loading for simple cases
   515  container, _ := pkcs12.QuickLoadP12("certificate.p12", "secure123")
   516  
   517  // Real-world scenarios
   518  // Web server certificate bundle
   519  pkcs12.CreateP12File("webserver.p12", serverKey, serverCert, caChain, webServerOpts)
   520  
   521  // Client authentication certificate
   522  pkcs12.QuickCreateP12("client_auth.p12", "client_password", clientKey, clientCert)
   523  
   524  // Code signing certificate with maximum security
   525  pkcs12.CreateP12File("codesign.p12", codeSignKey, codeSignCert, nil,
   526      pkcs12.CreateOptions{
   527          Password: "code_sign_password",
   528          FriendlyName: "Software Publisher Certificate",
   529          Iterations: 16384, // Maximum security for code signing
   530      })
   531  ```
   532  
   533  **PKCS#12 Features:**
   534  - โœ… **Multi-Algorithm Support**: RSA, ECDSA, Ed25519 private keys
   535  - โœ… **Certificate Chains**: Bundle complete CA hierarchies
   536  - โœ… **Password Protection**: Configurable iteration counts for security
   537  - โœ… **Cross-Platform**: Compatible with Windows, macOS, Linux
   538  - โœ… **Integration**: Seamless with keypair Manager and cert modules
   539  - โœ… **Validation**: Container integrity and certificate verification
   540  - โœ… **Real-World Ready**: Web server, client auth, code signing use cases
   541  
   542  **Security Levels:**
   543  - **Development**: 2048 iterations
   544  - **Production**: 4096-8192 iterations
   545  - **High Security**: 16384+ iterations for sensitive applications
   546  
   547  ## ๐Ÿ”„ Format Support Matrix
   548  
   549  | Format | RSA | ECDSA | Ed25519 | Usage |
   550  |--------|-----|-------|---------|-------|
   551  | **PEM** | โœ… | โœ… | โœ… | Text-based, Base64 encoded, most common |
   552  | **DER** | โœ… | โœ… | โœ… | Binary format, ~30% smaller than PEM |
   553  | **SSH** | โœ… | โœ… | โœ… | OpenSSH format for authorized_keys |
   554  | **PKCS#12** | โœ… | โœ… | โœ… | Password-protected container format |
   555  
   556  ## ๐Ÿ›ก๏ธ Security Features
   557  
   558  ### Cryptographic Security
   559  - **Strong Random Sources**: Uses `crypto/rand.Reader` exclusively
   560  - **Minimum Key Sizes**: RSA โ‰ฅ2048 bits enforced at compile time
   561  - **Secure Algorithms**: Only NIST curves and Ed25519 supported
   562  - **Authenticated Encryption**: AES-GCM prevents tampering
   563  - **Timing Attack Resistance**: Ed25519 and constant-time implementations
   564  
   565  ### File System Security
   566  - **Secure Permissions**: Private keys saved with 0600 permissions
   567  - **Directory Security**: Created with 0700 permissions (owner-only access)
   568  - **Atomic Operations**: Prevent partial writes and race conditions
   569  - **Secure Cleanup**: Temporary files properly removed
   570  
   571  ### Memory Security
   572  - **Type Safety**: Generic constraints prevent runtime type errors
   573  - **No Raw Material Exposure**: Cryptographic keys wrapped in safe types
   574  - **Defensive Copying**: Sensitive parameters copied defensively
   575  - **Validated Parameters**: All inputs validated before cryptographic operations
   576  
   577  ## ๐Ÿงช Testing and Quality Assurance
   578  
   579  ### Test Coverage Statistics
   580  - **Overall Coverage**: 80.3%
   581  - **Total Tests**: 844+ individual tests across 23 test files
   582  - **Test Categories**: Unit, Integration, Security, Benchmark, Edge Case
   583  
   584  **Module Coverage:**
   585  ```
   586  encryption/          89.1% (highest - most complex module)
   587  keypair/algo/        87.8% (algorithm implementations)
   588  signing/             79.8% (core signing)
   589  pkcs12/              79.1% (PKCS#12 operations)
   590  cert/                74.3% (certificate operations)
   591  keypair/             75.3% (manager and utilities)
   592  ```
   593  
   594  ### Quality Assurance Tools
   595  ```bash
   596  # Run comprehensive test suite
   597  task test              # Full test suite with race detection
   598  task test:coverage     # Generate HTML coverage report
   599  
   600  # Code quality checks
   601  task lint:full         # Comprehensive linting with golangci-lint
   602  task lint:security     # Security-focused linting (gosec)
   603  task format:check      # Verify code formatting
   604  
   605  # Security scanning
   606  task security:check    # Dependency vulnerability scanning
   607  ```
   608  
   609  ### ๐Ÿ“‹ Core Test Files
   610  
   611  | **Module** | **Test Coverage** | **Key Test Files** | **Purpose** |
   612  |------------|-------------------|-------------------|-------------|
   613  | **keypair/** | 75.3% | [`keypair/algo/rsa_test.go`](keypair/algo/rsa_test.go)<br>[`keypair/algo/ecdsa_test.go`](keypair/algo/ecdsa_test.go)<br>[`keypair/algo/ed25519_test.go`](keypair/algo/ed25519_test.go) | Algorithm implementations, key generation, format conversion |
   614  | **cert/** | 74.3% | [`cert/cert_test.go`](cert/cert_test.go)<br>[`cert/ca_test.go`](cert/ca_test.go) | Certificate creation, CA operations, chain verification |
   615  | **signing/** | 79.8% | [`signing/signing_test.go`](signing/signing_test.go)<br>[`signing/formats/pkcs7_test.go`](signing/formats/pkcs7_test.go) | Document signing, PKCS#7/CMS formats, verification |
   616  | **encryption/** | 89.1% | [`encryption/asymmetric/asymmetric_test.go`](encryption/asymmetric/asymmetric_test.go)<br>[`encryption/envelope/envelope_test.go`](encryption/envelope/envelope_test.go)<br>[`encryption/certificate/certificate_test.go`](encryption/certificate/certificate_test.go) | Multi-algorithm encryption, envelope encryption, certificate-based workflows |
   617  | **pkcs12/** | 79.1% | [`pkcs12/pkcs12_test.go`](pkcs12/pkcs12_test.go) | PKCS#12 file operations, password protection, certificate bundling |
   618  
   619  ### ๐Ÿ“– Developer Documentation
   620  
   621  - **[`CLAUDE.md`](CLAUDE.md)** - Development commands, architecture overview, and coding patterns for Claude Code AI
   622  - **[`CHANGELOG.md`](CHANGELOG.md)** - Version history and release notes
   623  - **[`examples/*/doc.md`](examples/)** - Detailed documentation for each example module
   624  
   625  ## ๐Ÿ“– Standards Compliance
   626  
   627  GoPKI implements and adheres to industry standards:
   628  
   629  - **RFC 5652**: Cryptographic Message Syntax (CMS)
   630  - **RFC 3447**: PKCS #1: RSA Cryptography Specifications
   631  - **RFC 5208**: PKCS #8: Private-Key Information Syntax
   632  - **RFC 7748**: Elliptic Curves for Security (Ed25519, X25519)
   633  - **RFC 5280**: Internet X.509 Public Key Infrastructure Certificate
   634  - **PKCS #7**: Cryptographic Message Syntax Standard
   635  - **PKCS #12**: Personal Information Exchange Syntax Standard
   636  - **OpenSSH**: SSH public/private key formats
   637  
   638  ## ๐Ÿ”— Dependencies
   639  
   640  GoPKI uses minimal, carefully selected dependencies:
   641  
   642  - **go.mozilla.org/pkcs7** v0.9.0 - Battle-tested CMS/PKCS#7 implementation
   643  - **golang.org/x/crypto** v0.42.0 - Extended cryptographic primitives
   644  - **software.sslmate.com/src/go-pkcs12** v0.6.0 - Standards-compliant PKCS#12
   645  
   646  **Design Philosophy**: Minimal dependencies, security-focused, standards-compliant, battle-tested libraries.
   647  
   648  ## ๐Ÿ’ป Development
   649  
   650  ### Using Taskfile (Recommended)
   651  
   652  Install [Task](https://taskfile.dev/installation/) for streamlined development:
   653  
   654  ```bash
   655  # Setup
   656  task setup             # Initialize project and dependencies
   657  task                   # Show all available tasks
   658  
   659  # Development workflow
   660  task test              # Run tests with coverage (80.3%)
   661  task format            # Format code
   662  task lint:full         # Comprehensive linting
   663  task examples:run      # Run all examples
   664  
   665  # Building
   666  task build             # Build library
   667  task build:examples    # Build example binaries
   668  
   669  # Cleanup
   670  task clean             # Clean build artifacts
   671  task examples:clean    # Clean example outputs
   672  ```
   673  
   674  ### Manual Development
   675  
   676  ```bash
   677  # Core operations
   678  go test ./... -race -coverprofile=coverage.out
   679  go build ./...
   680  go fmt ./...
   681  go vet ./...
   682  
   683  # Examples (with build tags)
   684  go run -tags example ./examples/keypair/main.go
   685  go run -tags example ./examples/certificates/main.go
   686  go run -tags example ./examples/signing/main.go
   687  go run -tags example ./examples/encryption/main.go
   688  ```
   689  
   690  ## ๐Ÿค Contributing
   691  
   692  We welcome contributions! Please see our contributing guidelines:
   693  
   694  1. **Fork** the repository
   695  2. **Create** a feature branch (`git checkout -b feature/amazing-feature`)
   696  3. **Write** tests for new functionality
   697  4. **Ensure** all tests pass (`task test`)
   698  5. **Format** code (`task format`)
   699  6. **Lint** code (`task lint:full`)
   700  7. **Commit** changes (`git commit -m 'Add amazing feature'`)
   701  8. **Push** to branch (`git push origin feature/amazing-feature`)
   702  9. **Open** a Pull Request
   703  
   704  ### Development Guidelines
   705  
   706  - **Type Safety First**: Use generic constraints, avoid `any`/`interface{}`
   707  - **Security Focus**: Follow established security practices
   708  - **Test Coverage**: Maintain or improve 80.3% coverage
   709  - **Documentation**: Update examples and docs for API changes
   710  - **Standards Compliance**: Adhere to cryptographic standards
   711  
   712  ## ๐Ÿ“„ License
   713  
   714  This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
   715  
   716  ## ๐Ÿ™ Acknowledgments
   717  
   718  - **Mozilla** for the excellent PKCS#7 library
   719  - **Go Team** for outstanding cryptographic standard library
   720  - **Community** for feedback and contributions
   721  
   722  ## ๐Ÿ“ž Support
   723  
   724  - **Documentation**: Comprehensive examples and API docs included
   725  - **Issues**: [GitHub Issues](https://github.com/jasoet/gopki/issues)
   726  - **Questions**: Use GitHub Issues for questions and feature requests
   727  
   728  ## ๐Ÿ—‚๏ธ Project Structure
   729  
   730  ```
   731  gopki/
   732  โ”œโ”€โ”€ keypair/                    # Core key management (foundation) - 75.3% coverage
   733  โ”‚   โ”œโ”€โ”€ algo/                   # Algorithm implementations (RSA, ECDSA, Ed25519)
   734  โ”‚   โ”‚   โ”œโ”€โ”€ rsa.go             # RSA key operations
   735  โ”‚   โ”‚   โ”œโ”€โ”€ ecdsa.go           # ECDSA operations
   736  โ”‚   โ”‚   โ”œโ”€โ”€ ed25519.go         # Ed25519 operations
   737  โ”‚   โ”‚   โ”œโ”€โ”€ rsa_test.go        # RSA algorithm tests
   738  โ”‚   โ”‚   โ”œโ”€โ”€ ecdsa_test.go      # ECDSA algorithm tests
   739  โ”‚   โ”‚   โ””โ”€โ”€ ed25519_test.go    # Ed25519 algorithm tests
   740  โ”‚   โ””โ”€โ”€ format/                # Format definitions (PEM, DER, SSH)
   741  โ”œโ”€โ”€ cert/                      # X.509 certificate operations - 74.3% coverage
   742  โ”‚   โ”œโ”€โ”€ cert.go               # Certificate creation and management
   743  โ”‚   โ”œโ”€โ”€ ca.go                 # Certificate Authority operations
   744  โ”‚   โ”œโ”€โ”€ cert_test.go          # Certificate operation tests
   745  โ”‚   โ””โ”€โ”€ ca_test.go            # CA operation tests
   746  โ”œโ”€โ”€ signing/                   # Document signing and verification - 79.8% coverage
   747  โ”‚   โ”œโ”€โ”€ signing.go            # Core signing functionality
   748  โ”‚   โ”œโ”€โ”€ formats/              # PKCS#7/CMS format support
   749  โ”‚   โ”‚   โ””โ”€โ”€ pkcs7_test.go     # PKCS#7 format tests
   750  โ”‚   โ””โ”€โ”€ signing_test.go       # Document signing tests
   751  โ”œโ”€โ”€ encryption/                # Data encryption and decryption - 89.1% coverage
   752  โ”‚   โ”œโ”€โ”€ asymmetric/           # Asymmetric encryption algorithms
   753  โ”‚   โ”‚   โ”œโ”€โ”€ asymmetric.go     # Core asymmetric operations
   754  โ”‚   โ”‚   โ”œโ”€โ”€ rsa_test.go       # RSA encryption tests
   755  โ”‚   โ”‚   โ”œโ”€โ”€ ecdsa_test.go     # ECDSA encryption tests
   756  โ”‚   โ”‚   โ”œโ”€โ”€ ed25519_test.go   # Ed25519 encryption tests
   757  โ”‚   โ”‚   โ””โ”€โ”€ asymmetric_test.go # Integration tests
   758  โ”‚   โ”œโ”€โ”€ symmetric/            # Symmetric encryption (AES-GCM)
   759  โ”‚   โ”‚   โ””โ”€โ”€ symmetric_test.go # AES-GCM tests
   760  โ”‚   โ”œโ”€โ”€ envelope/             # Envelope encryption
   761  โ”‚   โ”‚   โ””โ”€โ”€ envelope_test.go  # Envelope encryption tests
   762  โ”‚   โ”œโ”€โ”€ certificate/          # Certificate-based encryption
   763  โ”‚   โ”‚   โ””โ”€โ”€ certificate_test.go # Certificate encryption tests
   764  โ”‚   โ”œโ”€โ”€ encryption_test.go    # Core encryption tests
   765  โ”‚   โ””โ”€โ”€ cms_test.go          # CMS format tests
   766  โ”œโ”€โ”€ pkcs12/                   # PKCS#12 file management - 79.1% coverage
   767  โ”‚   โ””โ”€โ”€ pkcs12_test.go       # PKCS#12 operation tests
   768  โ”œโ”€โ”€ examples/                 # Comprehensive usage examples with documentation
   769  โ”‚   โ”œโ”€โ”€ keypair/             # Key generation examples
   770  โ”‚   โ”‚   โ”œโ”€โ”€ main.go          # Key generation demonstration
   771  โ”‚   โ”‚   โ””โ”€โ”€ doc.md           # Key management documentation
   772  โ”‚   โ”œโ”€โ”€ certificates/        # Certificate creation examples
   773  โ”‚   โ”‚   โ”œโ”€โ”€ main.go          # Certificate creation demonstration
   774  โ”‚   โ”‚   โ””โ”€โ”€ doc.md           # Certificate management documentation
   775  โ”‚   โ”œโ”€โ”€ signing/             # Document signing examples
   776  โ”‚   โ”‚   โ”œโ”€โ”€ main.go          # Document signing demonstration
   777  โ”‚   โ”‚   โ””โ”€โ”€ doc.md           # Digital signing documentation
   778  โ”‚   โ”œโ”€โ”€ encryption/          # Data encryption examples
   779  โ”‚   โ”‚   โ”œโ”€โ”€ main.go          # Encryption demonstration
   780  โ”‚   โ”‚   โ””โ”€โ”€ doc.md           # Encryption documentation
   781  โ”‚   โ””โ”€โ”€ pkcs12/              # PKCS#12 bundle examples
   782  โ”‚       โ”œโ”€โ”€ main.go          # PKCS#12 demonstration
   783  โ”‚       โ”œโ”€โ”€ doc.md           # PKCS#12 documentation
   784  โ”‚       โ””โ”€โ”€ output/          # Generated P12 files (gitignored)
   785  โ”œโ”€โ”€ CLAUDE.md                # Development guide for Claude Code AI
   786  โ”œโ”€โ”€ CHANGELOG.md             # Version history and release notes
   787  โ””โ”€โ”€ README.md               # This comprehensive guide
   788  ```
   789  
   790  ### ๐Ÿ“Š Coverage Summary by Module
   791  - **encryption/**: 89.1% (highest - most complex cryptographic operations)
   792  - **signing/**: 79.8% (document signing and PKCS#7/CMS formats)
   793  - **pkcs12/**: 79.1% (PKCS#12 file operations and bundling)
   794  - **keypair/**: 75.3% (foundational key management operations)
   795  - **cert/**: 74.3% (X.509 certificate operations and CA workflows)
   796  - **Overall**: 79.9% across 844+ individual tests
   797  
   798  ## ๐Ÿš€ Production Usage
   799  
   800  GoPKI is production-ready with:
   801  
   802  - โœ… **80.3% Test Coverage** with 844+ tests
   803  - โœ… **Type-Safe APIs** with Go generics
   804  - โœ… **Security Best Practices** enforced throughout
   805  - โœ… **Standards Compliance** for interoperability
   806  - โœ… **Comprehensive Examples** for all use cases
   807  - โœ… **CI/CD Pipeline** with automated testing
   808  - โœ… **Semantic Versioning** for reliable releases
   809  - โœ… **Minimal Dependencies** for security and maintenance
   810  
   811  Perfect for applications requiring robust PKI operations, certificate management, document signing, and data encryption with strong type safety guarantees.
   812  
   813  ---
   814  
   815  **Made with โค๏ธ in Go | Type-Safe Cryptography for Production**