Home > Net >  Issue with F# SHA256Managed, output hash Removes 0's
Issue with F# SHA256Managed, output hash Removes 0's

Time:09-21

Using F#, I'm trying to write a function to calculate the SHA256 hash of any given string. When I compare the hash values generated by my function to the one from this website (https://xorbin.com/tools/sha256-hash-calculator), the length of my hash is always smaller than 64. Upon closer examination, I noticed that my hash omits some 0 values. I'm suspecting something is off with how I'm encoding the string, but I'm not sure. Any thoughts on what is causing the problem and how to fix it??

Here is the function:

open System.Security.Cryptography
open System.Text

let calculateHash (inputString: string) =
    Encoding.UTF8.GetBytes(inputString)
    |> (new SHA256Managed()).ComputeHash
    |> Seq.iter (printf "%x")

    printfn ""

For example, here is the hash for the string "Test":

The website generates:

532eaabd9574880dbf76b9b8cc00832c20a6ec113d682299550d7a6e0f345e25

My function generates:

532eaabd957488dbf76b9b8cc0832c20a6ec113d68229955d7a6ef345e25

CodePudding user response:

The problem is not your calculation, but your printing.

You are iterating over individual bytes and printing them using printf "%x". This prints the byte as a hexadecimal value, but for numbers smaller than 16, this is just a single character - so if you printf "%x" 10, this results in just a - you need to pad this with spaces and get 0a.

To do this, you can change the format string to be x where 0 and 2 means pad with zeros, to total lenght of 2 characters:

let calculateHash (inputString: string) =
    Encoding.UTF8.GetBytes(inputString)
    |> (new SHA256Managed()).ComputeHash
    |> Seq.iter (printf "x")
    printfn ""
  • Related