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

     1  // Package envelope implements hybrid envelope encryption for efficient encryption
     2  // of large data sets using a combination of symmetric and asymmetric cryptography.
     3  //
     4  // Envelope encryption (also known as hybrid encryption) is a cryptographic technique
     5  // that combines the speed of symmetric encryption with the key distribution benefits
     6  // of asymmetric encryption. It's the recommended approach for encrypting large amounts
     7  // of data or when you need to encrypt for multiple recipients.
     8  //
     9  // How envelope encryption works:
    10  //  1. Generate a random symmetric encryption key (Data Encryption Key - DEK)
    11  //  2. Encrypt the actual data with the DEK using AES-GCM
    12  //  3. Encrypt the DEK with the recipient's public key (Key Encryption Key - KEK)
    13  //  4. Return both the encrypted data and the encrypted DEK
    14  //
    15  // Advantages:
    16  //   - Efficient for large data (no size limitations)
    17  //   - Can encrypt for multiple recipients by encrypting DEK with each recipient's key
    18  //   - Provides perfect forward secrecy when using ephemeral keys
    19  //   - Scales well with data size (only DEK encryption time scales with recipients)
    20  //
    21  // Security properties:
    22  //   - Data confidentiality through AES-GCM symmetric encryption
    23  //   - Key confidentiality through asymmetric encryption of the DEK
    24  //   - Data integrity and authenticity through AES-GCM authentication
    25  //   - Fresh DEK for each encryption operation
    26  //
    27  // Use cases:
    28  //   - Encrypting files larger than RSA key size limits
    29  //   - Multi-recipient encryption scenarios
    30  //   - Cloud storage encryption
    31  //   - Secure messaging systems
    32  //   - Database field encryption
    33  package envelope
    34  
    35  import (
    36  	"crypto/ecdsa"
    37  	"crypto/ed25519"
    38  	"crypto/rsa"
    39  	"fmt"
    40  	"time"
    41  
    42  	"github.com/jasoet/gopki/cert"
    43  	"github.com/jasoet/gopki/encryption"
    44  	"github.com/jasoet/gopki/encryption/asymmetric"
    45  	"github.com/jasoet/gopki/encryption/symmetric"
    46  	"github.com/jasoet/gopki/keypair"
    47  	"github.com/jasoet/gopki/keypair/algo"
    48  )
    49  
    50  // Encrypt encrypts data using envelope encryption (hybrid approach) for efficient
    51  // handling of data of any size with any supported key type.
    52  //
    53  // Type parameter:
    54  //   - T: Key pair type constrained to keypair.KeyPair interface
    55  //
    56  // Parameters:
    57  //   - data: The plaintext data to encrypt (any size supported)
    58  //   - keyPair: The recipient's key pair (public key used for DEK encryption)
    59  //   - opts: Encryption options (algorithm will be set to AlgorithmEnvelope)
    60  //
    61  // Returns:
    62  //   - *encryption.EncryptedData: Encrypted data with envelope algorithm and combined payload
    63  //   - error: Any error during DEK generation, data encryption, or key encryption
    64  //
    65  // Example:
    66  //
    67  //	// Works with any key type
    68  //	rsaKeys, _ := algo.GenerateRSAKeyPair(2048)
    69  //	largeFile := make([]byte, 10*1024*1024)  // 10MB file
    70  //	encrypted, err := envelope.Encrypt(largeFile, rsaKeys, opts)
    71  func Encrypt[T keypair.KeyPair](data []byte, keyPair T, opts encryption.EncryptOptions) (*encryption.EncryptedData, error) {
    72  	if err := encryption.ValidateEncryptOptions(opts); err != nil {
    73  		return nil, err
    74  	}
    75  
    76  	// Generate random AES-256 key for data encryption
    77  	aesKey, err := symmetric.GenerateAESKey(32)
    78  	if err != nil {
    79  		return nil, fmt.Errorf("failed to generate AES key: %w", err)
    80  	}
    81  
    82  	// Encrypt data with AES-GCM
    83  	symmetricOpts := encryption.EncryptOptions{
    84  		Algorithm: encryption.AlgorithmAESGCM,
    85  		Format:    opts.Format,
    86  		Metadata:  make(map[string]interface{}),
    87  	}
    88  
    89  	encryptedData, err := symmetric.EncryptAESGCM(data, aesKey, symmetricOpts)
    90  	if err != nil {
    91  		return nil, fmt.Errorf("failed to encrypt data with AES: %w", err)
    92  	}
    93  
    94  	// Encrypt AES key with recipient's public key
    95  	keyEncryptOpts := encryption.EncryptOptions{
    96  		Algorithm: GetAlgorithmForKeyType(getKeyType(any(keyPair))),
    97  		Format:    encryption.FormatCMS,
    98  		Metadata:  make(map[string]interface{}),
    99  	}
   100  
   101  	encryptedKey, err := asymmetric.Encrypt(aesKey, keyPair, keyEncryptOpts)
   102  	if err != nil {
   103  		return nil, fmt.Errorf("failed to encrypt AES key: %w", err)
   104  	}
   105  
   106  	// Create recipient info with complete encrypted key data
   107  	recipient := &encryption.RecipientInfo{
   108  		EncryptedKey:           encryptedKey.Data,
   109  		KeyEncryptionAlgorithm: encryptedKey.Algorithm,
   110  		EphemeralKey:           encryptedKey.EncryptedKey, // For ECDSA/Ed25519
   111  		KeyIV:                  encryptedKey.IV,
   112  		KeyTag:                 encryptedKey.Tag,
   113  	}
   114  
   115  	// Create envelope encrypted data
   116  	envelope := &encryption.EncryptedData{
   117  		Algorithm:    encryption.AlgorithmEnvelope,
   118  		Format:       opts.Format,
   119  		Data:         encryptedData.Data,
   120  		EncryptedKey: encryptedKey.Data, // Keep for backward compatibility
   121  		IV:           encryptedData.IV,
   122  		Tag:          encryptedData.Tag,
   123  		Recipients:   []*encryption.RecipientInfo{recipient},
   124  		Timestamp:    time.Now(),
   125  		Metadata:     opts.Metadata,
   126  	}
   127  
   128  	return envelope, nil
   129  }
   130  
   131  // Decrypt decrypts envelope-encrypted data.
   132  //
   133  // Type parameter:
   134  //   - T: Key pair type constrained to keypair.KeyPair interface
   135  //
   136  // Parameters:
   137  //   - encrypted: The envelope-encrypted data to decrypt
   138  //   - keyPair: The recipient's key pair (private key used for DEK decryption)
   139  //   - opts: Decryption options
   140  //
   141  // Returns:
   142  //   - []byte: The decrypted plaintext data
   143  //   - error: Any error during key or data decryption
   144  //
   145  // Example:
   146  //
   147  //	plaintext, err := envelope.Decrypt(encrypted, rsaKeys, opts)
   148  func Decrypt[T keypair.KeyPair](encrypted *encryption.EncryptedData, keyPair T, opts encryption.DecryptOptions) ([]byte, error) {
   149  	if err := encryption.ValidateDecryptOptions(opts); err != nil {
   150  		return nil, err
   151  	}
   152  
   153  	if encrypted.Algorithm != encryption.AlgorithmEnvelope {
   154  		return nil, fmt.Errorf("expected envelope algorithm, got %s", encrypted.Algorithm)
   155  	}
   156  
   157  	// Decrypt AES key using recipient's private key
   158  	keyDecryptOpts := encryption.DecryptOptions{
   159  		ExpectedAlgorithm: GetAlgorithmForKeyType(getKeyType(any(keyPair))),
   160  		VerifyTimestamp:   opts.VerifyTimestamp,
   161  		MaxAge:            opts.MaxAge,
   162  		ValidationOptions: make(map[string]interface{}),
   163  	}
   164  
   165  	var aesKey []byte
   166  	var err error
   167  
   168  	// Try to use recipient info if available (new format with ECDSA/Ed25519 support)
   169  	if len(encrypted.Recipients) > 0 {
   170  		recipient := encrypted.Recipients[0] // Use first recipient
   171  		keyEncryptedData := &encryption.EncryptedData{
   172  			Algorithm:    recipient.KeyEncryptionAlgorithm,
   173  			Format:       encryption.FormatCMS,
   174  			Data:         recipient.EncryptedKey,
   175  			EncryptedKey: recipient.EphemeralKey, // Ephemeral key for ECDSA/Ed25519
   176  			IV:           recipient.KeyIV,
   177  			Tag:          recipient.KeyTag,
   178  		}
   179  
   180  		aesKey, err = asymmetric.Decrypt(keyEncryptedData, keyPair, keyDecryptOpts)
   181  	} else {
   182  		// Fallback to legacy format (RSA only)
   183  		keyEncryptedData := &encryption.EncryptedData{
   184  			Algorithm: GetAlgorithmForKeyType(getKeyType(any(keyPair))),
   185  			Format:    encryption.FormatCMS,
   186  			Data:      encrypted.EncryptedKey,
   187  		}
   188  
   189  		aesKey, err = asymmetric.Decrypt(keyEncryptedData, keyPair, keyDecryptOpts)
   190  	}
   191  
   192  	if err != nil {
   193  		return nil, fmt.Errorf("failed to decrypt AES key: %w", err)
   194  	}
   195  
   196  	// Decrypt data using recovered AES key
   197  	dataEncryptedData := &encryption.EncryptedData{
   198  		Algorithm: encryption.AlgorithmAESGCM,
   199  		Format:    encrypted.Format,
   200  		Data:      encrypted.Data,
   201  		IV:        encrypted.IV,
   202  		Tag:       encrypted.Tag,
   203  	}
   204  
   205  	dataDecryptOpts := encryption.DecryptOptions{
   206  		ExpectedAlgorithm: encryption.AlgorithmAESGCM,
   207  		VerifyTimestamp:   opts.VerifyTimestamp,
   208  		MaxAge:            opts.MaxAge,
   209  		ValidationOptions: opts.ValidationOptions,
   210  	}
   211  
   212  	plaintext, err := symmetric.DecryptAESGCM(dataEncryptedData, aesKey, dataDecryptOpts)
   213  	if err != nil {
   214  		return nil, fmt.Errorf("failed to decrypt data with AES: %w", err)
   215  	}
   216  
   217  	return plaintext, nil
   218  }
   219  
   220  // EncryptForPublicKey encrypts data for a specific public key using envelope encryption.
   221  //
   222  // Type parameter:
   223  //   - T: Public key type constrained to keypair.PublicKey interface
   224  //
   225  // Parameters:
   226  //   - data: The plaintext data to encrypt
   227  //   - publicKey: The recipient's public key
   228  //   - opts: Encryption options
   229  //
   230  // Returns:
   231  //   - *encryption.EncryptedData: Envelope-encrypted data
   232  //   - error: Any error during encryption
   233  //
   234  // Example:
   235  //
   236  //	publicKey := rsaKeys.PublicKey()
   237  //	encrypted, err := envelope.EncryptForPublicKey(data, publicKey, opts)
   238  func EncryptForPublicKey[T keypair.PublicKey](data []byte, publicKey T, opts encryption.EncryptOptions) (*encryption.EncryptedData, error) {
   239  	// Generate random AES-256 key for data encryption
   240  	aesKey, err := symmetric.GenerateAESKey(32)
   241  	if err != nil {
   242  		return nil, fmt.Errorf("failed to generate AES key: %w", err)
   243  	}
   244  
   245  	// Encrypt data with AES-GCM
   246  	symmetricOpts := encryption.EncryptOptions{
   247  		Algorithm: encryption.AlgorithmAESGCM,
   248  		Format:    opts.Format,
   249  		Metadata:  make(map[string]interface{}),
   250  	}
   251  
   252  	encryptedData, err := symmetric.EncryptAESGCM(data, aesKey, symmetricOpts)
   253  	if err != nil {
   254  		return nil, fmt.Errorf("failed to encrypt data with AES: %w", err)
   255  	}
   256  
   257  	// Encrypt AES key with recipient's public key
   258  	keyEncryptOpts := encryption.EncryptOptions{
   259  		Algorithm: GetAlgorithmForKeyType(getPublicKeyType(any(publicKey))),
   260  		Format:    encryption.FormatCMS,
   261  		Metadata:  make(map[string]interface{}),
   262  	}
   263  
   264  	encryptedKey, err := asymmetric.EncryptForPublicKeyAny(aesKey, any(publicKey), keyEncryptOpts)
   265  	if err != nil {
   266  		return nil, fmt.Errorf("failed to encrypt AES key: %w", err)
   267  	}
   268  
   269  	// Create recipient info
   270  	recipient := &encryption.RecipientInfo{
   271  		EncryptedKey:           encryptedKey.Data,
   272  		KeyEncryptionAlgorithm: encryptedKey.Algorithm,
   273  		EphemeralKey:           encryptedKey.EncryptedKey,
   274  		KeyIV:                  encryptedKey.IV,
   275  		KeyTag:                 encryptedKey.Tag,
   276  	}
   277  
   278  	return &encryption.EncryptedData{
   279  		Algorithm:    encryption.AlgorithmEnvelope,
   280  		Format:       opts.Format,
   281  		Data:         encryptedData.Data,
   282  		EncryptedKey: encryptedKey.Data,
   283  		IV:           encryptedData.IV,
   284  		Tag:          encryptedData.Tag,
   285  		Recipients:   []*encryption.RecipientInfo{recipient},
   286  		Timestamp:    time.Now(),
   287  		Metadata:     opts.Metadata,
   288  	}, nil
   289  }
   290  
   291  // EncryptForMultipleRecipients encrypts data for multiple recipients.
   292  //
   293  // Parameters:
   294  //   - data: The data to encrypt
   295  //   - recipients: List of recipient public keys
   296  //   - opts: Encryption options
   297  //
   298  // Returns:
   299  //   - *encryption.EncryptedData: Multi-recipient encrypted data
   300  //   - error: Any error during encryption
   301  //
   302  // Example:
   303  //
   304  //	recipients := []keypair.GenericPublicKey{aliceKey, bobKey, charlieKey}
   305  //	encrypted, err := envelope.EncryptForMultipleRecipients(data, recipients, opts)
   306  func EncryptForMultipleRecipients(data []byte, recipients []keypair.GenericPublicKey, opts encryption.EncryptOptions) (*encryption.EncryptedData, error) {
   307  	if len(recipients) == 0 {
   308  		return nil, fmt.Errorf("at least one recipient is required")
   309  	}
   310  
   311  	// Generate random AES-256 key for data encryption
   312  	aesKey, err := symmetric.GenerateAESKey(32)
   313  	if err != nil {
   314  		return nil, fmt.Errorf("failed to generate AES key: %w", err)
   315  	}
   316  
   317  	// Encrypt data with AES-GCM
   318  	symmetricOpts := encryption.EncryptOptions{
   319  		Algorithm: encryption.AlgorithmAESGCM,
   320  		Format:    opts.Format,
   321  		Metadata:  make(map[string]interface{}),
   322  	}
   323  
   324  	encryptedData, err := symmetric.EncryptAESGCM(data, aesKey, symmetricOpts)
   325  	if err != nil {
   326  		return nil, fmt.Errorf("failed to encrypt data with AES: %w", err)
   327  	}
   328  
   329  	// Encrypt AES key for each recipient
   330  	var recipientInfos []*encryption.RecipientInfo
   331  	for i, publicKey := range recipients {
   332  		keyEncryptOpts := encryption.EncryptOptions{
   333  			Algorithm: GetAlgorithmForKeyType(getPublicKeyType(publicKey)),
   334  			Format:    encryption.FormatCMS,
   335  			Metadata:  make(map[string]interface{}),
   336  		}
   337  
   338  		// Note: This will only work for RSA keys currently
   339  		// ECDSA and Ed25519 would need ephemeral key generation
   340  		encryptedKey, err := asymmetric.EncryptForPublicKeyAny(aesKey, any(publicKey), keyEncryptOpts)
   341  		if err != nil {
   342  			return nil, fmt.Errorf("failed to encrypt AES key for recipient %d: %w", i, err)
   343  		}
   344  
   345  		recipientInfos = append(recipientInfos, &encryption.RecipientInfo{
   346  			KeyID:                  []byte(fmt.Sprintf("recipient-%d", i)),
   347  			EncryptedKey:           encryptedKey.Data,
   348  			KeyEncryptionAlgorithm: encryptedKey.Algorithm,
   349  			EphemeralKey:           encryptedKey.EncryptedKey,
   350  			KeyIV:                  encryptedKey.IV,
   351  			KeyTag:                 encryptedKey.Tag,
   352  		})
   353  	}
   354  
   355  	// Use first recipient's encrypted key as primary
   356  	primaryEncryptedKey := recipientInfos[0].EncryptedKey
   357  
   358  	return &encryption.EncryptedData{
   359  		Algorithm:    encryption.AlgorithmEnvelope,
   360  		Format:       opts.Format,
   361  		Data:         encryptedData.Data,
   362  		EncryptedKey: primaryEncryptedKey,
   363  		IV:           encryptedData.IV,
   364  		Tag:          encryptedData.Tag,
   365  		Recipients:   recipientInfos,
   366  		Timestamp:    time.Now(),
   367  		Metadata:     opts.Metadata,
   368  	}, nil
   369  }
   370  
   371  // DecryptForRecipient decrypts multi-recipient envelope data for a specific recipient.
   372  //
   373  // Type parameter:
   374  //   - T: Key pair type constrained to keypair.KeyPair interface
   375  //
   376  // Parameters:
   377  //   - encrypted: The multi-recipient encrypted data
   378  //   - keyPair: The recipient's key pair
   379  //   - recipientIndex: The index of this recipient in the recipient list
   380  //   - opts: Decryption options
   381  //
   382  // Returns:
   383  //   - []byte: The decrypted data
   384  //   - error: Any error during decryption
   385  //
   386  // Example:
   387  //
   388  //	// Decrypt as recipient at index 1
   389  //	plaintext, err := envelope.DecryptForRecipient(encrypted, bobKeys, 1, opts)
   390  func DecryptForRecipient[T keypair.KeyPair](encrypted *encryption.EncryptedData, keyPair T, recipientIndex int, opts encryption.DecryptOptions) ([]byte, error) {
   391  	if encrypted.Algorithm != encryption.AlgorithmEnvelope {
   392  		return nil, fmt.Errorf("expected envelope algorithm, got %s", encrypted.Algorithm)
   393  	}
   394  
   395  	if len(encrypted.Recipients) == 0 {
   396  		// Fallback to single-recipient decryption
   397  		return Decrypt(encrypted, keyPair, opts)
   398  	}
   399  
   400  	if recipientIndex < 0 || recipientIndex >= len(encrypted.Recipients) {
   401  		return nil, fmt.Errorf("invalid recipient index: %d", recipientIndex)
   402  	}
   403  
   404  	recipient := encrypted.Recipients[recipientIndex]
   405  
   406  	// Decrypt AES key using recipient's private key
   407  	keyDecryptOpts := encryption.DecryptOptions{
   408  		ExpectedAlgorithm: recipient.KeyEncryptionAlgorithm,
   409  		VerifyTimestamp:   opts.VerifyTimestamp,
   410  		MaxAge:            opts.MaxAge,
   411  		ValidationOptions: make(map[string]interface{}),
   412  	}
   413  
   414  	keyEncryptedData := &encryption.EncryptedData{
   415  		Algorithm:    recipient.KeyEncryptionAlgorithm,
   416  		Format:       encryption.FormatCMS,
   417  		Data:         recipient.EncryptedKey,
   418  		EncryptedKey: recipient.EphemeralKey,
   419  		IV:           recipient.KeyIV,
   420  		Tag:          recipient.KeyTag,
   421  	}
   422  
   423  	aesKey, err := asymmetric.Decrypt(keyEncryptedData, keyPair, keyDecryptOpts)
   424  	if err != nil {
   425  		return nil, fmt.Errorf("failed to decrypt AES key for recipient %d: %w", recipientIndex, err)
   426  	}
   427  
   428  	// Decrypt data using recovered AES key
   429  	dataEncryptedData := &encryption.EncryptedData{
   430  		Algorithm: encryption.AlgorithmAESGCM,
   431  		Format:    encrypted.Format,
   432  		Data:      encrypted.Data,
   433  		IV:        encrypted.IV,
   434  		Tag:       encrypted.Tag,
   435  	}
   436  
   437  	dataDecryptOpts := encryption.DecryptOptions{
   438  		ExpectedAlgorithm: encryption.AlgorithmAESGCM,
   439  		VerifyTimestamp:   opts.VerifyTimestamp,
   440  		MaxAge:            opts.MaxAge,
   441  		ValidationOptions: opts.ValidationOptions,
   442  	}
   443  
   444  	plaintext, err := symmetric.DecryptAESGCM(dataEncryptedData, aesKey, dataDecryptOpts)
   445  	if err != nil {
   446  		return nil, fmt.Errorf("failed to decrypt data with AES: %w", err)
   447  	}
   448  
   449  	return plaintext, nil
   450  }
   451  
   452  // EncryptWithCertificate encrypts data using a certificate's public key.
   453  //
   454  // Parameters:
   455  //   - data: The data to encrypt
   456  //   - certificate: The recipient's certificate
   457  //   - opts: Encryption options
   458  //
   459  // Returns:
   460  //   - *encryption.EncryptedData: Envelope-encrypted data
   461  //   - error: Any error during encryption
   462  //
   463  // Example:
   464  //
   465  //	encrypted, err := envelope.EncryptWithCertificate(data, recipientCert, opts)
   466  func EncryptWithCertificate(data []byte, certificate *cert.Certificate, opts encryption.EncryptOptions) (*encryption.EncryptedData, error) {
   467  	publicKey := certificate.Certificate.PublicKey
   468  
   469  	// Call the underlying encryption but then enhance with certificate info
   470  	encryptedData, err := EncryptForPublicKeyAny(data, publicKey, opts)
   471  	if err != nil {
   472  		return nil, err
   473  	}
   474  
   475  	// Add certificate information to recipient info for CMS compatibility
   476  	if len(encryptedData.Recipients) > 0 {
   477  		encryptedData.Recipients[0].Certificate = certificate.Certificate
   478  	}
   479  
   480  	return encryptedData, nil
   481  }
   482  
   483  // EncryptForPublicKeyAny is a non-generic wrapper for EncryptForPublicKey that works with any public key type.
   484  // This is used internally for dynamic dispatch when the public key type is not known at compile time.
   485  func EncryptForPublicKeyAny(data []byte, publicKey keypair.GenericPublicKey, opts encryption.EncryptOptions) (*encryption.EncryptedData, error) {
   486  	switch pk := publicKey.(type) {
   487  	case *rsa.PublicKey:
   488  		return EncryptForPublicKey(data, pk, opts)
   489  	case *ecdsa.PublicKey:
   490  		return EncryptForPublicKey(data, pk, opts)
   491  	case ed25519.PublicKey:
   492  		return asymmetric.EncryptForPublicKey(data, pk, opts)
   493  	default:
   494  		return nil, fmt.Errorf("unsupported public key type: %T", publicKey)
   495  	}
   496  }
   497  
   498  // Helper functions
   499  
   500  func getKeyType(keyPairAny keypair.GenericKeyPair) string {
   501  	switch keyPairAny.(type) {
   502  	case *algo.RSAKeyPair:
   503  		return "RSA"
   504  	case *algo.ECDSAKeyPair:
   505  		return "ECDSA"
   506  	case *algo.Ed25519KeyPair:
   507  		return "Ed25519"
   508  	default:
   509  		return "Unknown"
   510  	}
   511  }
   512  
   513  func getPublicKeyType(publicKeyAny keypair.GenericPublicKey) string {
   514  	switch publicKeyAny.(type) {
   515  	case *rsa.PublicKey:
   516  		return "RSA"
   517  	case *ecdsa.PublicKey:
   518  		return "ECDSA"
   519  	case ed25519.PublicKey:
   520  		return "Ed25519"
   521  	default:
   522  		return "Unknown"
   523  	}
   524  }
   525  
   526  // GetAlgorithmForKeyType returns the appropriate encryption algorithm for a key type
   527  func GetAlgorithmForKeyType(keyType string) encryption.Algorithm {
   528  	switch keyType {
   529  	case "RSA":
   530  		return encryption.AlgorithmRSAOAEP
   531  	case "ECDSA":
   532  		return encryption.AlgorithmECDH
   533  	case "Ed25519":
   534  		return encryption.AlgorithmX25519
   535  	default:
   536  		return encryption.AlgorithmEnvelope
   537  	}
   538  }