在C++中实现SHA-256

Implementing SHA-256 in C++

本文关键字:SHA-256 实现 C++      更新时间:2023-10-16

我正在尝试在MSVC++中实现SHA-256。除了将消息调度数组的前16个字扩展到剩下的48个字之外,我几乎做到了。我已经确定我的问题是在这一点上,因为它与nist.gov中的示例完全匹配,直到压缩算法的第17轮。我的消息时间表代码如下:

//Extend first 16 words into the remaining 48 words of the message schedule array:
for (int k = 16; k < 64; k++)
{
    bitset<32> s0 = rotr(W[k - 15], 7) ^= rotr(W[k - 15], 18) ^= (W[k - 15] >> 3);
    bitset<32> s1 = rotr(W[k - 2], 17) ^= rotr(W[k - 2], 19) ^= (W[k - 2] >> 10);
    W[k] = add(add(W[k - 16], s0), add(W[i - 7], s1));
}
bitset<32> add(bitset<32> a, bitset<32> b)
{
    unsigned long c = a.to_ulong();
    unsigned long d = b.to_ulong();
    return bitset<32>((c + d) % 4294967296);
}
bitset<32> rotr(bitset<32> b, int num)
{
    int temp = (int)b.to_ulong();
    temp = _rotr(temp, num);
    return bitset<32> (temp);
}

其中W[0.15]是填充消息的副本(与示例匹配)。有人看到问题了吗?完整的代码在这里。大约有170行。

这个问题已经很老了,但它还没有得到回答或关闭,所以我认为答案仍然是受欢迎的

将消息调度数组的前16个字扩展到剩下的48个字中,您可能是想让对add函数的第三次调用读取add(W[k-7], s1)而不是add(W[i-7], s1)

对于前7个块,数组索引i-7小于零。