Documentation
ΒΆ
Overview ΒΆ
File cms.go implements Cryptographic Message Syntax (CMS) format support using external Mozilla PKCS7 library for reliable and standards-compliant implementation.
This replaces the previous complex manual ASN.1 implementation with a battle-tested external library, reducing complexity and maintenance burden while improving security and standards compliance.
Standards compliance:
- RFC 5652: Cryptographic Message Syntax (CMS)
- PKCS#7: Cryptographic Message Syntax (legacy compatibility)
- AES-256-GCM: Authenticated encryption
- RSA-OAEP: Key transport mechanism
Features:
- Envelope encryption for multiple recipients
- Certificate-based encryption and decryption
- AES-256-GCM authenticated encryption (default)
- Standards-compliant ASN.1 DER encoding
- Simplified and maintainable codebase
Security:
- Authenticated encryption with AES-GCM
- RSA-OAEP for secure key transport
- Certificate validation during decryption
- No manual ASN.1 parsing (reduces attack surface)
Migration note:
The API signature for DecodeFromCMS has changed to require certificate and private key parameters for proper decryption. This is more secure and explicit than the previous implementation.
Package encryption provides comprehensive, type-safe data encryption and decryption functionality that seamlessly integrates with the GoPKI keypair and certificate infrastructure.
This package extends the GoPKI ecosystem by providing production-ready encryption capabilities using the same type-safe design patterns. It supports multiple cryptographic algorithms, various data sizes, and different output formats while maintaining compatibility with existing PKI workflows.
Key Features:
- Type-safe encryption with Go generics integration
- Multiple encryption algorithms with automatic selection
- Support for both small and large data encryption
- Certificate-based encryption workflows
- Configurable output formats (Raw, PKCS#7, CMS)
- Envelope encryption for large data sets
- Comprehensive error handling and validation
Supported Algorithms:
- RSA-OAEP: Direct RSA encryption (recommended for keys β₯2048 bits)
- ECDH + AES-GCM: ECDSA key agreement with symmetric encryption
- X25519 + AES-GCM: Ed25519-based key agreement with symmetric encryption
- AES-GCM: Direct symmetric encryption for envelope encryption
Data Size Recommendations:
- Small data (β€190 bytes for RSA-2048): Direct RSA-OAEP encryption
- Medium data (β€8KB): ECDH/X25519 + AES-GCM
- Large data (>8KB): Envelope encryption (recommended)
Output Formats:
- Raw: Binary format with magic bytes for format identification
- PKCS#7: Standard ASN.1 DER-encoded format
- CMS: Cryptographic Message Syntax format
Security Considerations:
- All encryption uses authenticated encryption (AES-GCM)
- RSA-OAEP provides semantic security for RSA encryption
- Key agreement protocols use ephemeral keys for forward secrecy
- Random nonces and IVs are generated for each encryption operation
Basic Usage Examples:
// Generate keys using existing GoPKI infrastructure
rsaKeys, err := keypair.GenerateKeyPair[algo.KeySize, *algo.RSAKeyPair](2048)
if err != nil {
log.Fatal(err)
}
// Simple data encryption
data := []byte("sensitive information")
encrypted, err := EncryptData(data, rsaKeys, DefaultEncryptOptions())
if err != nil {
log.Fatal(err)
}
// Decrypt the data
decrypted, err := DecryptData(encrypted, rsaKeys, DefaultDecryptOptions())
if err != nil {
log.Fatal(err)
}
// Large file encryption using envelope encryption
opts := DefaultEncryptOptions()
opts.UseEnvelopeEncryption = true
opts.Format = FormatRaw
largeData := make([]byte, 1024*1024) // 1MB data
encrypted, err = EncryptData(largeData, rsaKeys, opts)
Certificate-based Encryption:
// Load certificate from file
cert, err := cert.LoadCertificateFromFile("recipient.pem")
if err != nil {
log.Fatal(err)
}
// Encrypt for certificate recipient
encrypted, err := EncryptForCertificate(data, cert, DefaultEncryptOptions())
if err != nil {
log.Fatal(err)
}
Advanced Usage with Custom Options:
// Create custom encryption options
opts := EncryptOptions{
Algorithm: AlgorithmAuto, // Auto-select based on key type
UseEnvelopeEncryption: true, // Use envelope encryption for large data
Format: FormatPKCS7, // Use PKCS#7 output format
KeyDerivationRounds: 100000, // Custom KDF rounds
}
// Encrypt with custom options
encrypted, err := EncryptData(largeData, keyPair, opts)
Integration with Other GoPKI Packages:
This package is designed to work seamlessly with: - keypair: For key generation and management - cert: For certificate-based encryption workflows - pkcs12: For importing/exporting encrypted key stores - signing: For combined sign-then-encrypt workflows
Index ΒΆ
- Variables
- func EncodeData(data *EncryptedData) ([]byte, error)
- func ValidateCMS(data CMS) error
- func ValidateDecryptOptions(opts DecryptOptions) error
- func ValidateEncodedData(data []byte) error
- func ValidateEncryptOptions(opts EncryptOptions) error
- type Algorithm
- type CMS
- type CertificateEncryptor
- type DecryptOptions
- type Decryptor
- type EncryptOptions
- type EncryptedData
- type Encryptor
- type Format
- type KDFParams
- type MultiRecipientEncryptor
- type PrivateKeyDecryptor
- type PublicKeyEncryptor
- type RecipientInfo
Constants ΒΆ
This section is empty.
Variables ΒΆ
var ( ErrUnsupportedAlgorithm = errors.New("unsupported encryption algorithm") ErrUnsupportedFormat = errors.New("unsupported encryption format") ErrInvalidKey = errors.New("invalid encryption key") ErrDecryptionFailed = errors.New("decryption failed") ErrDataTooLarge = errors.New("data too large for encryption method") ErrInvalidRecipient = errors.New("invalid recipient information") ErrExpiredData = errors.New("encrypted data has expired") ErrInvalidFormat = errors.New("invalid encrypted data format") ErrInvalidParameters = errors.New("invalid encryption parameters") )
Common error types
Functions ΒΆ
func EncodeData ΒΆ
func EncodeData(data *EncryptedData) ([]byte, error)
EncodeData encodes EncryptedData to CMS format bytes Since CMS is the only supported format, this is a convenience function
func ValidateCMS ΒΆ
ValidateCMS validates CMS format data using external library
func ValidateDecryptOptions ΒΆ
func ValidateDecryptOptions(opts DecryptOptions) error
ValidateDecryptOptions validates decryption options
func ValidateEncodedData ΒΆ
ValidateEncodedData validates that the data is in valid CMS format
func ValidateEncryptOptions ΒΆ
func ValidateEncryptOptions(opts EncryptOptions) error
ValidateEncryptOptions validates encryption options
Types ΒΆ
type Algorithm ΒΆ
type Algorithm string
Algorithm EncryptionAlgorithm represents the algorithm used for encryption
const ( AlgorithmRSAOAEP Algorithm = "RSA-OAEP" AlgorithmECDH Algorithm = "ECDH" AlgorithmX25519 Algorithm = "X25519" AlgorithmAESGCM Algorithm = "AES-GCM" AlgorithmEnvelope Algorithm = "Envelope" )
AlgorithmRSAOAEP and related constants define supported encryption algorithms.
func GetAlgorithmForKeyType ΒΆ
GetAlgorithmForKeyType determines the appropriate encryption algorithm for a key type
type CMS ΒΆ
type CMS []byte
CMS represents CMS (Cryptographic Message Syntax) encoded data.
func EncodeToCMS ΒΆ
func EncodeToCMS(data *EncryptedData) (CMS, error)
EncodeToCMS converts EncryptedData to CMS format using external library
type CertificateEncryptor ΒΆ
type CertificateEncryptor interface {
EncryptWithCertificate(data []byte, certificate *x509.Certificate, opts EncryptOptions) (*EncryptedData, error)
SupportedAlgorithms() []Algorithm
}
CertificateEncryptor provides type-safe certificate-based encryption
type DecryptOptions ΒΆ
type DecryptOptions struct {
// Expected algorithm (for validation)
ExpectedAlgorithm Algorithm
// Verify timestamp
VerifyTimestamp bool
// Maximum age for encrypted data
MaxAge time.Duration
// Time to verify certificate validity (default: now)
VerifyTime time.Time
// Skip expiration check
SkipExpirationCheck bool
// Additional validation options
ValidationOptions map[string]any
// Try OpenSSL format first during decryption
// When true, attempts to decode as standard PKCS#7 EnvelopedData first
// Falls back to GoPKI format if that fails
// When false (default), auto-detects format based on structure
TryOpenSSLFormat bool
}
DecryptOptions contains options for decryption operations
func DefaultDecryptOptions ΒΆ
func DefaultDecryptOptions() DecryptOptions
DefaultDecryptOptions returns default decryption options
type Decryptor ΒΆ
type Decryptor[K keypair.KeyPair] interface { Decrypt(encrypted *EncryptedData, keyPair K, opts DecryptOptions) ([]byte, error) SupportedAlgorithms() []Algorithm }
Decryptor provides type-safe decryption operations
type EncryptOptions ΒΆ
type EncryptOptions struct {
// Encryption algorithm to use
Algorithm Algorithm
// Output format
Format Format
// Include recipient certificate
IncludeCertificate bool
// Additional certificate recipients for multi-recipient encryption
CertificateRecipients []*x509.Certificate
// Key derivation function parameters
KDF *KDFParams
// Custom metadata
Metadata map[string]any
// OpenSSL compatibility mode (RSA only)
// When true, uses standard PKCS#7 EnvelopedData format compatible with OpenSSL
// When false (default), uses GoPKI's custom format supporting RSA/ECDSA/Ed25519
// Note: Only works with RSA keys - ECDSA/Ed25519 will return error if this is true
OpenSSLCompatible bool
}
EncryptOptions contains options for encryption operations
func DefaultEncryptOptions ΒΆ
func DefaultEncryptOptions() EncryptOptions
DefaultEncryptOptions returns default encryption options
type EncryptedData ΒΆ
type EncryptedData struct {
// Algorithm used for encryption
Algorithm Algorithm
// Format of the encrypted data
Format Format
// The encrypted data bytes
Data []byte
// Encrypted symmetric key (for envelope encryption)
EncryptedKey []byte
// Initialization vector (for AES-GCM)
IV []byte
// Authentication tag (for AES-GCM)
Tag []byte
// Key derivation parameters (optional)
KDF *KDFParams
// Recipient information
Recipients []*RecipientInfo
// Timestamp when encrypted
Timestamp time.Time
// Additional metadata
Metadata map[string]any
}
EncryptedData represents encrypted data with its metadata
func DecodeDataWithKey ΒΆ
func DecodeDataWithKey[T keypair.PrivateKey](data []byte, cert *x509.Certificate, privateKey T) (*EncryptedData, error)
DecodeDataWithKey decodes CMS format bytes back to EncryptedData using certificate and private key This is the secure way to decode CMS data that requires explicit decryption credentials.
T represents the private key type (*rsa.PrivateKey, *ecdsa.PrivateKey, or ed25519.PrivateKey)
func DecodeFromCMS ΒΆ
func DecodeFromCMS[T any](cmsData CMS, cert *x509.Certificate, privateKey T) (*EncryptedData, error)
DecodeFromCMS parses CMS format into EncryptedData using external library
Note: This function signature has changed from the original implementation. It now requires a certificate and private key for proper decryption, which is more secure and explicit.
The function is generic and accepts any private key type:
- *rsa.PrivateKey for RSA keys
- *ecdsa.PrivateKey for ECDSA keys
- ed25519.PrivateKey for Ed25519 keys
This function auto-detects two formats:
- GoPKI format: JSON-wrapped envelope structure (supports RSA/ECDSA/Ed25519)
- OpenSSL format: Standard PKCS#7 EnvelopedData (RSA only)
Usage examples:
// Type inference (recommended) data, err := DecodeFromCMS(cmsBytes, cert, rsaPrivateKey) // Explicit type parameter data, err := DecodeFromCMS[*rsa.PrivateKey](cmsBytes, cert, rsaPrivateKey)
type Encryptor ΒΆ
type Encryptor[K keypair.KeyPair] interface { Encrypt(data []byte, keyPair K, opts EncryptOptions) (*EncryptedData, error) SupportedAlgorithms() []Algorithm }
Encryptor provides type-safe encryption operations
type Format ΒΆ
type Format string
Format EncryptionFormat represents the format of encrypted data Currently only CMS (RFC 5652) format is supported
type KDFParams ΒΆ
type KDFParams struct {
// Algorithm (PBKDF2, scrypt, etc.)
Algorithm string
// Salt
Salt []byte
// Iterations (for PBKDF2)
Iterations int
// Key length
KeyLength int
// Additional parameters
Params map[string]any
}
KDFParams contains key derivation function parameters
type MultiRecipientEncryptor ΒΆ
type MultiRecipientEncryptor interface {
EncryptForCertificates(data []byte, certificates []*x509.Certificate, opts EncryptOptions) (*EncryptedData, error)
AddCertificateRecipient(encrypted *EncryptedData, certificate *x509.Certificate) error
}
MultiRecipientEncryptor provides type-safe multi-recipient encryption for certificates
type PrivateKeyDecryptor ΒΆ
type PrivateKeyDecryptor[P keypair.PrivateKey] interface { DecryptWithPrivateKey(encrypted *EncryptedData, privateKey P, opts DecryptOptions) ([]byte, error) SupportedAlgorithms() []Algorithm }
PrivateKeyDecryptor provides type-safe private key decryption
type PublicKeyEncryptor ΒΆ
type PublicKeyEncryptor[P keypair.PublicKey] interface { EncryptForPublicKey(data []byte, publicKey P, opts EncryptOptions) (*EncryptedData, error) SupportedAlgorithms() []Algorithm }
PublicKeyEncryptor provides type-safe public key encryption
type RecipientInfo ΒΆ
type RecipientInfo struct {
// Recipient's certificate (optional)
Certificate *x509.Certificate
// Key identifier
KeyID []byte
// Encrypted key for this recipient
EncryptedKey []byte
// Key encryption algorithm
KeyEncryptionAlgorithm Algorithm
// Additional fields for ECDSA/Ed25519 support
// Ephemeral public key (for ECDH/X25519)
EphemeralKey []byte
// IV for key encryption (for AES-GCM)
KeyIV []byte
// Authentication tag for key encryption (for AES-GCM)
KeyTag []byte
}
RecipientInfo contains information about an encryption recipient
Directories
ΒΆ
| Path | Synopsis |
|---|---|
|
Package asymmetric provides asymmetric encryption operations using RSA, ECDSA, and Ed25519 algorithms.
|
Package asymmetric provides asymmetric encryption operations using RSA, ECDSA, and Ed25519 algorithms. |
|
Package certificate provides certificate-based encryption operations that integrate with the GoPKI certificate infrastructure for document-level encryption.
|
Package certificate provides certificate-based encryption operations that integrate with the GoPKI certificate infrastructure for document-level encryption. |
|
Package envelope implements hybrid envelope encryption for efficient encryption of large data sets using a combination of symmetric and asymmetric cryptography.
|
Package envelope implements hybrid envelope encryption for efficient encryption of large data sets using a combination of symmetric and asymmetric cryptography. |
|
Package symmetric provides AES-GCM symmetric encryption operations.
|
Package symmetric provides AES-GCM symmetric encryption operations. |