SHA256为相同的字符串输入提供不同的结果

时间:2017-12-03 15:30:51

标签: axapta x++ sha256

我有使用SHA256生成哈希码的简单代码,但是,它为同一输入提供了不同的结果。但是,如果我在引号中声明相同的字符串值,例如_input= "test",则返回相同的结果。

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 个答案:

答案 0 :(得分:1)

注意:

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

哈希的输入是_inputString,但长度取自_input,它们不相同。 _inputString!= _input

功能定义:

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

当前代码:

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

Debuggable(semio-pseudo)代码:

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

通过这种方式,可以轻松验证输入和长度。错误的可能性较小,因为_input仅使用一次。

注意:在实践中,我会从inputBytes得到长度,但我不熟悉X ++,所以我没有做出改变。

相关问题