我正在尝试用cryptopp :: SHA256替换MS SHA256Managed函数。 这是C#代码
internal byte[] GenerateKey(byte[] keySeed, Guid keyId)
{
byte[] truncatedKeySeed = new byte[30];
Array.Copy(keySeed, truncatedKeySeed, truncatedKeySeed.Length);
Console.WriteLine("Key Seed");
foreach (byte b in truncatedKeySeed)
{
Console.Write("0x" + Convert.ToString(b, 16) + ",");
}
Console.WriteLine();
//
// Get the keyId as a byte array
//
byte[] keyIdAsBytes = keyId.ToByteArray();
SHA256Managed sha_A = new SHA256Managed();
sha_A.TransformBlock(truncatedKeySeed, 0, truncatedKeySeed.Length, truncatedKeySeed, 0);
sha_A.TransformFinalBlock(keyIdAsBytes, 0, keyIdAsBytes.Length);
byte[] sha_A_Output = sha_A.Hash;
Console.WriteLine("sha_a:" + sha_A_Output.Length);
foreach (byte b in sha_A_Output)
{
Console.Write("0x" + Convert.ToString(b, 16) + ",");
}
Console.WriteLine();
.....
}
输出结果:
关键种子 0x5d,0x50,0x68,0xbe,0xc9,0xb3,0x84,0xff,0x60,0x44,0x86,0x71,0x59,0xf1,0x6d,0x6b,0x75,0x55,0x44,0xfc,0xd5,0x11,0x69,0x89,0xb1, 0xac,0xc4,0x27,0x8e,均为0x88
密钥ID 0x39,0x68,0xe1,0xb6,0xbd,0xee,0xf6,0x4f,是0xAB,0x76,0x8d,0x48,0x2d,0x8d,0x2B访问,的0x6A,
sha_a:32 0x7b,0xec,值为0x8F,0x1b,0x60,0x4e,0xb4,0xab,0x3b,0XB,0xbd,0xb8,0x71,0xd6,0xba,0x71,0xb1,0x26,0x41,0x7d,0x99,0x55,0xdc,为0x8E,0x64, 0x76,0x15,0x23,0x1b,是0xAB,0x76,0x62,
Crypto ++的替换功能如下:
byte key_seed[] = { 0x5D, 0x50, 0x68, 0xBE, 0xC9, 0xB3, 0x84, 0xFF, 0x60, 0x44, 0x86, 0x71, 0x59, 0xF1, 0x6D, 0x6B, 0x75, 0x55, 0x44, 0xFC,0xD5, 0x11, 0x69, 0x89, 0xB1, 0xAC, 0xC4, 0x27, 0x8E, 0x88 };
byte key_id[] = { 0x39,0x68,0xe1,0xb6,0xbd,0xee,0xf6,0x4f,0xab,0x76,0x8d,0x48,0x2d,0x8d,0x2b,0x6a };
byte truncated_key_seed[sizeof(key_seed)];
memset( truncated_key_seed,0,sizeof(truncated_key_seed));
memcpy( key_seed, truncated_key_seed, sizeof(key_seed) );
byte output[SHA256::DIGESTSIZE];
memset(output,0,sizeof(output));
SHA256 sha_a;
sha_a.Update(truncated_key_seed,sizeof(key_seed));
sha_a.Update(key_id,sizeof(key_id));
sha_a.Final(output);
printf("size:%lu\n",sizeof(output));
PrintHex(output,sizeof(output));
但是输出哈希值是 DB 36 C9 F6 F7 29 6D 6F 52 21 DA 9F 55 1D AE BC 3E 5A 15 DF E1 37 07 EE 8F BC 73 61 5F D6 E1 C3 与C#的sha_a结果不同。
从MSDN和Cryptopp reference,SHA256Managed :: TransformBlock和SHA256Managed :: TransformFinalBlock对Cryptopp :: Update和Cryptopp :: Final做了同样的事情。
SHA256Managed和cryptopp :: SHA256之间有什么区别导致这个结果?
答案 0 :(得分:0)
看起来像你的代码中的错误。
sha_a.Update(truncated_key_seed,sizeof(key_seed));
确保truncated_key_seed
在两个版本中都相同,尤其是原始key_seed
中未包含的字节......