我应该使用 wchar 还是 char 来加密?

Should I use wchar or char to encrypt?

本文关键字:加密 char 还是 wchar 我应该      更新时间:2023-10-16

我有这段代码来创建密钥的哈希,以使用 Wincrypt 加密字符串:

wchar_t key[] = L"123456789AFA11";
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: %xn", dwStatus);
CryptReleaseContext(hProv, 0);
system("pause");
return dwStatus;
}
HCRYPTHASH hHash;
if (!CryptCreateHash(hProv, CALG_SHA_256, 0, 0, &hHash)) {      // Note that we will truncate the SHA265 hash to the first 128 bits because we are using AES128.
dwStatus = GetLastError();
printf("CryptCreateHash failed: %xn", dwStatus);
CryptReleaseContext(hProv, 0);
system("pause");
return dwStatus;
}
if (!CryptHashData(hHash, (BYTE*)key_str, len * sizeof(wchar_t), 0)) {
DWORD err = GetLastError();
printf("CryptHashData Failed : %#xn", err);
system("pause");
return (-1);
}

如果我使用 char 而不是 wchar 作为密钥,加密文本完全不同,因为 wchar 是每个字符 2 个字节:

char key[] = "123456789AFA11";
char *key_str = key;
size_t len = lstrlenA(key_str);

DWORD dwStatus = 0;
BOOL bResult = FALSE;
wchar_t info[] = "Microsoft Enhanced RSA and AES Cryptographic Provider";
HCRYPTPROV hProv;
if (!CryptAcquireContextA(&hProv, NULL, info, PROV_RSA_AES, CRYPT_VERIFYCONTEXT)) {
dwStatus = GetLastError();
printf("CryptAcquireContext failed: %xn", dwStatus);
CryptReleaseContext(hProv, 0);
system("pause");
return dwStatus;
}
HCRYPTHASH hHash;
if (!CryptCreateHash(hProv, CALG_SHA_256, 0, 0, &hHash)) {      // Note that we will truncate the SHA265 hash to the first 128 bits because we are using AES128.
dwStatus = GetLastError();
printf("CryptCreateHash failed: %xn", dwStatus);
CryptReleaseContext(hProv, 0);
system("pause");
return dwStatus;
}
if (!CryptHashData(hHash, (BYTE*)key_str, len, 0)) {
DWORD err = GetLastError();
printf("CryptHashData Failed : %#xn", err);
system("pause");
return (-1);
}

我的问题是我应该使用哪个来散列密钥、字符字符串或wchar_t字符串?

还有另一个问题是我的应用程序中的 UTF-8 意味着始终使用字符,而 UTF-16 意味着使用wchar_t?我在Visual Studio 2017中总是使用UNICODE,那么我应该使用wchar,因为WindowsAPI的输出似乎很wchar_t?

我应该使用哪个来散列键、字符字符串或wchar_t字符串?

这是个人选择的问题。 使用适合您需求的任何一种。 加密对原始字节进行操作,它不关心这些字节代表什么。

我的应用程序中的 UTF-8 表示始终使用字符,UTF-16 表示使用wchar_t?

在窗户上,是的。wchar_t在大多数其他平台上不是 2 个字节,所以不是 UTF-16。

我在Visual Studio 2017中总是使用UNICODE,那么我应该使用wchar吗,因为WindowsAPI的输出似乎很wchar_t?

是的,Windows是一个基于Unicode的操作系统,它的大多数基于字符串的API都期望/返回UTF-16。 但加密 API 并不关心这一点。 但是,在您的情况下,您可能应该考虑在加密之前将 UTF-16 转换为 UTF-8,然后在解密后将 UTF-8 转换为 UTF-16。 这样,您的加密数据至少占用更少的存储空间。