HMAC_SHA256 not matching in Julia and python

I have to encode a pass phrase with a “api secret” in SHA256 then base encode64 and send it to the rest api server but I can not manage to match what I get out of python with Julia.

This is the python code

import hmac
import hashlib
import base64
from urllib.parse import urlencode

secret = "string"
pass = "string"

passphrase = base64.b64encode(hmac.new(secret.encode('utf-8'), pass.encode('utf-8'), hashlib.sha256).digest())

I used Nettle.jl for HMAC SHA256 Julia but I get a totally different output

secret = "string"
pass = "string"

passphrase = base64encode(hexdigest("sha256", secret, pass))

There is SHA.jl and it has apparently the same function which is hmac_sha2_256 but when I set my inputs as “secret” and “pass” it gives “no method matching” for the first input. I tried to convert the first input to UInt8 with transcode() function still gives the same error. What am I doing wrong ?

I got the same value as python gives with the SHA.jl. There is no documentation for HMAC functionality in the SHA.jl albeit having all the SHA1 to 3. If you search hmac_sha256 in the terminal you get the bellow explanation:

No documentation found.

  SHA.hmac_sha256 is a Function.

  # 5 methods for generic function "hmac_sha256":
  [1] hmac_sha256(key::Vector{UInt8}, data::Union{Tuple{Vararg{UInt8, N}} where N, AbstractVector{UInt8}}) in SHA at /Applications/Julia-1.7.app/Contents/Resources/julia/share/julia/stdlib/v1.7/SHA/src/SHA.jl:99
  [2] hmac_sha256(key::Vector{UInt8}, io::IO) in SHA at /Applications/Julia-1.7.app/Contents/Resources/julia/share/julia/stdlib/v1.7/SHA/src/SHA.jl:125
  [3] hmac_sha256(key::Vector{UInt8}, io::IO, chunk_size) in SHA at /Applications/Julia-1.7.app/Contents/Resources/julia/share/julia/stdlib/v1.7/SHA/src/SHA.jl:125
  [4] hmac_sha256(key::Vector{UInt8}, str::String) in SHA at /Applications/Julia-1.7.app/Contents/Resources/julia/share/julia/stdlib/v1.7/SHA/src/SHA.jl:109
  [5] hmac_sha256(key::Vector{UInt8}, str::AbstractString) in SHA at /Applications/Julia-1.7.app/Contents/Resources/julia/share/julia/stdlib/v1.7/SHA/src/SHA.jl:108

Which I was mistakenly putting a string as my key and solved with a Vector{UInt8}(secret) input as key.
I still could not get the Nettle.jl to match, I don’t know what Im doing wrong there.

1 Like

If there’s some API or documentation improvement to be made, please do open an issue on GitHub.

2 Likes

Alright will do.

For an example of how this works:

using SHA

key = "mykey"
msg = "mymsg"

enc = bytes2hex(hmac_sha256(Vector{UInt8}(key), msg))

This should be equivalent to Python’s

import hmac
import hashlib

key = "mykey"
msg = "mymsg"
encoding = 'utf-8'  # or 'ascii'

enc = hmac.new(key.encode(encoding), msg.encode(encoding), hashlib.sha256).hexdigest()
1 Like