Windows crypto API

I'm having trouble with a function I made to create a sha1 hash of some strings. The function generates a valid hash for strings longer than 4 chars, but for chars less than that the hash is wrong. I've been looking all over for a solution but I can't see whats wrong.

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;

}

Answers


CryptHashData accepts the length of the data as third parameter, and you pass size of the hash buffer there. You need to pass smth like strlen(plaintext) there.


Need Your Help

PHP Form not showing up in recipient's mailbox

php email scripting forms

My form does not go to recipient when submitted! I changed the file mail.tpl.txt to direct to my own email address as a test and I got the email just fine.

SVK synk and scheduled task

perl svk getpwuid

I'm trying to automate a SVK sync process.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.