1
0
Fork 0
mirror of synced 2025-09-24 04:40:05 +00:00
ZoKrates/zokrates_stdlib/stdlib/hashes/keccak/keccak.zok

111 lines
No EOL
3 KiB
Text

// based on keccak-f[1600] permutation
def rho() -> u32[24]:
return [
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 2, 14,
27, 41, 56, 8, 25, 43, 62, 18, 39, 61, 20, 44
]
def pi() -> u32[24]:
return [
10, 7, 11, 17, 18, 3, 5, 16, 8, 21, 24, 4,
15, 23, 19, 13, 12, 2, 20, 14, 22, 9, 6, 1
]
def rc() -> u64[24]:
return [
0x0000000000000001, 0x0000000000008082, 0x800000000000808a,
0x8000000080008000, 0x000000000000808b, 0x0000000080000001,
0x8000000080008081, 0x8000000000008009, 0x000000000000008a,
0x0000000000000088, 0x0000000080008009, 0x000000008000000a,
0x000000008000808b, 0x800000000000008b, 0x8000000000008089,
0x8000000000008003, 0x8000000000008002, 0x8000000000000080,
0x000000000000800a, 0x800000008000000a, 0x8000000080008081,
0x8000000000008080, 0x0000000080000001, 0x8000000080008008
]
// left rotation
def rotl64(u64 x, u32 n) -> u64:
return ((x << n) | (x >> (64 - n)))
// change endianness
def swap_u64(u64 val) -> u64:
val = ((val << 8) & 0xFF00FF00FF00FF00) | ((val >> 8) & 0x00FF00FF00FF00FF)
val = ((val << 16) & 0xFFFF0000FFFF0000) | ((val >> 16) & 0x0000FFFF0000FFFF)
return (val << 32) | (val >> 32)
// compression function
def keccakf(u64[25] st) -> u64[25]:
u32[24] rotc = rho()
u32[24] piln = pi()
u64[24] rndc = rc()
u64[5] bc = [0; 5]
u64 t = 0
for u32 r in 0..24 do
// theta
for u32 i in 0..5 do
bc[i] = st[i] ^ st[i + 5] ^ st[i + 10] ^ st[i + 15] ^ st[i + 20]
endfor
for u32 i in 0..5 do
t = bc[(i + 4) % 5] ^ rotl64(bc[(i + 1) % 5], 1)
for u32 j in 0..5 do
st[(j * 5) + i] = st[(j * 5) + i] ^ t
endfor
endfor
t = st[1]
// rho pi
for u32 i in 0..24 do
bc[0] = st[piln[i]]
st[piln[i]] = rotl64(t, rotc[i])
t = bc[0]
endfor
// chi
for u32 i in 0..5 do
for u32 j in 0..5 do
bc[j] = st[(i * 5) + j]
endfor
for u32 j in 0..5 do
u32 p = (i * 5) + j
st[p] = st[p] ^ (!bc[(j + 1) % 5] & bc[(j + 2) % 5])
endfor
endfor
// iota
st[0] = st[0] ^ rndc[r]
endfor
return st
def main<N, W>(u64[N] input, u64 pad) -> u64[25]:
u64[25] q = [0; 25]
u32 rate = (200 - (W / 4)) / 8
u32 pt = 0
// change endianness of inputs from big endian to little endian
for u32 i in 0..N do
input[i] = swap_u64(input[i])
endfor
// update
for u32 i in 0..N do
q[pt] = q[pt] ^ input[i]
pt = (pt + 1) % rate
q = if pt == 0 then keccakf(q) else q fi
endfor
// finalize
q[pt] = q[pt] ^ pad
q[rate - 1] = q[rate - 1] ^ 0x8000000000000000
q = keccakf(q)
// change endianness of output from little endian to big endian
for u32 i in 0..W/64 do
q[i] = swap_u64(q[i])
endfor
return q