我有這個C++在Visual Studio中開發計劃,其中應打印出給定的字符串的SHA1和MD5哈希值:SHA1功能給人怪異的輸出
#include "stdafx.h"
#include <iostream>
#include <ctime>
#include "windows.h"
#include "conio.h"
#include "wincrypt.h"
char Buf [256];
DWORD BufSize;
LPSTR CreateHash(LPSTR tohash, ALG_ID alg)
{
HCRYPTPROV hProv;
HCRYPTHASH hash;
if (CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL,
CRYPT_VERIFYCONTEXT))
{
if (CryptCreateHash(hProv, alg, 0, 0, &hash))
{
if (CryptHashData(hash, (BYTE *)&tohash, sizeof(tohash), 0))
{
ZeroMemory(&Buf, sizeof(Buf));
BufSize = sizeof(Buf);
if (!CryptGetHashParam(hash, HP_HASHVAL,
(BYTE *) &Buf, &BufSize, 0))
printf("Call to CryptGetHashParam failed. Error: %d\n",
GetLastError());
} else printf("Call to CryptHashData failed. Error: %d\n",
GetLastError());
if (!CryptDestroyHash(hash))
printf("Call to CryptDestroyHash failed. Error: %d\n",
GetLastError());
} else printf("Call to CryptCreateHash failed. Error: %d\n",
GetLastError());
if (!CryptReleaseContext(hProv, 0))
printf("Call to CryptReleaseContext failed. Error: %d\n",
GetLastError());
} else printf("Call to CryptAcquireContext failed. Error: %d\n",
GetLastError());
return Buf;
}
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
cout << "SHA hash: " << CreateHash("Visual C++", CALG_SHA)<<endl;
cout << "MD5 hash: " << CreateHash("Visual C++", CALG_MD5)<<endl;
system("pause");
}
它編譯,但是當我運行它,它顯示了怪異輸出。
輸出應該
SHA hash: 0e4abc18f9fb9d8d6d39f047dc20fbebd4a975bd
MD5 hash: f3be2f04531a477a4bb755f9f42c6f2e
但它打印
SHA hash: ü©á*ÀªvÍŒe²5Ê¥Å?•Â
MD5 hash: òù%•þîOú°b>«’
爲什麼?
我該如何解決這個問題?
它的原始輸出爲字節而不是十六進制。 – towr
除非需要支持XP,否則應該使用[下一代加密](http://msdn.microsoft.com/en-us/library/windows/desktop/aa376210(v = vs.85).aspx) API更容易和更安全地使用,並暴露更多的算法。 – Mgetz
@towr如何將原始輸出轉換爲十六進制輸出? – user3099950