修改哈希函数

时间:2016-01-12 15:07:46

标签: c++ hash xor sha256

我需要修改哈希码,这样我就可以得到64位哈希值,而不是256位哈希值。

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

其中ABDEFGH是32位字, ||联合行动。我必须使用公式

接收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

谢谢

1 个答案:

答案 0 :(得分:2)

尝试将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]; 

比通过concat获得结果两件

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;
}