Search code examples
cryptographypseudocodeshasha256

SHA 256 pseuedocode?


I've been trying to work out how SHA-256 works. One thing I've been doing for other algorithms is I've worked out a sort of step by step pseudocode function for the algorithm.

I've tried to do the same for SHA256 but thus far I'm having quite a bit of trouble.

I've tried to work out how the Wikipedia diagram works but besides the text part explaining the functions I'm not sure I've got it right.

Wikipedia diagram of SHA256 Caption for Wikipedia diagram of SHA256

Here's what I have so far:

  • Input is an array 8 items long where each item is 32 bits.
  • Output is an array 8 items long where each item is 32 bits.
  • Calculate all the function boxes and store those values. I'll refer to them by function name.
  • Store input, right shifted by 32 bits, into output.
    • At this point, in the out array, E is the wrong value and A is empty
  • Store the function boxes.
    • now we need to calculate out E and out A.
    • note: I've replaced the modulo commands with a bitwise AND 2^(32-1)

I can't figure out how the modulus adding lines up, but I think it is like this:

  • Store (Input H + Ch + ( (Wt+Kt) AND 2^31 ) ) AND 2^31 As mod1
  • Store (sum1 + mod1) AND 2^31 as mod2
  • Store (d + mod2) AND 2^31 into output E
    • now output E is correct and all we need is output A
  • Store (MA + mod2) AND 2^31 as mod3
  • Store (sum0 + mod3) AND 2^31 into output A
    • output now contains the correct hash of input.
    • Do we return now or does this need to be run repeatedly?

Did I get all of those addition modulos right?

what are Wt and Kt?

Would this get run once, and you're done or does it need to be run a certain number of times, with the output being re-used as input?

Here's the link by the way. http://en.wikipedia.org/wiki/SHA-2#Hash_function

Thanks alot, Brian


Solution

  • Have a look at the official standard that describes the algorithm, the variables are described here: http://csrc.nist.gov/publications/fips/fips180-4/fips-180-4.pdf

    (Oh, now I see I'm almost a year late with my answer, ah, never mind...)