webmcp
diff libraries/moonhash/moonhash.c @ 506:83b3882dc31b
New functions moonhash.shake128(data, len, alphabet), moonhash.shake256(data, len, alphabet)
Removed moonhash.shake128_128(...)
Removed moonhash.shake128_128(...)
author | jbe |
---|---|
date | Wed Aug 16 00:31:11 2017 +0200 (2017-08-16) |
parents | b36e366bba2b |
children |
line diff
1.1 --- a/libraries/moonhash/moonhash.c Tue Aug 15 21:00:51 2017 +0200 1.2 +++ b/libraries/moonhash/moonhash.c Wed Aug 16 00:31:11 2017 +0200 1.3 @@ -42,18 +42,59 @@ 1.4 return moonhash_sha3(L, FIPS202_SHA3_512, 512/8); 1.5 } 1.6 1.7 -int moonhash_shake(lua_State *L, moonhash_shake_fptr shakefunc, int len) { 1.8 +int moonhash_shake(lua_State *L, int R, lua_Integer deflen) { 1.9 const char *input; 1.10 size_t inputlen; 1.11 - unsigned char output[len]; 1.12 + lua_Integer outputlen; 1.13 + const char *alphabet; 1.14 + size_t alen; 1.15 + int abits = 0; 1.16 + uint8_t s[200]; 1.17 + luaL_Buffer luabuf; 1.18 + uint8_t *output; 1.19 + int readpos = 0; 1.20 + lua_Integer writepos = 0; 1.21 + int rbits = 0; 1.22 + int rbuf = 0; 1.23 + int rvalue; 1.24 input = luaL_checklstring(L, 1, &inputlen); 1.25 - shakefunc((const uint8_t *)input, inputlen, output, len); 1.26 - moonhash_push_hex(L, output, len); 1.27 + outputlen = luaL_optinteger(L, 2, deflen); 1.28 + alphabet = luaL_optlstring(L, 3, "0123456789abcdef", &alen); 1.29 + luaL_argcheck(L, alen>1, 3, "too few characters in alphabet"); 1.30 + { 1.31 + size_t t = alen-1; 1.32 + while (t) { 1.33 + abits++; 1.34 + if (abits > 8) luaL_argcheck(L, 0, 3, "too many characters in alphabet"); 1.35 + t >>= 1; 1.36 + } 1.37 + } 1.38 + KeccakF1600Init(s, R, (const uint8_t *)input, inputlen, 0x1F); 1.39 + output = (uint8_t *)luaL_buffinitsize(L, &luabuf, outputlen); 1.40 + while (writepos < outputlen) { 1.41 + if (rbits < abits) { 1.42 + if (readpos == R) { 1.43 + KeccakF1600(s); 1.44 + readpos = 0; 1.45 + } 1.46 + rbuf = (rbuf << 8) | s[readpos++]; 1.47 + rbits += 8; 1.48 + } 1.49 + rbits -= abits; 1.50 + rvalue = rbuf >> rbits; 1.51 + rbuf &= (1<<rbits)-1; 1.52 + if (rvalue < alen) output[writepos++] = alphabet[rvalue]; 1.53 + } 1.54 + luaL_pushresultsize(&luabuf, outputlen); 1.55 return 1; 1.56 } 1.57 1.58 -int moonhash_shake128_128(lua_State *L) { 1.59 - return moonhash_shake(L, FIPS202_SHAKE128, 128/8); 1.60 +int moonhash_shake128(lua_State *L) { 1.61 + return moonhash_shake(L, (1600-2*128)/8, 128/4); 1.62 +} 1.63 + 1.64 +int moonhash_shake256(lua_State *L) { 1.65 + return moonhash_shake(L, (1600-2*256)/8, 256/4); 1.66 } 1.67 1.68 static const struct luaL_Reg moonhash_module_functions[] = { 1.69 @@ -61,7 +102,8 @@ 1.70 {"sha3_256", moonhash_sha3_256}, 1.71 {"sha3_384", moonhash_sha3_384}, 1.72 {"sha3_512", moonhash_sha3_512}, 1.73 - {"shake128_128", moonhash_shake128_128}, 1.74 + {"shake128", moonhash_shake128}, 1.75 + {"shake256", moonhash_shake256}, 1.76 {NULL, NULL} 1.77 }; 1.78