#include
#include
#include
#pragma comment(lib, "Crypt32.lib")
int main() {
HCRYPTPROV hProv = NULL;
HCRYPTHASH hHash = NULL;
BYTE data[] = "Hello, SHA-256!"; // 数据的示例
// 获取一个加密服务提供者的句柄
if (!CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_AES, CRYPT_VERIFYCONTEXT)) {
std::cerr << "Error in CryptAcquireContext: " << GetLastError() << std::endl;
return 1;
}
// 创建一个哈希对象
if (!CryptCreateHash(hProv, CALG_SHA_256, 0, 0, &hHash)) {
std::cerr << "Error in CryptCreateHash: " << GetLastError() << std::endl;
CryptReleaseContext(hProv, 0);
return 1;
}
// 向哈希对象输入数据
if (!CryptHashData(hHash, data, sizeof(data) - 1, 0)) {
std::cerr << "Error in CryptHashData: " << GetLastError() << std::endl;
CryptDestroyHash(hHash);
CryptReleaseContext(hProv, 0);
return 1;
}
// 获取哈希值
BYTE hashValue[32]; // SHA-256 哈希值是 32 字节长度
DWORD hashSize = sizeof(hashValue);
if (!CryptGetHashParam(hHash, HP_HASHVAL, hashValue, &hashSize, 0)) {
std::cerr << "Error in CryptGetHashParam: " << GetLastError() << std::endl;
} else {
std::cout << "SHA-256 Hash Value: ";
for (int i = 0; i < sizeof(hashValue); i++) {
printf("%02x", hashValue[i]);
}
std::cout << std::endl;
}
// 清理资源
CryptDestroyHash(hHash);
CryptReleaseContext(hProv, 0);
return 0;
}