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

     1  // Package encryption provides comprehensive, type-safe data encryption and decryption functionality
     2  // that seamlessly integrates with the GoPKI keypair and certificate infrastructure.
     3  //
     4  // This package extends the GoPKI ecosystem by providing production-ready encryption capabilities
     5  // using the same type-safe design patterns. It supports multiple cryptographic algorithms,
     6  // various data sizes, and different output formats while maintaining compatibility with
     7  // existing PKI workflows.
     8  //
     9  // Key Features:
    10  //   - Type-safe encryption with Go generics integration
    11  //   - Multiple encryption algorithms with automatic selection
    12  //   - Support for both small and large data encryption
    13  //   - Certificate-based encryption workflows
    14  //   - Configurable output formats (Raw, PKCS#7, CMS)
    15  //   - Envelope encryption for large data sets
    16  //   - Comprehensive error handling and validation
    17  //
    18  // Supported Algorithms:
    19  //   - RSA-OAEP: Direct RSA encryption (recommended for keys ≥2048 bits)
    20  //   - ECDH + AES-GCM: ECDSA key agreement with symmetric encryption
    21  //   - X25519 + AES-GCM: Ed25519-based key agreement with symmetric encryption
    22  //   - AES-GCM: Direct symmetric encryption for envelope encryption
    23  //
    24  // Data Size Recommendations:
    25  //   - Small data (≤190 bytes for RSA-2048): Direct RSA-OAEP encryption
    26  //   - Medium data (≤8KB): ECDH/X25519 + AES-GCM
    27  //   - Large data (>8KB): Envelope encryption (recommended)
    28  //
    29  // Output Formats:
    30  //   - Raw: Binary format with magic bytes for format identification
    31  //   - PKCS#7: Standard ASN.1 DER-encoded format
    32  //   - CMS: Cryptographic Message Syntax format
    33  //
    34  // Security Considerations:
    35  //   - All encryption uses authenticated encryption (AES-GCM)
    36  //   - RSA-OAEP provides semantic security for RSA encryption
    37  //   - Key agreement protocols use ephemeral keys for forward secrecy
    38  //   - Random nonces and IVs are generated for each encryption operation
    39  //
    40  // Basic Usage Examples:
    41  //
    42  //	// Generate keys using existing GoPKI infrastructure
    43  //	rsaKeys, err := keypair.GenerateKeyPair[algo.KeySize, *algo.RSAKeyPair](2048)
    44  //	if err != nil {
    45  //		log.Fatal(err)
    46  //	}
    47  //
    48  //	// Simple data encryption
    49  //	data := []byte("sensitive information")
    50  //	encrypted, err := EncryptData(data, rsaKeys, DefaultEncryptOptions())
    51  //	if err != nil {
    52  //		log.Fatal(err)
    53  //	}
    54  //
    55  //	// Decrypt the data
    56  //	decrypted, err := DecryptData(encrypted, rsaKeys, DefaultDecryptOptions())
    57  //	if err != nil {
    58  //		log.Fatal(err)
    59  //	}
    60  //
    61  //	// Large file encryption using envelope encryption
    62  //	opts := DefaultEncryptOptions()
    63  //	opts.UseEnvelopeEncryption = true
    64  //	opts.Format = FormatRaw
    65  //
    66  //	largeData := make([]byte, 1024*1024) // 1MB data
    67  //	encrypted, err = EncryptData(largeData, rsaKeys, opts)
    68  //
    69  // Certificate-based Encryption:
    70  //
    71  //	// Load certificate from file
    72  //	cert, err := cert.LoadCertificateFromFile("recipient.pem")
    73  //	if err != nil {
    74  //		log.Fatal(err)
    75  //	}
    76  //
    77  //	// Encrypt for certificate recipient
    78  //	encrypted, err := EncryptForCertificate(data, cert, DefaultEncryptOptions())
    79  //	if err != nil {
    80  //		log.Fatal(err)
    81  //	}
    82  //
    83  // Advanced Usage with Custom Options:
    84  //
    85  //	// Create custom encryption options
    86  //	opts := EncryptOptions{
    87  //		Algorithm:             AlgorithmAuto,  // Auto-select based on key type
    88  //		UseEnvelopeEncryption: true,           // Use envelope encryption for large data
    89  //		Format:                FormatPKCS7,    // Use PKCS#7 output format
    90  //		KeyDerivationRounds:   100000,         // Custom KDF rounds
    91  //	}
    92  //
    93  //	// Encrypt with custom options
    94  //	encrypted, err := EncryptData(largeData, keyPair, opts)
    95  //
    96  // Integration with Other GoPKI Packages:
    97  //
    98  //	This package is designed to work seamlessly with:
    99  //	- keypair: For key generation and management
   100  //	- cert: For certificate-based encryption workflows
   101  //	- pkcs12: For importing/exporting encrypted key stores
   102  //	- signing: For combined sign-then-encrypt workflows
   103  package encryption
   104  
   105  import (
   106  	"crypto/x509"
   107  	"errors"
   108  	"time"
   109  
   110  	"github.com/jasoet/gopki/keypair"
   111  )
   112  
   113  // Algorithm EncryptionAlgorithm represents the algorithm used for encryption
   114  type Algorithm string
   115  
   116  const (
   117  	AlgorithmRSAOAEP  Algorithm = "RSA-OAEP"
   118  	AlgorithmECDH     Algorithm = "ECDH"
   119  	AlgorithmX25519   Algorithm = "X25519"
   120  	AlgorithmAESGCM   Algorithm = "AES-GCM"
   121  	AlgorithmEnvelope Algorithm = "Envelope"
   122  )
   123  
   124  // Format EncryptionFormat represents the format of encrypted data
   125  // Currently only CMS (RFC 5652) format is supported
   126  type Format string
   127  
   128  const (
   129  	FormatCMS Format = "cms" // RFC 5652 Cryptographic Message Syntax
   130  )
   131  
   132  // EncryptedData represents encrypted data with its metadata
   133  type EncryptedData struct {
   134  	// Algorithm used for encryption
   135  	Algorithm Algorithm
   136  	// Format of the encrypted data
   137  	Format Format
   138  	// The encrypted data bytes
   139  	Data []byte
   140  	// Encrypted symmetric key (for envelope encryption)
   141  	EncryptedKey []byte
   142  	// Initialization vector (for AES-GCM)
   143  	IV []byte
   144  	// Authentication tag (for AES-GCM)
   145  	Tag []byte
   146  	// Key derivation parameters (optional)
   147  	KDF *KDFParams
   148  	// Recipient information
   149  	Recipients []*RecipientInfo
   150  	// Timestamp when encrypted
   151  	Timestamp time.Time
   152  	// Additional metadata
   153  	Metadata map[string]any
   154  }
   155  
   156  // RecipientInfo contains information about an encryption recipient
   157  type RecipientInfo struct {
   158  	// Recipient's certificate (optional)
   159  	Certificate *x509.Certificate
   160  	// Key identifier
   161  	KeyID []byte
   162  	// Encrypted key for this recipient
   163  	EncryptedKey []byte
   164  	// Key encryption algorithm
   165  	KeyEncryptionAlgorithm Algorithm
   166  	// Additional fields for ECDSA/Ed25519 support
   167  	// Ephemeral public key (for ECDH/X25519)
   168  	EphemeralKey []byte
   169  	// IV for key encryption (for AES-GCM)
   170  	KeyIV []byte
   171  	// Authentication tag for key encryption (for AES-GCM)
   172  	KeyTag []byte
   173  }
   174  
   175  // KDFParams contains key derivation function parameters
   176  type KDFParams struct {
   177  	// Algorithm (PBKDF2, scrypt, etc.)
   178  	Algorithm string
   179  	// Salt
   180  	Salt []byte
   181  	// Iterations (for PBKDF2)
   182  	Iterations int
   183  	// Key length
   184  	KeyLength int
   185  	// Additional parameters
   186  	Params map[string]any
   187  }
   188  
   189  // EncryptOptions contains options for encryption operations
   190  type EncryptOptions struct {
   191  	// Encryption algorithm to use
   192  	Algorithm Algorithm
   193  	// Output format
   194  	Format Format
   195  	// Include recipient certificate
   196  	IncludeCertificate bool
   197  	// Additional certificate recipients for multi-recipient encryption
   198  	CertificateRecipients []*x509.Certificate
   199  	// Key derivation function parameters
   200  	KDF *KDFParams
   201  	// Custom metadata
   202  	Metadata map[string]any
   203  }
   204  
   205  // DecryptOptions contains options for decryption operations
   206  type DecryptOptions struct {
   207  	// Expected algorithm (for validation)
   208  	ExpectedAlgorithm Algorithm
   209  	// Verify timestamp
   210  	VerifyTimestamp bool
   211  	// Maximum age for encrypted data
   212  	MaxAge time.Duration
   213  	// Time to verify certificate validity (default: now)
   214  	VerifyTime time.Time
   215  	// Skip expiration check
   216  	SkipExpirationCheck bool
   217  	// Additional validation options
   218  	ValidationOptions map[string]any
   219  }
   220  
   221  // Encryptor provides type-safe encryption operations
   222  type Encryptor[K keypair.KeyPair] interface {
   223  	Encrypt(data []byte, keyPair K, opts EncryptOptions) (*EncryptedData, error)
   224  	SupportedAlgorithms() []Algorithm
   225  }
   226  
   227  // PublicKeyEncryptor provides type-safe public key encryption
   228  type PublicKeyEncryptor[P keypair.PublicKey] interface {
   229  	EncryptForPublicKey(data []byte, publicKey P, opts EncryptOptions) (*EncryptedData, error)
   230  	SupportedAlgorithms() []Algorithm
   231  }
   232  
   233  // Decryptor provides type-safe decryption operations
   234  type Decryptor[K keypair.KeyPair] interface {
   235  	Decrypt(encrypted *EncryptedData, keyPair K, opts DecryptOptions) ([]byte, error)
   236  	SupportedAlgorithms() []Algorithm
   237  }
   238  
   239  // PrivateKeyDecryptor provides type-safe private key decryption
   240  type PrivateKeyDecryptor[P keypair.PrivateKey] interface {
   241  	DecryptWithPrivateKey(encrypted *EncryptedData, privateKey P, opts DecryptOptions) ([]byte, error)
   242  	SupportedAlgorithms() []Algorithm
   243  }
   244  
   245  // CertificateEncryptor provides type-safe certificate-based encryption
   246  type CertificateEncryptor interface {
   247  	EncryptWithCertificate(data []byte, certificate *x509.Certificate, opts EncryptOptions) (*EncryptedData, error)
   248  	SupportedAlgorithms() []Algorithm
   249  }
   250  
   251  // MultiRecipientEncryptor provides type-safe multi-recipient encryption for certificates
   252  type MultiRecipientEncryptor interface {
   253  	EncryptForCertificates(data []byte, certificates []*x509.Certificate, opts EncryptOptions) (*EncryptedData, error)
   254  	AddCertificateRecipient(encrypted *EncryptedData, certificate *x509.Certificate) error
   255  }
   256  
   257  // Common error types
   258  var (
   259  	ErrUnsupportedAlgorithm = errors.New("unsupported encryption algorithm")
   260  	ErrUnsupportedFormat    = errors.New("unsupported encryption format")
   261  	ErrInvalidKey           = errors.New("invalid encryption key")
   262  	ErrDecryptionFailed     = errors.New("decryption failed")
   263  	ErrDataTooLarge         = errors.New("data too large for encryption method")
   264  	ErrInvalidRecipient     = errors.New("invalid recipient information")
   265  	ErrExpiredData          = errors.New("encrypted data has expired")
   266  	ErrInvalidFormat        = errors.New("invalid encrypted data format")
   267  	ErrInvalidParameters    = errors.New("invalid encryption parameters")
   268  )
   269  
   270  // DefaultEncryptOptions returns default encryption options
   271  func DefaultEncryptOptions() EncryptOptions {
   272  	return EncryptOptions{
   273  		Algorithm:             AlgorithmEnvelope,
   274  		Format:                FormatCMS, // CMS is the only supported format
   275  		IncludeCertificate:    false,
   276  		CertificateRecipients: nil,
   277  		KDF:                   nil,
   278  		Metadata:              make(map[string]any),
   279  	}
   280  }
   281  
   282  // DefaultDecryptOptions returns default decryption options
   283  func DefaultDecryptOptions() DecryptOptions {
   284  	return DecryptOptions{
   285  		ExpectedAlgorithm:   "",
   286  		VerifyTimestamp:     false,
   287  		MaxAge:              24 * time.Hour,
   288  		VerifyTime:          time.Time{}, // Zero time means use current time
   289  		SkipExpirationCheck: false,
   290  		ValidationOptions:   make(map[string]any),
   291  	}
   292  }
   293  
   294  // GetAlgorithmForKeyType determines the appropriate encryption algorithm for a key type
   295  func GetAlgorithmForKeyType(keyType string) Algorithm {
   296  	switch keyType {
   297  	case "RSA":
   298  		return AlgorithmRSAOAEP
   299  	case "ECDSA":
   300  		return AlgorithmECDH
   301  	case "Ed25519":
   302  		return AlgorithmX25519
   303  	default:
   304  		return AlgorithmEnvelope
   305  	}
   306  }
   307  
   308  // ValidateEncryptOptions validates encryption options
   309  func ValidateEncryptOptions(opts EncryptOptions) error {
   310  	switch opts.Algorithm {
   311  	case AlgorithmRSAOAEP, AlgorithmECDH, AlgorithmX25519, AlgorithmAESGCM, AlgorithmEnvelope:
   312  		// Valid algorithms
   313  	default:
   314  		return ErrUnsupportedAlgorithm
   315  	}
   316  
   317  	switch opts.Format {
   318  	case FormatCMS:
   319  		// Valid format - only CMS is supported
   320  	default:
   321  		return ErrUnsupportedFormat
   322  	}
   323  
   324  	return nil
   325  }
   326  
   327  // ValidateDecryptOptions validates decryption options
   328  func ValidateDecryptOptions(opts DecryptOptions) error {
   329  	if opts.MaxAge < 0 {
   330  		return ErrInvalidParameters
   331  	}
   332  	return nil
   333  }
   334  
   335  // EncodeData encodes EncryptedData to CMS format bytes
   336  // Since CMS is the only supported format, this is a convenience function
   337  func EncodeData(data *EncryptedData) ([]byte, error) {
   338  	if data == nil {
   339  		return nil, errors.New("encrypted data is nil")
   340  	}
   341  	return EncodeToCMS(data)
   342  }
   343  
   344  // DecodeDataWithKey decodes CMS format bytes back to EncryptedData using certificate and private key
   345  // This is the secure way to decode CMS data that requires explicit decryption credentials.
   346  //
   347  // T represents the private key type (*rsa.PrivateKey, *ecdsa.PrivateKey, or ed25519.PrivateKey)
   348  func DecodeDataWithKey[T keypair.PrivateKey](data []byte, cert *x509.Certificate, privateKey T) (*EncryptedData, error) {
   349  	if len(data) == 0 {
   350  		return nil, errors.New("data is empty")
   351  	}
   352  	return DecodeFromCMS(data, cert, privateKey)
   353  }
   354  
   355  // ValidateEncodedData validates that the data is in valid CMS format
   356  func ValidateEncodedData(data []byte) error {
   357  	return ValidateCMS(data)
   358  }