Search code examples
hashf#sha

F# converting hmac python into f#


How would I convert this Python code into F# "

message = nonce + client_id + api_key
signature = hmac.new(API_SECRET, msg=message, digestmod=hashlib.sha256).hexdigest().upper()

My code so far to achieve this:

let message =string(nonce)+ client_id + api_key
let signature = HMACSHA256.Create(API_secret+message)

Simple issue is I cannot find what represents the hexdigest() function in F#.

Also, do I combine the API_Secret with the message as I have done or must they be separated?


Solution

  • I think you need somethink like this:

    let hexdigest (bytes : byte[]) =
       let sb = System.Text.StringBuilder()
       bytes |> Array.iter (fun b -> b.ToString("X2") |> sb.Append |> ignore)
       string sb
    
    let signature =
       use hmac = new HMACSHA256.Create(API_secret)
       hmac.ComputeHash(message)
       |> hexdigest
    

    The part with the StringBuilder is what hexdigest does in python (if I get hexdigest right)