user3697209
user3697209

Reputation: 13

C++ SHA256 is different from command line SHA256

I'm trying to compute a SHA256 hash of the string iEk21fuwZApXlz93750dmW22pw389dPwOkm198sOkJEn37DjqZ32lpRu76xmw288xSQ9

When I run my C++ code, I get a string that's not even a valid SHA256 hash. However, when I run echo -n iEk21fuwZApXlz93750dmW22pw389dPwOkm198sOkJEn37DjqZ32lpRu76xmw288xSQ9 | openssl sha256, I get the correct hash. Here's my C++ code:

#include <iostream>
#include <time.h>
#include <sstream>
#include <string>
#include <iomanip>
#include <typeinfo>
#include <openssl/sha.h>
#include <cstdio>
#include <cstring>

std::string hash256(std::string string) {
    unsigned char digest[SHA256_DIGEST_LENGTH];

    SHA256_CTX ctx;
    SHA256_Init(&ctx);
    SHA256_Update(&ctx, string.c_str(), std::strlen(string.c_str()));
    SHA256_Final(digest, &ctx);

    char mdString[SHA256_DIGEST_LENGTH*2+1];
    for (int i = 0; i < SHA256_DIGEST_LENGTH; i++)
        std::sprintf(&mdString[i*2], "%02x", (unsigned int)digest[i]);

    return std::string(mdString);
}

int main(int argc, char *argv[])
{
    const char *hash = hash256("iEk21fuwZApXlz93750dmW22pw389dPwOkm198sOkJEn37DjqZ32lpRu76xmw288xSQ9").c_str();
    std::cout << hash << std::endl;
    return 0;
}

Another thing to note: When I run my code in an online compiler, such as Coliru, I get the correct hash. I am compiling with G++ on Cygwin with OpenSSL version OpenSSL 1.0.1g 7 Apr 2014

Upvotes: 1

Views: 1489

Answers (1)

Dave S
Dave S

Reputation: 21058

As pointed out by @Alan Stokes, you have Undefined Behavior due to a dangling reference to the internal structure of the string. Change your declaration of hash in main:

std::string hash = hash256("...");

Upvotes: 1

Related Questions