I've been banging my head for a bit now trying to figure out why this isn't encrypting properly. Unfortunately, there are not a lot of resources out there for using wincrypt.h. I prefer to use the windows api's over having to use some external library to do the same task. I was able to get MD5 and SHA1 working no problem. But for DES, it compiles ok, however the encryption doesn't encrypt properly.
Perhaps someone can see my error? Working in VC++ 6 environment.
#include <wincrypt.h>
extern HCRYPTPROV hCryptProv;
DWORD dwDataLen = 8;
struct DESContext {
unsigned char digest[9];
unsigned long hHash;
unsigned long hKey;
};
BOOL crypto_startup()
{
CryptAcquireContext(&hCryptProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, 0);
return TRUE;
}
void crypto_wrapup()
{
// Release provider handle
if(hCryptProv) CryptReleaseContext(hCryptProv, 0);
hCryptProv = NULL;
}
void DESInit(struct DESContext *ctx, LPSTR szPassKey)
{
// Hash in the password data.
CryptCreateHash(hCryptProv, CALG_MD5, 0, 0, &ctx->hHash);
CryptHashData(ctx->hHash,szPassKey, strlen(szPassKey), 0);
// Derive a session key from the hash object.
CryptDeriveKey(hCryptProv, CALG_DES, ctx->hHash, 0, &ctx->hKey);
}
void DESUpdate(struct DESContext *ctx, unsigned char *buf)
{
CryptEncrypt(ctx->hKey, 0, FALSE, 0, (LPBYTE)buf, &dwDataLen, lstrlen((const char *)buf));
}
void DESFinal(struct DESContext *ctx)
{
DWORD cb = 20;
CryptGetHashParam(ctx->hHash, HP_HASHVAL, ctx->digest, &cb, 0);
if(ctx->hHash) CryptDestroyHash(ctx->hHash);
ctx->hHash = 0;
}