Zokrates / ZoKrates

A toolbox for zkSNARKs on Ethereum
https://zokrates.github.io
GNU Lesser General Public License v3.0
1.8k stars 360 forks source link

how do hash a string value instead of integer values? #1345

Closed sourav-bz closed 9 months ago

sourav-bz commented 11 months ago

I checked out the "Types" in the doc, https://zokrates.github.io/language/types.html I haven't found any way I can hash a string value to check if they were right? Is there any function which I am not aware about?

hash = keccak('name01') or hash = poseidon('long-string')

How do i go about this?

dark64 commented 11 months ago

ZoKrates doesn't support strings as a type, but you can always convert your strings from ASCII to an array of bytes (u8) and work with that. There are some limitations with this method though as ZoKrates expects all inputs to be of fixed size. See this example.

sourav-bz commented 11 months ago

@dark64 what are the limitations? what if the length of the string is really long and dynamic? how do i go about dealing with that?

dark64 commented 11 months ago

@dark64 what are the limitations? what if the length of the string is really long and dynamic? how do i go about dealing with that?

Size has to be constant at compile-time, the program gets compiled to a static constraint system so no dynamic inputs are allowed. You could slice your input into fixed-size chunks and do some aggregation techniques maybe?

alv-around commented 10 months ago

@sourav-bz find in the following link an example on how to hash a string in python so is compatible in ZoKrates.

In the end what you do is convert a string into a string of 0s and 1s. This string can the be interpret as a binary number, which in turn can be seen as a number of any representation. The reason why this conversion is not so straigth forward is due to the fact that 'utf-8' (the standard string encoding in python and others..) is that UTF-8 is a variable-length character encoding standard. This means that string with different number of characters might have the same number of bits/bytes and that there are not direct map between a byte and a certain character.

Note that this is something which lays on the language you use to generate the hashes, rather than on ZoKrates side. Moreover this answers the original issue title and body, so I would suggest to close this issue.

sourav-bz commented 9 months ago

@alvaro-alonso thank you so much for this! it solved the problem i was trying to solve 🙏