Using ExCrypto to decrypt a message (sample Ruby code)

Hey,

I have this code in Ruby and would like to achieve the same in Elixir (maybe using ExCrypto?)

This is the Ruby code:

require("openssl")
 
# Convert hexadecimal string
def convert(hex)
    return [hex].pack("H*")
end
 
# Create new decipher
def new_decipher(key, iv)
    cipher = OpenSSL::Cipher.new("aes-256-gcm")
    cipher.decrypt
    cipher.key = key
    cipher.iv = iv
     
    return cipher
end
 
# Data from configuration
key_from_configuration = "000102030405060708090a0b0c0d0e0f000102030405060708090a0b0c0d0e0f"
 
# Data from server
iv_from_http_header = "000000000000000000000000"
auth_tag_from_http_header = "CE573FB7A41AB78E743180DC83FF09BD"
http_body = "0A3471C72D9BE49A8520F79C66BBD9A12FF9"
 
# Convert data to process
key = convert(key_from_configuration)
iv = convert(iv_from_http_header)
auth_tag = convert(auth_tag_from_http_header)
cipher_text = convert(http_body)
 
# Prepare decryption
decipher = new_decipher(key, iv)
decipher.auth_tag = auth_tag
 
# Decrypt
result = decipher.update(cipher_text) + decipher.final
puts result

Would be great if someone could help me get this working.

Thanks :wink:

1 Like

Here’s how to do it without ExCrypto:

iex(1)> key = Base.decode16!("000102030405060708090a0b0c0d0e0f000102030405060708090a0b0c0d0e0f", case: :lower)
<<0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0, 1, 2, 3, 4, 5, 6, 7,
  8, 9, 10, 11, 12, 13, 14, 15>>
iex(2)> iv = Base.decode16!("000000000000000000000000")
<<0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0>>
iex(3)> auth_tag = Base.decode16!("CE573FB7A41AB78E743180DC83FF09BD")
<<206, 87, 63, 183, 164, 26, 183, 142, 116, 49, 128, 220, 131, 255, 9, 189>>
iex(4)> cipher_text = Base.decode16!("0A3471C72D9BE49A8520F79C66BBD9A12FF9")
<<10, 52, 113, 199, 45, 155, 228, 154, 133, 32, 247, 156, 102, 187, 217, 161,
  47, 249>>
iex(5)> :crypto.block_decrypt(:aes_gcm, key, iv, {<<>>, cipher_text, auth_tag})
"{\"type\":\"PAYMENT\"}"
4 Likes

Great man it works!! Thanks a lot! :slight_smile: