lets implement a symmetric encryption , given a key and a value give me the encrypted…
- User
lets implement a symmetric encryption , given a key and a value give me the encrypted value in a determinisitic manner.
Do it in ruby and follow best practices
Assistant
Okay, let's implement symmetric encryption in Ruby using AES (Advanced Encryption Standard) in GCM (Galois/Counter Mode). GCM is a good choice because it provides both encryption and authentication (AEAD - Authenticated Encryption with Associated Data).
To achieve deterministic encryption (same key, same plaintext yields same ciphertext), we must use a fixed Initialization Vector (IV) and a fixed salt for key derivation.
Important Security Warning: Using a fixed IV and fixed salt for deterministic encryption is generally NOT recommended for most security applications.
- Fixed IV: If you encrypt the same plaintext multiple times with the same key and the same (fixed) IV, you will always get the same ciphertext. This can leak information. For example, an attacker might learn when the same message is being sent. Best practice is to use a unique, random IV for each encryption operation (and prepend it to the ciphertext).
- Fixed Salt (for KDF): If multiple users use the same password, and you use a fixed salt, they will all derive the same encryption key. This makes rainbow table attacks more feasible across your user base if one password leaks. Best practice is to use a unique, random salt per user/key.
However, since the requirement is explicitly for deterministic output, we will proceed with fixed values, but you must understand these trade-offs. This approach might be suitable for specific use cases like encrypting database fields where you need to be able to query the encrypted values (though even then, there are specialized techniques).
Here's the implementation:
require 'openssl' require 'base64' require 'digest' # For SHA256 if we were to derive IV, not strictly needed for fixed IV module DeterministicSymmetricEncryptor # --- Configuration Constants --- # AES-256-GCM is a strong modern choice. CIPHER_ALGORITHM = 'aes-256-gcm'.freeze # Key Derivation Function (KDF) parameters # PBKDF2 is a standard KDF. # WARNING: This salt is FIXED for determinism. In a real-world, non-deterministic scenario, # this salt should be randomly generated per key and stored. PBKDF2_SALT = "a-fixed-salt-for-determinism".freeze # MUST be the same for encrypt/decrypt PBKDF2_ITERATIONS = 20_000 # NIST recommendation is >= 10,000 # Initialization Vector (IV) # WARNING: This IV is FIXED for determinism. In a real-world, non-deterministic scenario, # this IV should be randomly generated for each encryption and prepended to the ciphertext. # For AES-GCM, a 12-byte (96-bit) IV is commonly recommended. # Ensure this IV is exactly the length required by the cipher (cipher.iv_len). # We'll generate a 12-byte fixed IV. # You could use something like: OpenSSL::Random.random_bytes(12) once and store it, # or derive it from something fixed. For simplicity, we'll use a fixed string. FIXED_IV_STRING = "FixedIV12Bytes" # This will be 14 bytes, let's truncate or hash # Let's derive it to ensure correct length and binary format: FIXED_IV = Digest::SHA256.digest(FIXED_IV_STRING)[0...12] # Take first 12 bytes of SHA256 hash # --- Key Derivation --- # Derives a cryptographically strong key from a user-provided password/key string. private_class_method def self.derive_key(password_string) cipher = OpenSSL::Cipher.new(CIPHER_ALGORITHM) key_length = cipher.key_len # For AES-256, this is 32 bytes OpenSSL::PKCS5.pbkdf2_hmac( password_string, PBKDF2_SALT, PBKDF2_ITERATIONS, key_length, OpenSSL::Digest::SHA256.new # Use SHA256 for PBKDF2 ) end # --- Encryption --- def self.encrypt(key_string:, value:) raise ArgumentError, "key_string cannot be nil or empty" if key_string.nil? || key_string.empty? raise ArgumentError, "value cannot be nil" if value.nil? # Empty string value is okay derived_key = derive_key(key_string) cipher = OpenSSL::Cipher.new(CIPHER_ALGORITHM) cipher.encrypt cipher.key = derived_key cipher.iv = FIXED_IV # Use the fixed IV # For GCM, you can optionally include "Associated Authenticated Data" (AAD) # This data is not encrypted but is authenticated. If it changes, decryption fails. # For simplicity, we'll omit AAD, or use an empty string. # cipher.auth_data = "" # Or some fixed associated data if needed encrypted_data = cipher.update(value.to_s) + cipher.final auth_tag = cipher.auth_tag # GCM requires storing the authentication tag # For deterministic output, we don't prepend the IV (since it's fixed and known) # We only need to store the ciphertext and the auth_tag. # We'll combine them and Base64 encode for easy storage/transmission. # Format: Base64(auth_tag) + "." + Base64(ciphertext) # The auth_tag for AES-GCM is typically 16 bytes. [ Base64.strict_encode64(auth_tag), Base64.strict_encode64(encrypted_data) ].join('.') rescue OpenSSL::Cipher::CipherError => e # Log error or raise a custom error raise "Encryption failed: #{e.message}" end # --- Decryption --- def self.decrypt(key_string:, encrypted_value_string:) raise ArgumentError, "key_string cannot be nil or empty" if key_string.nil? || key_string.empty? raise ArgumentError, "encrypted_value_string cannot be nil or empty" if encrypted_value_string.nil? || encrypted_value_string.empty? derived_key = derive_key(key_string) auth_tag_b64, ciphertext_b64 = encrypted_value_string.split('.', 2) unless auth_tag_b64 && ciphertext_b64 raise ArgumentError, "Encrypted value string is not in the expected format (tag.ciphertext)" end begin auth_tag = Base64.strict_decode64(auth_tag_b64) encrypted_data = Base64.strict_decode64(ciphertext_b64) rescue ArgumentError # Base64 decoding error raise "Decryption failed: Invalid Base64 encoding in encrypted value." end decipher = OpenSSL::Cipher.new(CIPHER_ALGORITHM) decipher.decrypt decipher.key = derived_key decipher.iv = FIXED_IV # Use the same fixed IV decipher.auth_tag = auth_tag # Set the authentication tag BEFORE decryption # If AAD was used during encryption, it must be set here too: # decipher.auth_data = "" # Must be identical to AAD used in encryption decrypted_data = decipher.update(encrypted_data) + decipher.final decrypted_data rescue OpenSSL::Cipher::CipherError => e # This error often means the key is wrong, the data is corrupt, # or the auth_tag doesn't match (tampering or wrong key/IV). raise "Decryption failed: #{e.message}. Possible incorrect key, tampered data, or wrong IV/salt configuration." end end # --- Example Usage --- if __FILE__ == $PROGRAM_NAME my_key = "super_secret_key_123!" original_value = "This is a sensitive piece of information." puts "Original Value: #{original_value}" # Encryption encrypted_val = DeterministicSymmetricEncryptor.encrypt(key_string: my_key, value: original_value) puts "Encrypted (Deterministic): #{encrypted_val}" # Encryption again with same key and value encrypted_val_again = DeterministicSymmetricEncryptor.encrypt(key_string: my_key, value: original_value) puts "Encrypted Again (Deterministic): #{encrypted_val_again}" puts "Are they the same? #{encrypted_val == encrypted_val_again}" # Should be true # Decryption begin decrypted_val = DeterministicSymmetricEncryptor.decrypt(key_string: my_key, encrypted_value_string: encrypted_val) puts "Decrypted Value: #{decrypted_val}" puts "Decryption successful? #{original_value == decrypted_val}" rescue StandardError => e puts "Decryption Error: #{e.message}" end puts "\n--- Test with a different value ---" another_value = "Another secret." encrypted_another = DeterministicSymmetricEncryptor.encrypt(key_string: my_key, value: another_value) puts "Encrypted (Another Value): #{encrypted_another}" decrypted_another = DeterministicSymmetricEncryptor.decrypt(key_string: my_key, encrypted_value_string: encrypted_another) puts "Decrypted (Another Value): #{decrypted_another}" puts "\n--- Test with a wrong key ---" wrong_key = "wrong_key_!" begin DeterministicSymmetricEncryptor.decrypt(key_string: wrong_key, encrypted_value_string: encrypted_val) rescue StandardError => e puts "Decryption with wrong key (expected failure): #{e.message}" # Should fail end puts "\n--- Test with tampered data (modify auth_tag) ---" parts = encrypted_val.split('.') tampered_auth_tag_b64 = Base64.strict_encode64(OpenSSL::Random.random_bytes(16)) # GCM auth tag is usually 16 bytes tampered_encrypted_val = [tampered_auth_tag_b64, parts[1]].join('.') begin DeterministicSymmetricEncryptor.decrypt(key_string: my_key, encrypted_value_string: tampered_encrypted_val) rescue StandardError => e puts "Decryption with tampered auth_tag (expected failure): #{e.message}" # Should fail end puts "\n--- Test with tampered data (modify ciphertext) ---" parts = encrypted_val.split('.') tampered_ciphertext_b64 = Base64.strict_encode64(Base64.strict_decode64(parts[1]) + "extra") tampered_encrypted_val_2 = [parts[0], tampered_ciphertext_b64].join('.') begin DeterministicSymmetricEncryptor.decrypt(key_string: my_key, encrypted_value_string: tampered_encrypted_val_2) rescue StandardError => e puts "Decryption with tampered ciphertext (expected failure): #{e.message}" # Should fail end endExplanation and Best Practices followed (within the deterministic constraint):
-
Algorithm Choice (AES-256-GCM):
aes-256-gcmis a strong, modern, and widely recommended authenticated encryption (AEAD) algorithm.- AES-256: Uses a 256-bit key for strong encryption.
- GCM Mode: Provides both confidentiality (encryption) and integrity/authenticity (via an authentication tag). This means it detects if the ciphertext has been tampered with.
-
Key Derivation (PBKDF2):
- The
key_stringprovided by the user (which might be a password) is not directly used as the encryption key. - Instead,
OpenSSL::PKCS5.pbkdf2_hmacis used. PBKDF2 (Password-Based Key Derivation Function 2) is a standard algorithm to stretch a password into a cryptographically strong key of a desired length. - Salt (
PBKDF2_SALT): A salt adds uniqueness to the key derivation process. For determinism, this salt is fixed. In non-deterministic scenarios, this salt should be random and stored alongside the encrypted data. - Iterations (
PBKDF2_ITERATIONS): A high number of iterations makes brute-forcing the original password much harder. 20,000 is a reasonable starting point. - Digest (
OpenSSL::Digest::SHA256.new): SHA256 is used as the underlying hash function for PBKDF2.
- The
-
Initialization Vector (IV):
FIXED_IV: For GCM mode, an IV is required. For determinism, this IV is fixed. It's crucial that this IV is exactly the length required by the cipher (typically 12 bytes for GCM). We derive it from a fixed string using SHA256 to ensure it's a binary string of the correct length.- Security Implication: Reusing an IV with the same key for different plaintexts in GCM mode can be catastrophic, potentially compromising all messages encrypted with that key/IV pair. Since we are fixing it for determinism, this system is vulnerable if an attacker can observe multiple ciphertexts generated from different plaintexts using the same key.
-
Encryption Process:
cipher.encryptsets the cipher to encryption mode.cipher.key = derived_keysets the derived key.cipher.iv = FIXED_IVsets the initialization vector.cipher.update(value) + cipher.finalperforms the encryption.cipher.auth_tagretrieves the GCM authentication tag. This tag is essential for verifying data integrity during decryption.
-
Ciphertext Formatting:
- The output format is
Base64(auth_tag).Base64(ciphertext). - Base64 encoding is used to convert the binary ciphertext and auth_tag into a string that can be easily stored or transmitted.
strict_encode64avoids newlines. - The IV is not prepended because it's fixed and known by both encrypting and decrypting parties.
- The output format is
-
Decryption Process:
- The same
derived_keyandFIXED_IVare used. - The
auth_tagis extracted from the input string and set on the decipher object usingdecipher.auth_tag = auth_tag. This must be done before callingfinal. - If decryption succeeds and the authentication tag matches, the original plaintext is returned.
- If the key is wrong, the data is tampered, or the IV/salt configuration differs,
OpenSSL::Cipher::CipherErrorwill typically be raised duringdecipher.final(or ifauth_tagis incorrect).
- The same
-
Error Handling:
- Basic argument checks are included.
rescue OpenSSL::Cipher::CipherErrorcatches common cryptographic errors during encryption/decryption, providing more user-friendly messages.
-
Modularity:
- The encryption/decryption logic is encapsulated in a module
DeterministicSymmetricEncryptor.
- The encryption/decryption logic is encapsulated in a module
This implementation fulfills the request for deterministic symmetric encryption while using strong cryptographic primitives. Remember the significant security caveats associated with using fixed IVs and salts. If the "deterministic" requirement can be relaxed, using random IVs (prepended to ciphertext) and random salts (stored with the key or user profile) is strongly recommended for better security.