I have a working python AES-256-GCM snippet from https://stackoverflow.com/a/77376155/22814155:
from Crypto.Cipher import AES
from Crypto.Hash import SHA512
from Crypto.Protocol.KDF import PBKDF2
# plaintext='Changeit!'
password='1+LFssX4whxz9lOPQ9OS7g4NvQzbCe8j'
salt = b'NiFi Static Salt'
def decrypt(ciphertext, key, mode):
(ciphertext, authTag, nonce) = ciphertext
encobj = AES.new(key, mode, nonce)
return(encobj.decrypt_and_verify(ciphertext, authTag))
key = PBKDF2(password, salt, 32, count=160000, hmac_hash_module=SHA512) # 32 bytes key
ciphertext = (
bytes.fromhex('2242e26ffd3e2c33c2'), # actual ciphertext
bytes.fromhex('98f06730fffa9687cb0d845f57c1a645'), # authentication tag
bytes.fromhex('697a84312aac99fbe2315f0637c96035') # nonce
)
res = decrypt(ciphertext, key, AES.MODE_GCM)
print ("\n\nDecrypted:\t",res.decode()) # Decrypted: Changeit!
However, I'm attempting to translate this to Ruby. I have the following code:
require 'openssl'
password = '1+LFssX4whxz9lOPQ9OS7g4NvQzbCe8j'
salt = 'NiFi Static Salt'
def decrypt(ciphertext, auth_tag, key, nonce)
password = '1+LFssX4whxz9lOPQ9OS7g4NvQzbCe8j'
salt = 'NiFi Static Salt'.bytes.join('')
decipher = OpenSSL::Cipher.new('AES-256-GCM')
decipher.decrypt
decipher.key = key
decipher.iv = nonce
decipher.auth_tag = auth_tag
decrypted_text = decipher.update(ciphertext)
decrypted_text << decipher.final
decrypted_text
end
key = OpenSSL::PKCS5.pbkdf2_hmac(password, salt, 160000, 32, 'SHA512')
ciphertext = ["2242e26ffd3e2c33c2"].pack('H*') # actual ciphertext
auth_tag = ["98f06730fffa9687cb0d845f57c1a645"].pack('H*') # authentication tag
nonce = ["697a84312aac99fbe2315f0637c96035"].pack('H*') # nonce
res = decrypt(ciphertext, auth_tag, key, nonce)
puts "\n\nDecrypted:\t#{res}"
However, it errors with /tmp/test.rb:12:in iv=': iv must be 12 bytes (ArgumentError). The nonce is definitely larger than 12 bytes, however it was in python as well. Not sure what the difference is or how to correct it.