无法将一段代码移植到C ++(CHAP)

时间:2015-03-22 19:58:50

标签: php c++ openssl md5 challenge-response

我有以下看似简单的PHP代码,它是我需要合并到C ++项目中的CHAP实现的一部分:

$response = md5("\0" . hash('sha256', $password) . pack('H32', $challenge);

这是我到目前为止所做的:

// should do what hash('sha256', $password) does
string shaString(const string str)
{
        unsigned char hash[SHA256_DIGEST_LENGTH];
        SHA256_CTX sha256;
        SHA256_Init(&sha256);
        SHA256_Update(&sha256, str.c_str(), str.size());
        SHA256_Final(hash, &sha256);
        stringstream ss;
        for (int i = 0; i < SHA256_DIGEST_LENGTH; i++)
        {
                ss << hex << setw(2) << setfill('0') << (int)hash[i];
        }
        return ss.str();
}

// should do the rest
string md5String(const string password, const string challenge)
{
    int clen = challenge.length() / 2; // should be half length of hex values
    int plen = password.length() + 1;  // add one for null terminating string
    int tlen = clen + plen + 1;
    unsigned char *buffer = (unsigned char *) malloc(tlen);
    unsigned short buf;
    const char *pstr = password.c_str();
    unsigned char digest[MD5_DIGEST_LENGTH];
    MD5_CTX md5;

    memset(buffer, 0, tlen);

    // skip the first byte as we need to start with \0,
    // copy password starting at second byte
    memcpy(buffer + 1, pstr, plen);
    int start = plen + 1;

    // should be equivalent to pack('H32', $challenge)
    for (int j = 0; j < clen; j++) {
        if (scanf((challenge.substr(j * 2, 2)).c_str(), "%hx", &buf) < 1)
            break;
        buffer[start + j] = (unsigned char) buf;
    }

    MD5_Init(&md5);    // md5 what we got so far
    MD5_Update(&md5, buffer, tlen);
    MD5_Final(digest, &md5);
    stringstream ss;
    for (int i = 0; i < MD5_DIGEST_LENGTH; i++)
    {
        ss << hex << setw(2) << setfill('0') << (int)digest[i];
    }

    free(buffer);

    return ss.str();
}

string response = md5String(shaString(password.c_str()), challenge.c_str());

代码运行并生成字符串,但值不正确,我无法确定原因,因为它是加密哈希,很难比较结果。

我觉得我在某个地方做了些蠢事,几个小时都在争吵。任何建议将不胜感激。我的目标只是完成PHP中已经完成的工作,当然不在PHP上运行exec。

我怀疑我在某处对字符串做错了。

0 个答案:

没有答案