hoseinisalim
Convert base64 string to byte string
how to convert base64 string to byte string?
Most Liked
chrismcg
You can turn it into a list:
iex(11)> "Like this š" |> Base.encode64
"TGlrZSB0aGlzIPCfmIA="
iex(12)> "TGlrZSB0aGlzIPCfmIA=" |> Base.decode64!() |> :binary.bin_to_list()
[76, 105, 107, 101, 32, 116, 104, 105, 115, 32, 240, 159, 152, 128]
NobbZ
I already told you a few times, the documentation of that library is far from par.
Also @chrismcg told you to try Base.url_decode64!/1, which you obviously didnāt, as it works for me:
iex(1)> message = "Foo"
"Foo"
iex(2)> {:ok, key64} = ExCrypto.generate_aes_key(:aes_256, :base64)
{:ok, "YBFgCMzhnxIOVeirWf5hgzbFmUcvZcHY0yKRJJ4Ocks="}
iex(3)> key = Base.url_decode64!(key64)
<<96, 17, 96, 8, 204, 225, 159, 18, 14, 85, 232, 171, 89, 254, 97, 131, 54, 197,
153, 71, 47, 101, 193, 216, 211, 34, 145, 36, 158, 14, 114, 75>>
iex(4)> {:ok, {iv, ciphered}} = ExCrypto.encrypt(key, message)
{:ok,
{<<195, 207, 172, 38, 128, 248, 158, 10, 14, 239, 231, 195, 48, 154, 244, 177>>,
<<4, 238, 11, 86, 7, 6, 5, 86, 13, 182, 189, 113, 193, 85, 194, 141>>}}
iex(5)> {:ok, clear} = ExCrypto.decrypt(key, iv, ciphered)
{:ok, "Foo"}
It seems as if you really need to actively read and understand the sources of this library to be able to use it.
My suggestion is, that you use :bytes with the key generator and then convert the resulting binary to exactly the format you really need. No surprises anymore because of bad documentation, that claims to return base64 encoded string but actually does return an Base64-URL-encoded stringā¦
NobbZ
NobbZ
Why should one want that? Most of the time, the binary consumes much less memory, and if you are randomly reading bytes from it, its also much faster. Also writing it to a file is probably faster, as it can be read from continous memory, while writing from a list would mean to follow a pointer for each next byte.
Also binaries are much easier to handle if we want to match on exact bits.
So, do not convert from a binary to a list unless you really have to, and then you should be sure to use the correct conversion function.
NobbZ
For use in ExCrypto.encrypt/2 you need to generate the key as :bytes.







