0

I'm trying to build an app that will call a contract from javascript. I want the contract to validate that the parameters weren't tampered with. In order to do that, my plan was to figure out the parameters server-side, hash the combination of parameters, and sign the hash. I'd pass the hash and signature along to the contract for the contract to validate. The hash would prove the parameters haven't changed and the signature would prove that I generated the hash.

I'm currently trying to figure out the hashing part.

void Main()
{
    var bytes = ASCIIEncoding.ASCII.GetBytes("abc");

    SHA256 hasher = SHA256Cng.Create();
    var hashed = hasher.ComputeHash(bytes);
    Console.WriteLine(BitConverter.ToString(hashed).Replace("-", string.Empty));
}

gives me an output of BA7816BF8F01CFEA414140DE5DAE2223B00361A396177A9CB410FF61F20015AD

On the other side of the fence I have

pragma solidity 0.4.18;    

contract HashCheck {    
    function hash(bytes32 toHash) public returns(bytes32) {
        bytes32 hashed = sha256(toHash);
        return hashed;        
    }
}

which returns

truffle(development)> f.hash.call("abc")
'0x26426d7cb06a12643ccfe84107603083d835c37f000a12f734137a0c8df77f26'

I'm happy to try out keccak (sha3) hashing but I haven't figured out how to do that in C# yet.

0

Your function accepts bytes32, which is 32 bytes long. But in C#, you're only hashing 3 bytes. In C#, you need to right pad zeros to make the length 32.

  • Nice! That was it (except it's actually right-padded with nulls '\0' rather than zeroes). var abcBytes = ASCIIEncoding.ASCII.GetBytes("abc".PadRight(32, '\0')); – Luke Schoen Jan 14 '18 at 1:30
  • '\0' is the character representation of the byte value 0, so those are one and the same. (If you pad the string, you need to use characters. If you pad the bytes, you need bytes.) – user19510 Jan 14 '18 at 1:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.