Reputation: 31
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;
}
Upvotes: 2
Views: 2095
Reputation: 112875
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.
Upvotes: 1