lang/python/ SHA256


Page SHA256 does not exist yet.

The following code generates the correct constants for the Rust implementation I wrote.

#!/usr/bin/env python3
import math

ofn = "src/consts.rsi"

# generate constants for sha256
def isprime(x):
  for i in range(2,int(1+x**0.5)):
    if x % i == 0:
      return False
  return True
def tofrac(x):
  f = x - math.floor(x)
  g = f * 2**32
  h = int(g)
  return h
def gen_consts():
  a = list(filter(isprime,range(2,312)))[:64]
  b = a[:8]
  I = list(map(lambda t: tofrac(t**(1/2)),b))
  K = list(map(lambda t: tofrac(t**(1/3)),a))
  return (I,K)
I,K = gen_consts()

def print_consts(ty,name,vals):
  n = len(vals)
  print(f"const {name} : [{ty} ; {n}] = [")
  for i,val in enumerate(vals):
    if i<len(vals)-1:
      print(f"  0x{val:08x},",end="")
      if i%4 == (4-1):
        print()
    else:
      print(f"  0x{val:08x}")
  print("];")

if __name__ == "__main__":
  print("mod sha256_consts {")
  print_consts("u32","I",I)
  print_consts("u32","K",K)   
  print("}")