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

     1  package asymmetric
     2  
     3  import (
     4  	"crypto/aes"
     5  	"crypto/cipher"
     6  	"crypto/rand"
     7  	"crypto/sha256"
     8  	"fmt"
     9  	"io"
    10  
    11  	"golang.org/x/crypto/hkdf"
    12  )
    13  
    14  // deriveAESKey derives an AES-256 key from a shared secret using HKDF.
    15  //
    16  // This function uses HKDF (HMAC-based Key Derivation Function) with SHA-256
    17  // to derive a deterministic 256-bit AES key from the provided shared secret.
    18  // The same shared secret will always produce the same AES key.
    19  //
    20  // Parameters:
    21  //   - sharedSecret: The shared secret obtained from key agreement (ECDH/X25519)
    22  //
    23  // Returns:
    24  //   - []byte: A 32-byte (256-bit) AES key derived from the shared secret
    25  //
    26  // Security properties:
    27  //   - Uses HKDF with SHA-256 for cryptographically strong key derivation
    28  //   - Includes a salt value ("GoPKI-AES-Key") for domain separation
    29  //   - Produces uniformly distributed key material
    30  func deriveAESKey(sharedSecret []byte) []byte {
    31  	hkdf := hkdf.New(sha256.New, sharedSecret, nil, []byte("GoPKI-AES-Key"))
    32  	key := make([]byte, 32) // 256-bit key
    33  	_, _ = io.ReadFull(hkdf, key)
    34  	return key
    35  }
    36  
    37  // encryptAESGCM encrypts data using AES-256-GCM with a random nonce.
    38  //
    39  // AES-GCM provides authenticated encryption, ensuring both confidentiality
    40  // and integrity of the encrypted data. A random nonce is generated for each
    41  // encryption operation to ensure semantic security.
    42  //
    43  // Parameters:
    44  //   - data: The plaintext data to encrypt
    45  //   - key: The 32-byte AES-256 key
    46  //
    47  // Returns:
    48  //   - []byte: The encrypted ciphertext
    49  //   - []byte: The random nonce (IV) used for encryption
    50  //   - []byte: The authentication tag for integrity verification
    51  //   - error: Any error that occurred during encryption
    52  //
    53  // Security properties:
    54  //   - AES-256-GCM authenticated encryption
    55  //   - Random nonce for each encryption (semantic security)
    56  //   - Authentication tag prevents tampering
    57  func encryptAESGCM(data []byte, key []byte) ([]byte, []byte, []byte, error) {
    58  	if len(key) != 32 {
    59  		return nil, nil, nil, fmt.Errorf("key must be 32 bytes for AES-256")
    60  	}
    61  
    62  	block, err := aes.NewCipher(key)
    63  	if err != nil {
    64  		return nil, nil, nil, fmt.Errorf("failed to create AES cipher: %w", err)
    65  	}
    66  
    67  	gcm, err := cipher.NewGCM(block)
    68  	if err != nil {
    69  		return nil, nil, nil, fmt.Errorf("failed to create GCM cipher: %w", err)
    70  	}
    71  
    72  	nonce := make([]byte, gcm.NonceSize())
    73  	if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
    74  		return nil, nil, nil, fmt.Errorf("failed to generate nonce: %w", err)
    75  	}
    76  
    77  	ciphertext := gcm.Seal(nil, nonce, data, nil)
    78  
    79  	// Separate the ciphertext and tag
    80  	tagStart := len(ciphertext) - gcm.Overhead()
    81  	actualCiphertext := ciphertext[:tagStart]
    82  	tag := ciphertext[tagStart:]
    83  
    84  	return actualCiphertext, nonce, tag, nil
    85  }
    86  
    87  // decryptAESGCM decrypts AES-256-GCM encrypted data with authentication verification.
    88  //
    89  // This function reverses the AES-GCM encryption process, verifying the authentication
    90  // tag to ensure data integrity before returning the plaintext.
    91  //
    92  // Parameters:
    93  //   - ciphertext: The encrypted data to decrypt
    94  //   - key: The 32-byte AES-256 key used for encryption
    95  //   - nonce: The nonce (IV) used during encryption
    96  //   - tag: The authentication tag for integrity verification
    97  //
    98  // Returns:
    99  //   - []byte: The decrypted plaintext data
   100  //   - error: Any error that occurred during decryption or authentication failure
   101  //
   102  // Security properties:
   103  //   - Authentication tag verification prevents tampering
   104  //   - Constant-time comparison for tag verification
   105  //   - Fails securely on authentication errors
   106  func decryptAESGCM(ciphertext []byte, key []byte, nonce []byte, tag []byte) ([]byte, error) {
   107  	if len(key) != 32 {
   108  		return nil, fmt.Errorf("key must be 32 bytes for AES-256")
   109  	}
   110  
   111  	block, err := aes.NewCipher(key)
   112  	if err != nil {
   113  		return nil, fmt.Errorf("failed to create AES cipher: %w", err)
   114  	}
   115  
   116  	gcm, err := cipher.NewGCM(block)
   117  	if err != nil {
   118  		return nil, fmt.Errorf("failed to create GCM cipher: %w", err)
   119  	}
   120  
   121  	// Reconstruct the full ciphertext with tag
   122  	fullCiphertext := append(ciphertext, tag...)
   123  
   124  	plaintext, err := gcm.Open(nil, nonce, fullCiphertext, nil)
   125  	if err != nil {
   126  		return nil, fmt.Errorf("GCM decryption failed (authentication error): %w", err)
   127  	}
   128  
   129  	return plaintext, nil
   130  }