MatijaL

MatijaL

How to hash a random number?

Hi,
I’m trying to hash a random number but can’t make it work…

num = Enum.random(1..9999)
hashed_num = :crypto.hash(:sha256, num)

I’m getting “1st argument: not an iodata term” error. From my understanding, Enum.random creates a number and :crypto.hash wants an iodata. The same thing happens if I use :crypto.rand_uniform(1, 9999) instead of Enum.random… can anyone help?

Marked As Solved

LostKobrakai

LostKobrakai

An integer() value is not a subtype of iodata() and even the integers allowed as part of an iolist need to be byte values, so in the range of 0..255. you likely want to encode your integer to a binary format first.

Also Liked

tangui

tangui

You can transform any term to a binary (and then hash it) with :erlang.binary_to_term/1:

iex> :erlang.term_to_binary(42)
<<131, 97, 42>>
iex> :erlang.term_to_binary(42.0)
<<131, 70, 64, 69, 0, 0, 0, 0, 0, 0>>
iex> :erlang.term_to_binary({4, 2})
<<131, 104, 2, 97, 4, 97, 2>>
soup

soup

Note that’s hashing the string “999”, not the integer 999, which might make a difference to some intentions or across application contexts. (You could argue that settling on “we always hash everything as utf8-string” as being more transportable/less-complex?)

Your hashing here is fixed width but for some things like encoding Base58 it makes a difference in payload size if nothing else.

t = DateTime.utc_now() |> DateTime.to_unix(:microsecond)

to_string_encode =
  t
  |> Integer.to_string()
  |> Base.encode64()
  |> dbg()

to_bin_encode =
  t
  |> then(fn x ->
    <<x::unsigned-integer-size(64)>>
  end)
  |> Base.encode64()
  |> dbg()

to_string_base =
  t
  # you can also pass a 2->36 (not 64!) as a base
  # this is *not* functionally the same thing though!
  |> Integer.to_string(32)
  |> dbg()

[
  to_string_encode: to_string_encode,
  to_bin_encode: to_bin_encode,
]

# the encoded string is a larger payload than the encoded integer
# => [to_string_encode: "MTY2NjQzNTI4MTAzNzU3NA==",
# =>  to_bin_encode:    "AAXrnTL3qQY="]

term_to_binary might be problematic as its leading byte is a version number (which I assume can change …) and the docs warn “There is no guarantee that this function will return the same encoded representation for the same term.”

There is an option for deterministic but it’s not x-otp version stable.

Option deterministic (introduced in OTP 24.1) can be used to ensure that within the same major release of Erlang/OTP, the same encoded representation is returned for the same term. There is still no guarantee that the encoded representation remains the same between major releases of Erlang/OTP.

That does make me wonder though, how easy is it to safely & stabley hash an actual composed data type? You could convert to some other format like json or mpack but those aren’t guaranteed to be stably ordered. I guess you’re stuck converting each value to a bitstring/hash and hashing the combination?

voltone

voltone

Or, instead of counting bits, you can just let the Erlang runtime produce the smallest binary representation of any given integer: :binary.encode_unsigned/1.

Still, I wonder what use-case is the OP had in mind: it seems to me this is building a PRNG with questionable randomness properties. If the idea is to return 32 bytes of truly random data, use :crypto.strong_rand_bytes(32). Might be faster too…

Where Next?

Popular in Questions Top

marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
Lily
In templates/appointment/index.html.eex: &lt;%= for appointment &lt;- @appointments do %&gt; &lt;tr&gt; &lt;td&gt;&lt;%= appoi...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
jaysoifer
Is there a way to rollback a specific migration and only that one (“skipping” all the other ones)? Would mix ecto.rollback -v 200809061...
New
earth10
Hi, I’m just starting to build a side-project with Elixir and Phoenix and doing some basic test with Elixir alone. What strikes me is th...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New

Other popular topics Top

aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
New
hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a &gt; b) do {:ok, "a"} end if (a &lt; b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
gausby
I asked this very same question on twitter and got some interesting feedback, but I thought it would be a good question to ask here as we...
1207 39467 209
New
boundedvariable
I am going through the kafka architecture. All the features what the kafka is providing are already in Erlang. I would like hear your opi...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 54120 245
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement