sha256 to big integer

Posted by Fearless on Sun 15 Nov 2020 11:32 PM — 6 posts, 22,921 views.

#0
How do I get the output of sha256 into a big integer? (Yes, I'm going to do math on it.) Everything I tried doesn't work.


str = "foo"

ihash = bc.number(utils.sha256(str))
Note("bc: " .. tostring(ihash))

shex = utils.tohex(utils.sha256(str))
Note("hex: " .. shex)

ihash = bc.number(shex)
Note("bc: " .. tostring(ihash))

shex = "0x" .. shex
ihash = bc.number(shex)
Note("bc: " .. tostring(ihash))
Amended on Mon 16 Nov 2020 02:41 AM by Nick Gammon
Australia Forum Administrator #1
You can do it by breaking down the hex number into chunks, and then using a loop to build up the final number, multiplying each chunk by the appropriate power of 2, like this:


str = "foo"

shex = utils.tohex(utils.sha256(str))
Note("hex: " .. shex)

mul = 0
out = bc.number (0)


for i = 64, 1, -8 do
  local hexdigits = string.sub (shex, i - 7, i)
  local decdigits = tonumber (hexdigits, 16)
  out = out + bc.number (decdigits) * bc.pow (2, mul)
  mul = mul + 32
end -- for

print (out)



Result:


19970150736239713706088444570146546354146685096673408908105596072151101138862
USA Global Moderator #2
[EDIT] Looks like Nick beat me to the answer!

bc.number doesn't accept hex formatted strings, so you have to break it apart and do some recombinant arithmetic.

Try this from the BC library test code:


function hex2bc(s)
   local x=bc.number(0)
   for i=1,#s do
      x=16*x+tonumber(s:sub(i,i),16)
   end
   return x
end


shex = utils.tohex(utils.sha256("foo"))
Note("Hex: " .. shex)
Note("BC: " .. bc.tostring(hex2bc(shex)))
Amended on Mon 16 Nov 2020 02:46 AM by Fiendish
Australia Forum Administrator #3
My answer was specifically written for a 64-character hex string (256 bits) whereas the code Fiendish posted would be more general (for any length hex string).

It gives the same results, which is kind-of comforting.


Hex: 2C26B46B68FFC68FF99B453C1D30413413422D706483BFA0F98A5E886266E7AE
BC: 19970150736239713706088444570146546354146685096673408908105596072151101138862
Amended on Mon 16 Nov 2020 03:19 AM by Nick Gammon
#4
That function is great. I could have written something a bit messier but I never would have found that one. Thanks.

Google knows exactly one URL with "function hex2bc(s)" but knowing the answer and then searching for it is cheating.
USA Global Moderator #5
It came from https://github.com/LuaDist/lbc/blob/93ca33ce5cbc31b1bfe3e985e10afcfb9e9c8b92/test.lua#L153-L159