0

What would be the equivalent of PHP's date("c"), hash_hmac('sha512', "str1", "str2"), and pack("H*", $secretkey) in Elixir?

I want to convert this to elixir code

$binKey = pack("H*", $hmackey);
$hmac = strtoupper(hash_hmac('sha512', $msg, $binKey));
Fractaliste
  • 5,777
  • 11
  • 42
  • 86

1 Answers1

0

I don't know any PHP but here someone already asked how to format a date. If you want ISO8601 as the output it's super easy (Date.utc_today() |> Date.to_iso8601()).

Elixir does not provide HMAC hashing in its standard library as far as I know. But you can use the Erlang function: :crypto.hash/2 E.g., :crypto.hash(:sha512, "text"). See the Erlang crypto docs. Note that I'm unsure about what hash_hmac does exactly. If you want a Message Authentication Code, look into the :crypto.mac/3 function.

As for pack("H*", $secretkey) is that converting an integer to a string in hexadecimal representation? If that's the case, then secret_key |> Integer.to_string(16) is what you want.


After your comment I assume this is what you want to copy and paste:

hmac_key = "deadbeef"
msg = "your message to sign"
bin_key = hmac_key |> String.to_integer(16)
:crypto.mac(:hmac, :sha512, msg, bin_key) |> Base.encode16()

Obviously you'll still need to substitute msg and hmac_key with your values.

kaikuchn
  • 795
  • 7
  • 15
  • This don't run for me – Hasimbola RAKOTOSON May 19 '22 at 13:29
  • $binKey = pack("H*", $hmackey); $hmac = strtoupper(hash_hmac('sha512', $msg, $binKey)); This is the code that I want to convert to Elixir – Hasimbola RAKOTOSON May 19 '22 at 13:42
  • I appended a copy&paste ready code block, this should be what you want. – kaikuchn May 19 '22 at 15:37
  • I've tried this code but this raise an error, I don't know how to do this in Elixir – Hasimbola RAKOTOSON May 20 '22 at 05:52
  • Do we really need the bin_key step? It seems to me one can simply call `:crypto.mac(:hmac, :sha512, msg, hmac_key)`. – bortzmeyer May 20 '22 at 08:59
  • @bortzmeyer it would be a very different key though. It looks like the key is provided as a hex string in the original code. Not knowing anything else about the system I really can't say what's unnecessary here. That's something the OP would need to think about. OP, what's the error you are getting? The above code works for me..? – kaikuchn May 20 '22 at 15:09