coruus / keccak-tiny

A tiny implementation of SHA-3, SHAKE, Keccak, and sha3sum
97 stars 35 forks source link

Python, Perl or other "golfed" implementation #6

Open DonaldTsang opened 6 years ago

DonaldTsang commented 6 years ago

Since this is ~4 years old, maybe it is time to try and rewrite the code to be smaller, then possibly golfing the code in different languages like Python, Perl and others.

Example: https://www.nayuki.io/res/cryptographic-primitives-in-plain-python/sha3hash.py Has been rewritten as

rg=range
_m,_n,_r=5,24,((0,36,3,41,18),(1,44,10,45,2),(62,6,43,15,61),(28,55,25,21,56),(27,20,39,8,14),)
_u=(1<<64)-1
def il(var): return isinstance(var,list)
def r64(v,a): return ((v<<a)|(v>>(64-a)))&_u

def _hash(m,n):
    assert il(m)
    m = list(m);k=200-n//4;m.append(0x06)
    while len(m)%k!=0: m.append(0x00)
    m[-1]|=0x80;t=[[0] * _m for _ in rg(_m)]
    for i in rg(len(m)//k): b=m[i*k:(i+1)*k];cm(b,t)
    result=[]
    for i in rg(n//8):
    j=i>>3;x,y=j%_m,j//_m;result.append(int(t[x][y]>>((i%8)*8))&0xFF)
    return result

def cm(k,t):
    s = _m
    def loop(l): exec('for x in z: for y in z: '+l)
    assert il(k) and len(k)<=s*s*8 and il(t) and len(t)==s
    for col in t: assert il(col) and len(col)==s
    for (i,b) in enumerate(k):
    j=i>>3;x,y=j%s,j//s;t[x][y]^=b<<((i%8)*8)
    a=t;r=1;z=rg(s)
    for _ in rg(_n):
        c=[0]*s;loop('c[x]^=a[x][y]');d=[(c[(x-1)%s]^r64(c[(x+1)%s],1)) for x in z]
        loop('a[x][y]^=d[x]');e=[[r64(a[x][y],_r[x][y]) for y in z] for x in z]
        b=[[None] * s for _ in z];loop('b[y][(x*2+y*3)%s]=e[x][y]')
        loop('a[x][y]=b[x][y]^(~b[(x+1)%s][y]&b[(x+2)%s][y])')
        for i in rg(7):
      a[0][0]^=(r&1)<<((1<<i)-1);r=(r<<1)^((r>>7)*0x171)
DonaldTsang commented 6 years ago

Original implementation: https://github.com/XKCP/XKCP/blob/master/Standalone/CompactFIPS202/Python/CompactFIPS202.py