我对以下代码(使用已知密钥解密文件)有问题:
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <wincrypt.h>
void error(const char *what) {
fprintf(stderr, "%s failed with last error 0x%x\n", what, GetLastError());
exit(1);
}
#define AES_KEY_SIZE 32
typedef struct {
BLOBHEADER hdr;
DWORD dwKeySize;
BYTE rgbKeyData[AES_KEY_SIZE];
} AES256KEYBLOB;
BYTE *hex2byte(const char *hex) {
int len = strlen(hex) / 2;
BYTE *bytes = malloc(len);
if (bytes == NULL) {
error("malloc");
return NULL;
}
unsigned char val[2];
for (int i = 0; i < len; i++) {
sscanf(&hex[i * 2], "%2hhx", &val);
bytes[i] = val[0];
}
return bytes;
}
int main(int argc, char *argv[]) {
if (argc != 3) {
fprintf(stderr, "Usage: %s <input_file> <output_file>\n", argv[0]);
return 1;
}
BYTE *key = hex2byte("c2ecf7a4f3d1620f18cd38379269948fcd3aaf4fdce6d50d310464ea823a");
AES256KEYBLOB aes256KeyBlob;
aes256KeyBlob.hdr.bType = PLAINTEXTKEYBLOB;
aes256KeyBlob.hdr.bVersion = CUR_BLOB_VERSION;
aes256KeyBlob.hdr.reserved = 0;
aes256KeyBlob.hdr.aiKeyAlg = CALG_AES_256;
aes256KeyBlob.dwKeySize = AES_KEY_SIZE;
memcpy(aes256KeyBlob.rgbKeyData, key, AES_KEY_SIZE);
HCRYPTPROV hProv;
if (!CryptAcquireContextA(&hProv, NULL, MS_ENH_RSA_AES_PROV_A, PROV_RSA_AES, CRYPT_VERIFYCONTEXT)) {
error("CryptAcquireContext");
}
HCRYPTKEY hKey;
if (!CryptImportKey(hProv, (BYTE *) &aes256KeyBlob, sizeof(AES256KEYBLOB), 0, CRYPT_EXPORTABLE, &hKey)) {
CryptReleaseContext(hProv, 0);
error("CryptImportKey");
}
DWORD numBytes = 0;
if (!CryptEncrypt(hKey, 0, TRUE, 0, NULL, &numBytes, 0)) {
error("CryptEncrypt");
}
FILE *input_file = fopen(argv[1], "rb");
if (!input_file) {
perror("Error opening input file");
return 1;
}
FILE *output_file = fopen(argv[2], "wb");
if (!output_file) {
perror("Error opening output file");
fclose(input_file);
return 1;
}
BYTE blk[numBytes];
while (fread(blk, 1, numBytes, input_file) == numBytes) {
if (!CryptDecrypt(hKey, 0, TRUE, 0, blk, &numBytes)) {
//error("CryptDecrypt");
}
fwrite(blk, 1, numBytes, output_file);
}
free(key);
CryptDestroyKey(hKey);
CryptReleaseContext(hProv, 0);
fclose(input_file);
fclose(output_file);
return 0;
}
这段代码可以工作,但我必须注释错误判断行:
//error("CryptDecrypt");
我try 按照其他堆栈溢出解决方案中的建议增加缓冲区大小,但无济于事. 我不太关心,因为代码可以工作,但我希望了解其中的原因以及如何避免它. 请注意,如果我使用:
CryptDecrypt(hKey, 0, FALSE, 0, blk, &numBytes)
我没有得到错误,但它只对第一个块起作用.
请不要将此标记为副本,因为所有解决方案都不起作用.