Thanks for the reply ChristopheBelpaire,
does the iv argument have to be binary when given to the one_time function and the key can be a string?
because when i try Base.decode16! the key i get (ArgumentError) non-alphabet digit found: “%” as that how other Help with crypto module - crypto_one_time method - (ArgumentError) argument error Issue - #2 by NobbZ users have done
# Use AES 128 Bit Keys for Encryption.
@block_size 16
def encrypt(plaintext) do
# create random Initialisation Vector
iv = "}Lq5Wu~nkr\Vdfm~"
# sample secret_key is a 32 bit hex string
secret_key = "%8R=&PfC5SXT:pRF2vF[5zCTy}M7CX]J"
plaintext = pad(plaintext, @block_size)
encrypted_text = :crypto.crypto_one_time(:aes_128_cbc, secret_key, iv, plaintext, true )
encrypted_text = ( iv <> encrypted_text )
:base64.encode(encrypted_text)
end
def decrypt(ciphertext) do
secret_key = "%8R=&PfC5SXT:pRF2vF[5zCTy}M7CX]J"
ciphertext = :base64.decode(ciphertext)
<<iv::binary-16, ciphertext::binary>> = ciphertext
decrypted_text = :crypto.crypto_one_time(:aes_128_cbc, secret_key, iv, ciphertext, false )
unpad(decrypted_text)
end
def unpad(data) do
to_remove = :binary.last(data)
:binary.part(data, 0, byte_size(data) - to_remove)
end
# PKCS5Padding
def pad(data, block_size) do
to_add = block_size - rem(byte_size(data), block_size)
data <> :binary.copy(<<to_add>>, to_add)
end
end