I want to find a hash function to generate a hash with a given length - function

Just like the title, I want to find a hash function to generate a hash with a given length. From the Internet I found one solution is I can use the SHAKE256 technique. But I cannot find some java code to use the SHAKE256. Anyone can provide me some sample java code so that I can use it in my code?

I typed java shake256 into Google and found this solution as the 2nd result: https://github.com/aelstad/keccakj. It is a Java library called "keccakj" that is able to compute shake256 hashes, among others.

For shake256, to generate a hash of an arbitrary bit length d and d < 256, you can just trim the result of SHAKEDigest from bouncycastle.
public static byte[] hash(byte[] src, int byteLength){
//import org.bouncycastle.crypto.digests.SHAKEDigest;
Assert.assertTrue("do not support result length more than 32", byteLength<=32);
SHAKEDigest d = new SHAKEDigest(256);
byte[]checksumByte = new byte[32];
d.update(src,0,src.length);
d.doFinal(checksumByte,0);
return Arrays.copyOf(checksumByte,byteLength);
}

Related

Solidity and Web3 sha3() methods return something else

In my contract, I have a function that returns the sha3 hash of a certain set of values. While running some tests I found that the value returned from this function differs from the hash value generated by web3.utils.sha3() (with identical arguments).
Here is the code:
Solidity
function hashInfo() public onlyOwner view returns (bytes32) {
bytes32 hash = sha3(
'0x969A70A4fa9F69D2D655E4B743abb9cA297E5328',
'0x496AAFA2960f3Ff530716B5334c9aFf4612e3c27',
'jdiojd',
'oidjoidj',
'idjodj',
12345
)
return hash;
}
JS (web3)
async function testHash(instance){
const contractHash = await instance.methods.hashInfo().call({from: '0x969A70A4fa9F69D2D655E4B743abb9cA297E5328'});
const localHash = web3.utils.sha3(
'0x969A70A4fa9F69D2D655E4B743abb9cA297E5328',
'0x496AAFA2960f3Ff530716B5334c9aFf4612e3c27',
'jdiojd',
'oidjoidj',
'idjodj',
12345
)
console.log(contractHash);
console.log(localHash);
console.log('local == contract: ' + (contractHash == localHash));
}
The resulting console output is:
0xe65757c5a99964b72d217493c192c073b9a580ec4b477f40a6c1f4bc537be076
0x3c23cebfe35b4da6f6592d38876bdb93f548085baf9000d538a1beb31558fc6d
local == contract: false
Any ideas? Does this have something to do with passing multiple arguments to the functions? I have also tried to convert everything to a string and concatenate them into one single string, but also without success.
Thanks in advance!
UPDATE
I found out there also if a web3 method called web3.utils.soliditySha3(). This too did not work and gave the following result:
0xe65757c5a99964b72d217493c192c073b9a580ec4b477f40a6c1f4bc537be076
0x0cf65f7c81dab0a5d414539b0e2f3807526fd9c15e197eaa6c7706d27aa7a0f8
local == contract: false
I'm happy I came after your update as I was just gonna suggest solditySHA3. Now that you've got the right function your problem is most likely with Soldity packing it's parameters.
As you can see here, sha3 is an alias to keccak256 which tightly packs it's arguments. Following the link on that page takes you here which fully explains how it's handled. Basically just take the inputs to soliditySHA3 and pack the bits as if they were the sizes of the variables you used. So if you hashed two uint32s (32 bits each, 64 total) you need to take the 2 64 bit Javascript numbers and compress them into 1 Javascript number.
For cases where more than 64 bits are needed I believe you can pass sequential ints (sets of 64 bits) to soliditySHA3 or you could use a BigInt. Personally, I usually try to only hash 256 bit variables together to avoid having to manually pack my bits on the JS end, but we all know that space constraints are huge in Solidity. I hope I helped, and let me know if you have further questions.

How to Paramatrized vector of registers in chisel

I need an example on how to paramtrize Vector of registers in terms of bit-width and initial values which are not '0' and are different for each register.
My use-case is a generic filter coefficients bank with some unique reset values to each, and off course an option to override values.
I thought of something like the below code (not really sure how to write the iteration, so this is kind of pseudo):
class Coeffbank(bitWidth : UInt ,ncoeff : UInt, rstVal : Vec(SInt)) extends Module {
// how do iterate through the reset vector ?? //
val coeffs = Vec.fill(ncoeff) {Reg(init = SInt(rstVal(i),width = bitwidth))
}
Also, when new'ing the above (instantiating this module how do I pass the list of reset value in the argument list?
Hoping to get some help on how to write it properly.
The explanation should probably be a bit more thorough, but basically you need to create a Reg of Vec. Something like should do it:
val coeffs = RegInit(rstVal)
In this case, since you already have the Vec of reset values, you can just pass it to the Reg constructor.
I'm assuming that the size of rstVal is equal to ncoeff, otherwise you'll need to reduce the size of rstVal with something like rstVal.take(ncoeff). Also note that I'm using RegInit which is the preferred way to create a register with a reset value.
Let's start with the easy case. This would be much easier if instead of a Vec of SInts your rstVal array was instead a scala collection (Seq, Array, ...) of regular SInt. When possible it is best to save generation of actual hardware until you directly need them. If rstVal contains Int's. Your code would become
val newRstVals = VecInit(Seq.tabulate(ncoeff) { index => rstVals(index).S(bitWidth.W) })
val reg = RegInit(newRstVals)
If you really need to pass in a Vec then the right approach is to create a separate type instance and use the two argument call to RegInit
val vecType = Vec(ncoeff, SInt(bitWidth.W))
val newRstVals1 = VecInit(Seq.tabulate(ncoeff) { index => newRstVals(index) })
val reg = RegInit(vecType, newRstVals1)
There might be problems if the bitWidth you pass in is not big enough to contain the constants you have passed in. You probably should have some checks for that.

Indexing of elements in a Seq of string with chisel

I have, tab=Array(1.U, 6.U, 5.U, 2.U, 4.U, 3.U) and Y=Seq(b,g,g,g,b,g), tab is an array of UInt.
I want to do a map on tab as follows:
tab.map(case idx=>Y(idx))
But I keep getting the error: found chisel3.core.UInt, required Int.
I tried using the function peek() to convert idx to an Int by doing
tab.map(case idx=>Y(peek(idx).toInt)
but I get peek not found. I also saw that I cannot convert a chisel UInt to an Int here but did not understand the use of peek well with the example given. So please, is there another approach to do the above?
Thanks!
The immediate problem is that you cannot access the elements of scala collections using a hardware construct like UInt or SInt. It should work if you wrap Y in a Vec. Depending on your overall module this would probably look like
val YVec = VecInit(Y)
val mappedY = tab.map { case idx => YVec(idx) }

Better way to send data to server

I have two ways in which i can send data(json string) to server.
1)map<key,list>
eg. {"components":["ab","bc","cd"],"values":[1,2,3]}
This represents value of component "ab" is 1.
2) map<key,values>
eg. {"ab":1,"bc":2,"cd":3}
Now above example is of three components but I want to send thousands of components so which one is more scalable in terms of size and performance.
If you feel I missed some details feel free to ask.
Server side you will have to do this if you want value for key "bc":
Option 1: {"components":["ab","bc","cd"],"values":[1,2,3]}
String json = [...] // got json from client
MyJsonObject jo = new Gson().fromJson(json, MyJsonObject.class);
int index = jo.getComponents().indexOf("bc"); // O(n)
int value = jo.getValuess().get(index); // O(1)
Option 2: {"ab":1,"bc":2,"cd":3}
String json = [...] // got json from client
MyJsonObject jo = new Gson().fromJson(json, MyJsonObject.class);
int value = jo.get("bc"); // O(1) ~ O(n)
I believe the option 2 is better because of better performance. Moreover it is simpler and more readable than option 1. Differences in the bandwidth can be neglected.
But you should decide what solution is better for your application.

code generation with Xtend

I am implementing my own DSL and using Xtend to generate C code. I have developed small prototype using XPand/Xtend but now I need to convert prototype into XTend.
In Xpand, I used to define "Generate" function to generate C file but I don't know how can I do similar thing using XTend. Any help in this regard would be highly appreciated.
«DEFINE Generate FOR dsl::defs::module»
«FILE "Com.c" -»
/* DATE «dateString()» */
«EXPAND COM_C::COM_Def_C »
«ENDFILE»
«ENDDEFINE»
Thanks and Regards,
Hemal Bavishi
You could do something like this:
def xtendFunc() '''
/* DATE «dateString()» */
'''
or
def xtendFunc() {
var = '''/* DATE «dateString()» */'''
return var
}
(Assuming the 'dateString()' function is in the same class)
This in Xtend is called using template expressions(Enclosed within three quotes '''...'''). You can contain the result of the function in a val (final variable in Xtend) for the first case. Then use another function for the other template COM_C:COM_Def_C. Append the result into a variable and write into a file using simple java.