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

     1  // File cms.go implements Cryptographic Message Syntax (CMS) format support using
     2  // external Mozilla PKCS7 library for reliable and standards-compliant implementation.
     3  //
     4  // This replaces the previous complex manual ASN.1 implementation with a
     5  // battle-tested external library, reducing complexity and maintenance burden
     6  // while improving security and standards compliance.
     7  //
     8  // Standards compliance:
     9  //   - RFC 5652: Cryptographic Message Syntax (CMS)
    10  //   - PKCS#7: Cryptographic Message Syntax (legacy compatibility)
    11  //   - AES-256-GCM: Authenticated encryption
    12  //   - RSA-OAEP: Key transport mechanism
    13  //
    14  // Features:
    15  //   - Envelope encryption for multiple recipients
    16  //   - Certificate-based encryption and decryption
    17  //   - AES-256-GCM authenticated encryption (default)
    18  //   - Standards-compliant ASN.1 DER encoding
    19  //   - Simplified and maintainable codebase
    20  //
    21  // Security:
    22  //   - Authenticated encryption with AES-GCM
    23  //   - RSA-OAEP for secure key transport
    24  //   - Certificate validation during decryption
    25  //   - No manual ASN.1 parsing (reduces attack surface)
    26  //
    27  // Migration note:
    28  //
    29  //	The API signature for DecodeFromCMS has changed to require certificate
    30  //	and private key parameters for proper decryption. This is more secure
    31  //	and explicit than the previous implementation.
    32  package encryption
    33  
    34  import (
    35  	"crypto/x509"
    36  	"fmt"
    37  	"time"
    38  
    39  	"github.com/smallstep/pkcs7"
    40  )
    41  
    42  type CMS []byte
    43  
    44  // EncodeToCMS converts EncryptedData to CMS format using external library
    45  func EncodeToCMS(data *EncryptedData) (CMS, error) {
    46  	if data == nil {
    47  		return nil, fmt.Errorf("encrypted data is nil")
    48  	}
    49  
    50  	// For envelope encryption, we need recipient certificates
    51  	if len(data.Recipients) == 0 {
    52  		return nil, fmt.Errorf("no recipients available for CMS envelope encryption")
    53  	}
    54  
    55  	// Extract certificates from recipients
    56  	var recipients []*x509.Certificate
    57  	for _, recip := range data.Recipients {
    58  		if recip.Certificate != nil {
    59  			recipients = append(recipients, recip.Certificate)
    60  		}
    61  	}
    62  
    63  	if len(recipients) == 0 {
    64  		return nil, fmt.Errorf("no valid certificates found in recipients")
    65  	}
    66  
    67  	// Set encryption algorithm based on our algorithm
    68  	switch data.Algorithm {
    69  	case AlgorithmAESGCM:
    70  		pkcs7.ContentEncryptionAlgorithm = pkcs7.EncryptionAlgorithmAES256GCM
    71  	case AlgorithmRSAOAEP, AlgorithmECDH, AlgorithmX25519, AlgorithmEnvelope:
    72  		// Use AES-256-GCM as default for all asymmetric algorithms
    73  		pkcs7.ContentEncryptionAlgorithm = pkcs7.EncryptionAlgorithmAES256GCM
    74  	default:
    75  		pkcs7.ContentEncryptionAlgorithm = pkcs7.EncryptionAlgorithmAES256GCM
    76  	}
    77  
    78  	// Encrypt using external library
    79  	return pkcs7.Encrypt(data.Data, recipients)
    80  }
    81  
    82  // DecodeFromCMS parses CMS format into EncryptedData using external library
    83  //
    84  // Note: This function signature has changed from the original implementation.
    85  // It now requires a certificate and private key for proper decryption,
    86  // which is more secure and explicit.
    87  //
    88  // The function is generic and accepts any private key type:
    89  //   - *rsa.PrivateKey for RSA keys
    90  //   - *ecdsa.PrivateKey for ECDSA keys
    91  //   - ed25519.PrivateKey for Ed25519 keys
    92  //
    93  // Usage examples:
    94  //
    95  //	// Type inference (recommended)
    96  //	data, err := DecodeFromCMS(cmsBytes, cert, rsaPrivateKey)
    97  //
    98  //	// Explicit type parameter
    99  //	data, err := DecodeFromCMS[*rsa.PrivateKey](cmsBytes, cert, rsaPrivateKey)
   100  func DecodeFromCMS[T any](cmsData CMS, cert *x509.Certificate, privateKey T) (*EncryptedData, error) {
   101  	if len(cmsData) == 0 {
   102  		return nil, fmt.Errorf("CMS data is empty")
   103  	}
   104  
   105  	// Parse PKCS7 structure
   106  	p7, err := pkcs7.Parse(cmsData)
   107  	if err != nil {
   108  		return nil, fmt.Errorf("failed to parse PKCS7 structure: %w", err)
   109  	}
   110  
   111  	// Decrypt the content
   112  	decryptedData, err := p7.Decrypt(cert, privateKey)
   113  	if err != nil {
   114  		return nil, fmt.Errorf("failed to decrypt PKCS7 content: %w", err)
   115  	}
   116  
   117  	// Create EncryptedData structure
   118  	result := &EncryptedData{
   119  		Format:     FormatCMS,
   120  		Algorithm:  AlgorithmEnvelope, // Default to envelope encryption
   121  		Data:       decryptedData,
   122  		Recipients: make([]*RecipientInfo, 0),
   123  		Metadata:   make(map[string]any),
   124  		Timestamp:  time.Now(),
   125  	}
   126  
   127  	// Create a recipient info based on the provided certificate
   128  	// Since the PKCS7 struct doesn't expose internal recipient details,
   129  	// we create a basic recipient info with the certificate used for decryption
   130  	recipInfo := &RecipientInfo{
   131  		Certificate:            cert,
   132  		KeyEncryptionAlgorithm: AlgorithmRSAOAEP, // Default assumption
   133  	}
   134  	result.Recipients = append(result.Recipients, recipInfo)
   135  
   136  	return result, nil
   137  }
   138  
   139  // ValidateCMS validates CMS format data using external library
   140  func ValidateCMS(data CMS) error {
   141  	if len(data) == 0 {
   142  		return fmt.Errorf("CMS data is empty")
   143  	}
   144  
   145  	// Try to parse the data
   146  	_, err := pkcs7.Parse(data)
   147  	if err != nil {
   148  		return fmt.Errorf("invalid CMS format: %w", err)
   149  	}
   150  
   151  	return nil
   152  }