emn178 / js-sha3

A simple SHA-3 / Keccak hash function for JavaScript supports UTF-8 encoding.
MIT License
354 stars 86 forks source link

cSHAKE implementation produces invalid output #24

Closed paulmillr closed 1 year ago

paulmillr commented 3 years ago

You have issue with cshake implementation here: https://github.com/emn178/js-sha3/blob/b39d0910cb4cce54a6060c21e1491d55f70269bf/src/sha3.js#L326 it should be var paddingBytes = (w - bytes % w) % w;, since it should not pad if value is already divisible by block size without remainder. (spec: https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-185.pdf: bytepad function step 3 here: while (len(z)/8) mod w ≠ 0: We encountered the same error in noble-hashes, which contains XKCP-generated test vectors

Test case which triggers the error:

let str='084fed08b978af4d7d196a7446a86b58009e636b611db16211b65a9aadff29c5084fed08b978af4d7d196a7446a86b58009e636b611db16211b65a9aadff29c5084fed08b978af4d7d196a7446a86b58009e636b611db16211b65a9aadff29c5084fed08b978af4d7d196a7446a86b58009e636b611db16211b65a9aad';
Buffer.from(new Uint8Array(require('js-sha3').kmac256.create(Buffer.from([]), 16*8, Buffer.from(str, 'hex')).update(Buffer([])).arrayBuffer())).toString('hex')==='031801b0b50ebeef772fbe7a279bc144'

Instead, it returns bc58e9c8534e5fa7346f06e6ab25e2db

ren1244 commented 2 years ago

For cshake128(X, L, N, S) I get incorrect result if length of S is 161 and N is empty string.

ren1244 commented 2 years ago

cshake128/256

for example

console.log(jsSha3.cshake128('',  128, '', ''));
//get: 7f9c2ba4e88f827d616045507605853e

console.log(jsSha3.cshake128([],  128, '', ''));
//get: 7f9c2ba4e88f827d616045507605853e

console.log(jsSha3.cshake128('',  128, [], ''));
//get: 1cdef541e61a208fd370edc896cc7ee0

console.log(jsSha3.cshake128('',  128, '', []));
//get: 1cdef541e61a208fd370edc896cc7ee0

console.log(jsSha3.cshake128([],  128, [], []));
//get: 1cdef541e61a208fd370edc896cc7ee0
emn178 commented 1 year ago

Thank you for reporting. Will fix in next version.

emn178 commented 1 year ago

fixed in v0.9.1, please check.