C++ プロジェクトに組み込む必要がある CHAP 実装の一部である、一見単純な次の PHP コードがあります。
$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 で exec を実行せずに、PHP で既に行われていることを行うことです。
どこかで文字列に何か問題があるのではないかと思います。