Code from PHP to Elixir

Hello EveryBody!
I want to ask how to convert this PHP code to Elixir code

$binKey = pack(“H*”, $hmackey);

$hmac = strtoupper(hash_hmac(‘sha512’, $msg, $binKey));

Thanks! :smiley:

Let me google that for you… The solution provided here should help:

4 Likes

Had to deal with this a few weeks back and that SO answer saved me.

Can someone help me please because I don’t know how to resolve this problem

Hi,

What is $hmackey and what is the output of pack("H*", $hmackey) ?

Did you try the stuff linked in the post by @mruoss ?

3 Likes

$hmackey is a value like this “0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF”

and pack(“H*”, $hmackey) is like this , var_dump respon is that a string(64)
“#Eg����#Eg����#Eg����#Eg����#Eg����#Eg����#Eg����#Eg����”

Yes it’s work but it’s doen’t return the same value like the respone in PHP code

I am not sure how pack("H*" ...) works. According to the docs it seems is generates a string reprensenting the data like how PHP reprensents the data in memory. If you need to do that in another language you need to know exactly what is the transformation of the data here.

Edit: found a hint:

So pack("H", "7") results in 0x70 (ASCII character 'p') and not in 0x07 (BELL character)as well as pack("H*", "347") results in 0x34 ('4') and 0x70 ('p') and not 0x03 and 0x47.

Well it looks like if I execute the following code:

<?php

$key = "0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF";
$v = pack("H*", $key);
file_put_contents("data", $v);

And the following elixir code:

packed = File.read!("data")
IO.inspect(packed, label: "packed")

I get the following output from elixir:

packed: <<1, 35, 69, 103, 137, 171, 205, 239, 1, 35, 69, 103, 137, 171, 205, 239, 1, 35,
  69, 103, 137, 171, 205, 239, 1, 35, 69, 103, 137, 171, 205, 239, 1, 35, 69,
  103, 137, 171, 205, 239, 1, 35, 69, 103, 137, 171, 205, 239, 1, 35, ...>>

And If I just decode the key I get this:

key = "0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF"
decoded = Base.decode16!(key)
IO.inspect(decoded, label: "decoded")
decoded: <<1, 35, 69, 103, 137, 171, 205, 239, 1, 35, 69, 103, 137, 171, 205, 239, 1, 35,
  69, 103, 137, 171, 205, 239, 1, 35, 69, 103, 137, 171, 205, 239, 1, 35, 69,
  103, 137, 171, 205, 239, 1, 35, 69, 103, 137, 171, 205, 239, 1, 35, ...>>

It seems that with H* pack() is just doing a decoding from base 16.

So maybe you should do something like that:

bin_key = Base.decode16!(hmac_key)
hmac =  Base.encode16(:crypto.mac(:hmac, :sha512, bin_key, msg))

Thanks everybody, I’ve resolve the problem with the answer of @lud

1 Like