修改哈希函数

Modifying hash function

我需要修改散列码,这样我得到的不是 256 位散列值,而是遵循从 ula 代替 256 位散列值的规则。

h=A||B||C||D||E||F||G||H

其中 ABDEFGH 为 32 位话说,|| concat 操作。我必须使用公式

接收 64 位哈希
 h=B xor D xor F xor H || A xor C xor E xor G.

我正在使用以下 Sha256 实现,但我无法找到必须完成此操作的部分 - http://www.zedwood.com/article/cpp-sha256-function

sha应该是这样的

SHA-256("10301231030456") = 0xe4a6aade78b1c5ad21a76adca6beb75634c1ff45e7aba9d18f861211d43d69e1

目标是获得:

SHA-256-mod("10301231030456") = 0xed99b2cb7e462d56

谢谢

尝试将 256 位数组转换为 unsigned long mod_args[8];

std::string sha = sha256("10301231030456");

char hash[32];

for (int i = 0, j = 0; i < sha.length(); i += 2, j++)
{
    std::string sub = sha.substr(i, 2);
    hash[j] = strtoul(sub.c_str(), NULL, 16);
}

unsigned long mod_args[8];
memcpy(mod_args, hash, 32);

比获得 2 块 64 位:

unsigned long a = mod_args[1] ^ mod_args[3] ^ mod_args[5] ^ mod_args[7];
unsigned long b = mod_args[0] ^ mod_args[2] ^ mod_args[4] ^ mod_args[6]; 

比通过连接那两块得到结果

unsigned long long result = (((unsigned long long)a) << 32) | b;

unsigned long long result = (((unsigned long long)b) << 32) | a;

考虑哪个散列必须更旧 ab

完整的解决方案是:

#define B_OLDER_THAN_A

int main()
{
    std::string sha = sha256("10301231030456");

    char hash[32];

    for (int i = 0, j = 0; i < sha.length(); i += 2, j++)
    {
        std::string sub = sha.substr(i, 2);
        hash[j] = strtoul(sub.c_str(), NULL, 16);
    }

    unsigned long mod_args[8];
    memcpy(mod_args, hash, 32);

    unsigned long a = mod_args[1] ^ mod_args[3] ^ mod_args[5] ^ mod_args[7];
    unsigned long b = mod_args[0] ^ mod_args[2] ^ mod_args[4] ^ mod_args[6];

#ifdef B_OLDER_THAN_A
    unsigned long long result = (((unsigned long long)b) << 32) | ((unsigned long long)a);
#else
    unsigned long long result = (((unsigned long long)a) << 32) | ((unsigned long long)b);
#endif

    unsigned char output[8] = { 0 };

    memcpy(output, (char*)(&result), 8);

    for (int i = 0; i < 8; i++)
        std::cout << setfill('0') << setw(2) << hex << (unsigned int)(output[i]);

    std::cout << endl;


    return 0;
}