我在创建一些字符串的 sha1 哈希时遇到了问题。该函数为超过 4 个字符的字符串生成一个有效的散列,但对于小于该散列的字符,该散列是错误的。我一直在寻找解决方案,但我看不出有什么问题。
int create_hash(char *plaintext, char *digest) {
char digest_buff[3];
DWORD buf_size = SHA1_HASH_LEN;
HCRYPTPROV prov;
HCRYPTHASH hash;
BYTE rgbHash[SHA1_HASH_LEN];
CHAR rgbDigits[] = "0123456789abcdef";
int i;
if(!CryptAcquireContext(&prov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) {
if(DEBUG) {
printf("CryptAcquireContext failed: %d\n", GetLastError());
}
return SHA1_FAILED;
}
if(!CryptCreateHash(prov, CALG_SHA, NULL, NULL, &hash)) {
if(DEBUG) {
printf("CryptCreateHash failed: %d\n", GetLastError());
}
return SHA1_FAILED;
}
if(!CryptHashData(hash, (BYTE *)plaintext, sizeof(hash), NULL)) {
if(DEBUG) {
printf("CryptHashData failed: %d\n", GetLastError());
}
return SHA1_FAILED;
}
if(!CryptGetHashParam(hash, HP_HASHVAL, rgbHash, &buf_size, NULL)) {
if(DEBUG) {
printf("CryptGetHashParam failed: %d\n", GetLastError());
}
return SHA1_FAILED;
}
for(i=0; i < buf_size; i++) {
sprintf(digest_buff, "%c%c", rgbDigits[rgbHash[i] >> 4], rgbDigits[rgbHash[i] & 0xf]);
strcat(digest, digest_buff);
}
if(!CryptDestroyHash(hash)) {
if(DEBUG) {
printf("CryptDestroyHash failed: %d\n", GetLastError());
}
return SHA1_FAILED;
}
if(!CryptReleaseContext(prov, NULL)) {
if(DEBUG) {
printf("CryptReleaseContext failed: %d\n", GetLastError());
}
return SHA1_FAILED;
}
if(DEBUG) {
printf("digest: %s\n", digest);
}
return 0;
}