Keccak256 – How to Pass a String to be Hashed Using Keccak256

bytes32keccaksha3string

I'm trying to do something that in theory is very simple: I want to pass a string like "hello" to a function and then compute the sha3/keccak256 hash.
I think the problem is that if the parameter is a bytes32 (as it is now), the hash function will produce a different output.

How can I get the same hashes with these two methods inside a smart contract? In practice, how to get a return true in the following code?

function someFunction(bytes32 _string) returns(bool){
    bool result = false;
    bytes32 hashparameter = sha3(_string);
    bytes32 hashstring = sha3("hello");
    if(hashstring == hashparameter) {
        result = true;
    }

    return result;

}

How can I truncate the passed bytes32 so that it consider only the first 5 bytes for the sha3?

Thanks for your time, I hope you have the solution. If I'll find something, I'll update the question.

Best Answer

try this snipet

function bytes32ToString(bytes32 x) constant returns (string) {
    bytes memory bytesString = new bytes(32);
    uint charCount = 0;
    for (uint j = 0; j < 32; j++) {
        byte char = byte(bytes32(uint(x) * 2 ** (8 * j)));
        if (char != 0) {
            bytesString[charCount] = char;
            charCount++;
        }
    }
    bytes memory bytesStringTrimmed = new bytes(charCount);
    for (j = 0; j < charCount; j++) {
        bytesStringTrimmed[j] = bytesString[j];
    }
    return string(bytesStringTrimmed);
}

 function someFunction(bytes32 _string) returns(bool){
    bool result = false;
    bytes32 hashparameter = sha3(bytes32ToString(_string));
    bytes32 hashstring = sha3("hello");
    if(hashstring == hashparameter) {
        result = true;
    }

    return result;

}

the first function converts bytes32 to string then passes the result to hashing function. I've tried it gives true for "hello".