我有一个正在运行的程序,该程序使用wincrypt.h
中的AES128加密9字节的字符串,但是当我更改密钥的最后一个字符时会发生一些奇怪的事情:
从L"3igcZhRdWq96m3GUmTAiv2"
到例如L"3igcZhRdWq96m3GUmTAiv1"
或L"3igcZhRdWq96m3GUmTAiv9"
加密的文本仍然彼此相同。
#include <Windows.h>
#include <wincrypt.h>
#include <stdio.h>
#pragma comment(lib, "crypt32.lib")
#define BUFFER_SIZE 16
//params: <input file> <output file> <is decrypt mode> <key>
int wmain()
{
wchar_t key[] = L"3igcZhRdWq96m3GUmTAiv2";
wchar_t *key_str = key;
size_t len = lstrlenW(key_str);
DWORD dwStatus = 0;
BOOL bResult = FALSE;
wchar_t info[] = L"Microsoft Enhanced RSA and AES Cryptographic Provider";
HCRYPTPROV hProv;
if (!CryptAcquireContextW(&hProv, NULL, info, PROV_RSA_AES, CRYPT_VERIFYCONTEXT)) {
dwStatus = GetLastError();
printf("CryptAcquireContext failed: %x\n", dwStatus);
CryptReleaseContext(hProv, 0);
system("pause");
return dwStatus;
}
HCRYPTHASH hHash;
if (!CryptCreateHash(hProv, CALG_SHA_256, 0, 0, &hHash)) {
dwStatus = GetLastError();
printf("CryptCreateHash failed: %x\n", dwStatus);
CryptReleaseContext(hProv, 0);
system("pause");
return dwStatus;
}
if (!CryptHashData(hHash, (BYTE*)key_str, len, 0)) {
DWORD err = GetLastError();
printf("CryptHashData Failed : %#x\n", err);
system("pause");
return (-1);
}
printf("[+] CryptHashData Success\n");
HCRYPTKEY hKey;
if (!CryptDeriveKey(hProv, CALG_AES_128, hHash, 0, &hKey)) {
dwStatus = GetLastError();
printf("CryptDeriveKey failed: %x\n", dwStatus);
CryptReleaseContext(hProv, 0);
system("pause");
return dwStatus;
}
printf("[+] CryptDeriveKey Success\n");
const size_t string_size = BUFFER_SIZE;
BYTE string[string_size] = { "Fooooooo" };
DWORD out_len = 9;
if (!CryptEncrypt(hKey, NULL, TRUE, 0, string, &out_len, string_size)) {
printf("[-] CryptEncrypt failed\n");
}
for (DWORD i = 0; i < out_len; i++)
printf("%02x ", string[i]);
printf("\n");
printf("%lu\n", out_len);
//printf("%s", string);
//printf("\n");
if (!CryptDecrypt(hKey, NULL, TRUE, 0, string, &out_len)) {
printf("[-] CryptDecrypt failed\n");
}
printf("%lu\n", out_len);
printf("%s", string);
printf("\n");
memset(string, 0, string_size);
CryptReleaseContext(hProv, 0);
CryptDestroyKey(hKey);
CryptDestroyHash(hHash);
printf("Finished\n");
system("pause");
return 0;
}
还请注意,我之前公开的键的SHA256哈希值彼此不同:
3igcZhRdWq96m3GUmTAiv2 -> F5584805AA52AC68062331F3B852001F2585D23105C22D61CF25C3C71D998F9B
3igcZhRdWq96m3GUmTAiv1 -> 25DF6A58974E67ABD2DE6EE29F1A045F87ADCDC05C879235C450D12ABAA549C1
3igcZhRdWq96m3GUmTAiv9 -> AE6FFA99AFF1A72ED31B4A16CE86CE060B1DB3C0ECA3769F27D8891155B1E16D
来源:https://passwordsgenerator.net/sha256-hash-generator/
如果我更改密钥的中间或第一个字符(例如前3个字符)或添加更多字符,则这次加密的文本将按预期方式更改。
你知道为什么会这样吗?如果更改密钥的任何字符,则加密的文本应会更改,但是仅更改最后一个字符不会发生这种情况。
答案 0 :(得分:7)
if (!CryptHashData(hHash, (BYTE*)key_str, len, 0)) {
您正在传递len
,即key_str
的长度,以字符(wchar_t
),而CryptHashData
则期望字节数。这意味着它实际上仅使用key_str
的前半部分(因为wchar_t
在Win32上是2个字节)。
您可以轻松解决此问题:
if (!CryptHashData(hHash, (BYTE*)key_str, len*sizeof(*key_str), 0)) {