在C ++和PHP中使用不同的结果HMAC SHA-256

时间:2017-07-26 07:34:07

标签: php c++ openssl sha256 hmac

我将字符串编码为base64并使用此base64字符串生成HMAC SHA256。我将HMAC(char字节)的结果编码为base64。

我使用C ++:openssl库。

在PHP和C ++中获得了不同的结果:

C ++:

JSON: {"req_hash":"someUniqCodeHash","answer":true}

BASE64: eyJyZXFfaGFzaCI6InNvbWVVbmlxQ29kZUhhc2giLCJhbnN3ZXIiOnRydWV9

HMAC: P/p2YlxL8xdhmn+QIAlVLFDS50ai4JE/l1pMMrKZKrE=

PHP:

JSON: {"req_hash":"someUniqCodeHash","answer":true}

BASE64: eyJyZXFfaGFzaCI6InNvbWVVbmlxQ29kZUhhc2giLCJhbnN3ZXIiOnRydWV9

HMAC: P/p2YlxL8xdhmn+QIAlVLFDS50ai4JE/l1pMMrKZKrE=

如果你能看到, HMAC结果相同

c++: P/p2YlxL8xdhmn+QIAlVLFDS50ai4JE/l1pMMrKZKrE=

php: P/p2YlxL8xdhmn+QIAlVLFDS50ai4JE/l1pMMrKZKrE=

但是,当我像这样更改JSON时(将true更改为false

JSON: {"req_hash":"someUniqCodeHash","answer":false}

我得到了这个:

C ++:

JSON: {"req_hash":"someUniqCodeHash","answer":false}

BASE64: eyJyZXFfaGFzaCI6InNvbWVVbmlxQ29kZUhhc2giLCJhbnN3ZXIiOmZhbHNlfQ==

HMAC: znUOWS2MMLpjIBSpq2GfSNivaL8IUDcZXZs24D0=

PHP:

JSON: {"req_hash":"someUniqCodeHash","answer":false}

BASE64: eyJyZXFfaGFzaCI6InNvbWVVbmlxQ29kZUhhc2giLCJhbnN3ZXIiOmZhbHNlfQ==

HMAC: znUOWS2MMLpjIBSpq2GfSNivaL8IUDcZXZs24D0AHZA=

为什么HMAC结果不同?

你可以看到:

C++: znUOWS2MMLpjIBSpq2GfSNivaL8IUDcZXZs24D0=

PHP: znUOWS2MMLpjIBSpq2GfSNivaL8IUDcZXZs24D0AHZA=

在PHP HMAC字符串中添加了一些字符:...AHZA=这是什么?

我的 PHP代码

 <?php
 $b = base64_encode('{"req_hash":"someUniqCodeHash","answer":false}');
 $hmac =$b.".".base64_encode(hash_hmac('sha256',$b,'eyJhZGRyZXNzX3RvIjp7JzEnOidjbGll',true));

我的 C ++代码

std::string sfjson = "{\"req_hash\":\"someUniqCodeHash\",\"answer\":false}";
std::cout << "JSON: " << sfjson << "\n";

std::string fencoded_data = base64_encode_str(sfjson);
std::cout << "BASE64: " << fencoded_data << "\n";

unsigned char* digest;
std::string key = "eyJhZGRyZXNzX3RvIjp7JzEnOidjbGll";

digest = HMAC(EVP_sha256(), reinterpret_cast<const unsigned char*>(key.c_str()), key.length(), reinterpret_cast<const unsigned char*>(fencoded_data.c_str()), fencoded_data.length(), NULL, NULL);

std::string sName(reinterpret_cast<char*>(digest));

std::string hmac_data = base64_encode_str(sName);

std::cout << "HMAC: " << hmac_data << "\n";

从那里开始的Base64:https://gist.github.com/rustem-art/5f6b510c65bbbfd279386225b978f960

1 个答案:

答案 0 :(得分:0)

我找到了解决方案! ;)

永远不要使用NULL作为:

digest = HMAC(EVP_sha256(),
              reinterpret_cast<const unsigned char*>(key.c_str()), key.length(),
              reinterpret_cast<const unsigned char*>(data.c_str()), data.length(),
              NULL, NULL);

使用特殊变量(在我的代码中:diglen和result)作为返回函数。

unsigned int diglen;

unsigned char result[EVP_MAX_MD_SIZE];

digest = HMAC(EVP_sha256(),
              reinterpret_cast<const unsigned char*>(key.c_str()), key.length(),
              reinterpret_cast<const unsigned char*>(data.c_str()), data.length(),
              result, &diglen);