Von C nach Java, Teil 4: Datenkompression und Verschlüsselung

Seite 9: Listing 5

Inhaltsverzeichnis
int    processBlock(PBP_S pbp_s) {
DWORD dwTid;

/**
* given is the inputBlock with inputSize bytes length
* and an outputBlock which is at least allocated with 2 times
* of inputSize length the processed outputBlock length will
* be returned in *outputSize
*/
int ret, outputSize=2*pbp_s->inputSize;
uchar *outputBlock=malloc(outputSize);

if ((ret=compress2(outputBlock, (ulong *)&outputSize,
pbp_s->inputBlock, pbp_s->inputSize,
Z_BEST_COMPRESSION))!=Z_OK) {
fprintf(stderr,"compress2() returned %d and failed\n",ret);
return -1;
}
if (isCrypt) {
#ifdef WIN32
/**
* to be thread - safe it is necessary to initialize an
* own context for each thread
*/
bool bResult;
DWORD dwSize;
HCRYPTPROV hProv;
HCRYPTHASH hHash;
HCRYPTKEY hKey;

if (!CryptAcquireContext(&hProv, NULL, MS_DEF_PROV,
PROV_RSA_FULL, 0)) {
fprintf(stderr,"CryptAcquireContext() FAILED!\n");
return -1;
}
if (!CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash)) {
fprintf(stderr,"CryptCreateHash() FAILED!\n");
return -1;
}
if (!CryptHashData(hHash, passwd, strlen(passwd), 0)) {
fprintf(stderr,"CryptHashData() FAILED!\n");
return -1;
}
if (!CryptDeriveKey(hProv, CALG_RC4, hHash,
CRYPT_EXPORTABLE, &hKey)) {
fprintf(stderr,"CryptDeriveKey() FAILED!\n");
return -1;
}
dwSize=outputSize;
if (!CryptEncrypt(hKey, 0, TRUE, 0, NULL, &dwSize, outputSize)) {
fprintf(stderr,"CryptEncrypt(1) FAILED!\n");
return -1;
}
if (!CryptEncrypt(hKey, 0, TRUE, 0, outputBlock, &dwSize, dwSize)) {
fprintf(stderr,"CryptEncrypt(2) FAILED!\n");
return -1;
}
outputSize=dwSize;
CryptDestroyKey(hKey);
CryptDestroyHash(hHash);
CryptReleaseContext(hProv, 0);
#endif
}
pbp_s->outputBlock=outputBlock;
pbp_s->outputSize=outputSize;
if (CreateThread((LPSECURITY_ATTRIBUTES)NULL,0,
(LPTHREAD_START_ROUTINE)flushBlockToFile,(LPVOID)pbp_s,0,
&dwTid)==NULL) {
fprintf(stderr,"CreateThread(flushBlockToFile()) failed!\n");
fclose(pbp_s->ofp);
return -1;
}
free(pbp_s->inputBlock);
WaitForSingleObject(blocksWrittenMutex, INFINITE);
threadActiveCount--;
ReleaseMutex(blocksWrittenMutex);
return 0;
}