2
votes

I have simple code to generate hash code using SHA256, however, it gives different result for the same input. However, if I declare the same string value in quotes for example _input= "test" then it returns the same result.

public static System.String generateKey(System.String _input)
{
     System.Byte[] convertedArr;
     SHA256Managed sh = new System.Security.Cryptography.SHA256Managed();
        convertedArr = sh.ComputeHash(System.Text.Encoding::UTF8.GetBytes(_inputString),0, System.Text.Encoding::UTF8.GetByteCount(_input));
        hashCode = System.Convert::ToBase64String(convertedArr);
    return hashCode;
    }
1
What's the value of _input? - aaron
Please show more of your code - what is input, FNSGenerateHashDetails etc - DAXaholic
Please don't tag c# if you are not using it. - Camilo Terevinto
Does FNSGenerateHashDetails maybe add some "salt" to the hash input? - Martin Ullrich
When you embed function calls in a function call it becomes much harder to debug. Use intermediate variables, any decent compiler will reduce the code. Write code for human understandability and debugging. Finally provide a minimal reproducible example, add this to the question alonf with text values and intermediate values such as the result of FNSGenerateHashDetails::GetBytes and System.Text.Encoding::UTF8.GetByteCount. Terse and to debug code is not leet. - zaph

1 Answers

1
votes

Note:

convertedArr = sh.ComputeHash(System.Text.Encoding::UTF8.GetBytes(_inputString),0, System.Text.Encoding::UTF8.GetByteCount(_input));

The input to the hash is _inputString but the length is taken from _input, they are not the same. _inputString != _input.

The function defintion:

public static System.String generateKey(System.String _input)

Current code:

convertedArr = sh.ComputeHash(System.Text.Encoding::UTF8.GetBytes(_inputString),0, System.Text.Encoding::UTF8.GetByteCount(_input));

Debuggable (semio-pseudo) code:

inputBytes  = System.Text.Encoding::UTF8.GetBytes(_input)
inputLength = System.Text.Encoding::UTF8.GetByteCount(_input)
hashBytes   = convertedArr = sh.ComputeHash(inputBytes, 0, inputLength);

With this the input and length can easily be verified. The chance of the error is less because _input is only used once.

Note: In practice I would get the length from inputBytes but I am not fluent in X++ so I did not make that change.