github.com/jasoet/gopki@v1.15.0/encryption/symmetric/symmetric.go (about) 1 // Package symmetric provides AES-GCM symmetric encryption operations. 2 // 3 // This package implements authenticated encryption using AES-GCM (Galois/Counter Mode), 4 // which provides both confidentiality and authenticity in a single operation. 5 // AES-GCM is the recommended authenticated encryption mode for new applications. 6 // 7 // Features: 8 // - AES-GCM authenticated encryption with 128, 192, or 256-bit keys 9 // - HKDF (HMAC-based Key Derivation Function) for key derivation 10 // - Automatic nonce generation for each encryption operation 11 // - Authentication tag verification during decryption 12 // - Password-based key derivation with PBKDF2 13 // 14 // Security properties: 15 // - Confidentiality: Data is encrypted with AES in counter mode 16 // - Authenticity: GMAC provides authentication of both data and AAD 17 // - Integrity: Any tampering with ciphertext is detected during decryption 18 // - Nonce misuse resistance: Each encryption uses a unique random nonce 19 // 20 // Performance characteristics: 21 // - High performance on modern processors with AES-NI instructions 22 // - Parallelizable encryption and decryption 23 // - Minimal overhead compared to AES-CTR + HMAC 24 // 25 // Example usage: 26 // 27 // // Generate a random key 28 // key, err := symmetric.GenerateAESKey(32) // 256-bit key 29 // if err != nil { 30 // log.Fatal(err) 31 // } 32 // 33 // // Encrypt data 34 // opts := encryption.EncryptOptions{ 35 // Algorithm: encryption.AlgorithmAESGCM, 36 // Format: encryption.FormatCMS, 37 // } 38 // encrypted, err := symmetric.EncryptAESGCM(data, key, opts) 39 // 40 // // Decrypt data 41 // decrypted, err := symmetric.DecryptAESGCM(encrypted, key, opts) 42 package symmetric 43 44 import ( 45 "crypto/aes" 46 "crypto/cipher" 47 "crypto/rand" 48 "crypto/sha256" 49 "fmt" 50 "io" 51 "time" 52 53 "github.com/jasoet/gopki/encryption" 54 "golang.org/x/crypto/hkdf" 55 "golang.org/x/crypto/pbkdf2" 56 ) 57 58 // EncryptAESGCM encrypts data using AES-GCM authenticated encryption with the provided key. 59 // 60 // This function implements authenticated encryption using AES in Galois/Counter Mode. 61 // It automatically generates a unique nonce for each encryption operation and 62 // includes the authentication tag in the output for integrity verification. 63 // 64 // Key requirements: 65 // - Must be exactly 16, 24, or 32 bytes for AES-128, AES-192, or AES-256 66 // - Should be cryptographically random or derived using a secure KDF 67 // - Must not be reused across different encryption contexts 68 // 69 // Parameters: 70 // - data: The plaintext data to encrypt (no size limitations) 71 // - key: The AES encryption key (16, 24, or 32 bytes) 72 // - opts: Encryption options (algorithm will be set to AlgorithmAESGCM) 73 // 74 // Returns: 75 // - *encryption.EncryptedData: Encrypted data containing nonce + ciphertext + auth tag 76 // - error: Invalid key size or encryption failure 77 // 78 // Security properties: 79 // - Semantic security: identical plaintexts produce different ciphertexts 80 // - Authentication: tampering with ciphertext is detected during decryption 81 // - Nonce uniqueness: each encryption uses a fresh 96-bit random nonce 82 // 83 // Performance: 84 // - Efficient on hardware with AES-NI instructions 85 // - Suitable for encrypting data of any size 86 // - Lower overhead than separate encryption + MAC operations 87 // 88 // Example: 89 // 90 // key := make([]byte, 32) // 256-bit key 91 // _, _ = rand.Read(key) 92 // encrypted, err := symmetric.EncryptAESGCM(data, key, opts) 93 // if err != nil { 94 // log.Fatal("AES-GCM encryption failed:", err) 95 // } 96 func EncryptAESGCM(data []byte, key []byte, opts encryption.EncryptOptions) (*encryption.EncryptedData, error) { 97 if err := encryption.ValidateEncryptOptions(opts); err != nil { 98 return nil, err 99 } 100 101 // Validate key size 102 if len(key) != 16 && len(key) != 24 && len(key) != 32 { 103 return nil, fmt.Errorf("invalid AES key size: %d bytes (must be 16, 24, or 32)", len(key)) 104 } 105 106 // Create AES cipher 107 block, err := aes.NewCipher(key) 108 if err != nil { 109 return nil, fmt.Errorf("failed to create AES cipher: %w", err) 110 } 111 112 // Create GCM mode 113 gcm, err := cipher.NewGCM(block) 114 if err != nil { 115 return nil, fmt.Errorf("failed to create GCM mode: %w", err) 116 } 117 118 // Generate nonce 119 nonce := make([]byte, gcm.NonceSize()) 120 if _, err := io.ReadFull(rand.Reader, nonce); err != nil { 121 return nil, fmt.Errorf("failed to generate nonce: %w", err) 122 } 123 124 // Encrypt and authenticate 125 ciphertext := gcm.Seal(nil, nonce, data, nil) 126 127 // Extract authentication tag (last 16 bytes) 128 tagStart := len(ciphertext) - gcm.Overhead() 129 actualCiphertext := ciphertext[:tagStart] 130 tag := ciphertext[tagStart:] 131 132 return &encryption.EncryptedData{ 133 Algorithm: encryption.AlgorithmAESGCM, 134 Format: opts.Format, 135 Data: actualCiphertext, 136 IV: nonce, 137 Tag: tag, 138 Timestamp: time.Now(), 139 Metadata: opts.Metadata, 140 }, nil 141 } 142 143 // DecryptAESGCM decrypts AES-GCM encrypted data with authentication verification. 144 // 145 // This function reverses the AES-GCM encryption process, verifying the authentication 146 // tag to ensure data integrity before returning the plaintext. If the authentication 147 // tag verification fails, the function returns an error and no plaintext is revealed. 148 // 149 // Parameters: 150 // - encrypted: The encrypted data structure containing ciphertext, nonce, and tag 151 // - key: The same AES key used for encryption (16, 24, or 32 bytes) 152 // - opts: Decryption options for validation 153 // 154 // Returns: 155 // - []byte: The decrypted plaintext data 156 // - error: Authentication failure, invalid parameters, or decryption error 157 // 158 // Security guarantees: 159 // - Authentication: Returns error if data has been tampered with 160 // - Constant-time tag verification: Prevents timing attacks 161 // - No partial decryption: Either succeeds completely or fails entirely 162 // 163 // Example: 164 // 165 // decrypted, err := symmetric.DecryptAESGCM(encrypted, key, opts) 166 // if err != nil { 167 // log.Fatal("AES-GCM decryption failed:", err) 168 // } 169 func DecryptAESGCM(encrypted *encryption.EncryptedData, key []byte, opts encryption.DecryptOptions) ([]byte, error) { 170 if err := encryption.ValidateDecryptOptions(opts); err != nil { 171 return nil, err 172 } 173 174 if encrypted.Algorithm != encryption.AlgorithmAESGCM { 175 return nil, fmt.Errorf("expected AES-GCM algorithm, got %s", encrypted.Algorithm) 176 } 177 178 // Validate key size 179 if len(key) != 16 && len(key) != 24 && len(key) != 32 { 180 return nil, fmt.Errorf("invalid AES key size: %d bytes (must be 16, 24, or 32)", len(key)) 181 } 182 183 // Create AES cipher 184 block, err := aes.NewCipher(key) 185 if err != nil { 186 return nil, fmt.Errorf("failed to create AES cipher: %w", err) 187 } 188 189 // Create GCM mode 190 gcm, err := cipher.NewGCM(block) 191 if err != nil { 192 return nil, fmt.Errorf("failed to create GCM mode: %w", err) 193 } 194 195 // Reconstruct ciphertext with tag 196 ciphertextWithTag := append(encrypted.Data, encrypted.Tag...) 197 198 // Decrypt and verify authentication 199 plaintext, err := gcm.Open(nil, encrypted.IV, ciphertextWithTag, nil) 200 if err != nil { 201 return nil, fmt.Errorf("AES-GCM decryption failed (authentication error): %w", err) 202 } 203 204 return plaintext, nil 205 } 206 207 // GenerateAESKey generates a cryptographically secure random AES key. 208 // 209 // Parameters: 210 // - keySize: Key size in bytes (16 for AES-128, 24 for AES-192, 32 for AES-256) 211 // 212 // Returns: 213 // - []byte: The generated AES key 214 // - error: Invalid key size error 215 // 216 // Example: 217 // 218 // key, err := symmetric.GenerateAESKey(32) // Generate 256-bit key 219 // if err != nil { 220 // log.Fatal(err) 221 // } 222 func GenerateAESKey(keySize int) ([]byte, error) { 223 if keySize != 16 && keySize != 24 && keySize != 32 { 224 return nil, fmt.Errorf("invalid AES key size: must be 16, 24, or 32 bytes") 225 } 226 227 key := make([]byte, keySize) 228 if _, err := io.ReadFull(rand.Reader, key); err != nil { 229 return nil, fmt.Errorf("failed to generate random key: %w", err) 230 } 231 232 return key, nil 233 } 234 235 // DeriveKeyFromPassword derives an AES key from a password using PBKDF2. 236 // 237 // This function uses PBKDF2 (Password-Based Key Derivation Function 2) with 238 // SHA-256 to derive a cryptographic key from a password and salt. 239 // 240 // Parameters: 241 // - password: The password string 242 // - salt: Random salt (at least 16 bytes recommended) 243 // - keySize: Desired key size in bytes (16, 24, or 32) 244 // - iterations: Number of PBKDF2 iterations (100,000 minimum recommended) 245 // 246 // Returns: 247 // - []byte: The derived AES key 248 // - error: Invalid parameters 249 // 250 // Security recommendations: 251 // - Use a random salt of at least 16 bytes 252 // - Use at least 100,000 iterations (more for higher security) 253 // - Store the salt with the encrypted data for decryption 254 // 255 // Example: 256 // 257 // salt, _ := symmetric.GenerateSalt(16) 258 // key, err := symmetric.DeriveKeyFromPassword("myPassword", salt, 32, 100000) 259 func DeriveKeyFromPassword(password string, salt []byte, keySize int, iterations int) ([]byte, error) { 260 if keySize != 16 && keySize != 24 && keySize != 32 { 261 return nil, fmt.Errorf("invalid AES key size: must be 16, 24, or 32 bytes") 262 } 263 264 if len(salt) < 8 { 265 return nil, fmt.Errorf("salt too short: minimum 8 bytes required") 266 } 267 268 if iterations < 1000 { 269 return nil, fmt.Errorf("iteration count too low: minimum 1000 required") 270 } 271 272 key := pbkdf2.Key([]byte(password), salt, iterations, keySize, sha256.New) 273 return key, nil 274 } 275 276 // DeriveKeyFromSharedSecret derives an AES key from a shared secret using HKDF. 277 // 278 // This function uses HKDF (HMAC-based Key Derivation Function) with SHA-256 279 // to derive a deterministic AES key from a shared secret obtained through 280 // key agreement protocols like ECDH or X25519. 281 // 282 // Parameters: 283 // - sharedSecret: The shared secret from key agreement 284 // - info: Optional context/application-specific information 285 // - keySize: Desired key size in bytes (16, 24, or 32) 286 // 287 // Returns: 288 // - []byte: The derived AES key 289 // - error: Invalid parameters or derivation failure 290 // 291 // Example: 292 // 293 // // After ECDH key agreement 294 // aesKey, err := symmetric.DeriveKeyFromSharedSecret(sharedSecret, []byte("encryption"), 32) 295 func DeriveKeyFromSharedSecret(sharedSecret []byte, info []byte, keySize int) ([]byte, error) { 296 if keySize != 16 && keySize != 24 && keySize != 32 { 297 return nil, fmt.Errorf("invalid AES key size: must be 16, 24, or 32 bytes") 298 } 299 300 if len(sharedSecret) == 0 { 301 return nil, fmt.Errorf("shared secret cannot be empty") 302 } 303 304 hkdf := hkdf.New(sha256.New, sharedSecret, nil, info) 305 key := make([]byte, keySize) 306 if _, err := io.ReadFull(hkdf, key); err != nil { 307 return nil, fmt.Errorf("failed to derive key: %w", err) 308 } 309 310 return key, nil 311 } 312 313 // GenerateSalt generates a cryptographically random salt. 314 // 315 // Parameters: 316 // - size: Salt size in bytes (16 bytes minimum recommended) 317 // 318 // Returns: 319 // - []byte: The generated salt 320 // - error: Invalid size or generation failure 321 // 322 // Example: 323 // 324 // salt, err := symmetric.GenerateSalt(16) 325 // if err != nil { 326 // log.Fatal(err) 327 // } 328 func GenerateSalt(size int) ([]byte, error) { 329 if size < 16 { 330 return nil, fmt.Errorf("salt size too small: minimum 16 bytes recommended") 331 } 332 333 salt := make([]byte, size) 334 if _, err := io.ReadFull(rand.Reader, salt); err != nil { 335 return nil, fmt.Errorf("failed to generate salt: %w", err) 336 } 337 338 return salt, nil 339 } 340 341 // QuickEncryptSymmetric provides simple symmetric encryption with default options. 342 // 343 // Parameters: 344 // - data: The plaintext data to encrypt 345 // - key: The AES encryption key 346 // 347 // Returns: 348 // - *encryption.EncryptedData: The encrypted data 349 // - error: Any error during encryption 350 // 351 // Example: 352 // 353 // key, _ := symmetric.GenerateAESKey(32) 354 // encrypted, err := symmetric.QuickEncryptSymmetric(data, key) 355 func QuickEncryptSymmetric(data []byte, key []byte) (*encryption.EncryptedData, error) { 356 return EncryptAESGCM(data, key, encryption.DefaultEncryptOptions()) 357 } 358 359 // QuickDecryptSymmetric provides simple symmetric decryption with default options. 360 // 361 // Parameters: 362 // - encrypted: The encrypted data 363 // - key: The AES decryption key 364 // 365 // Returns: 366 // - []byte: The decrypted plaintext 367 // - error: Any error during decryption 368 // 369 // Example: 370 // 371 // plaintext, err := symmetric.QuickDecryptSymmetric(encrypted, key) 372 func QuickDecryptSymmetric(encrypted *encryption.EncryptedData, key []byte) ([]byte, error) { 373 return DecryptAESGCM(encrypted, key, encryption.DefaultDecryptOptions()) 374 }