C++ CryptGenRandom()函数的使用!急!
我现在的目的很简单,就是想利用这个函数来产生随机数。之前使用Rand()函数,但是发现这个函数并不能产生真正的随机数。求高手用CryptGenRandom函数给个产生随机...
我现在的目的很简单,就是想利用这个函数来产生随机数。之前使用Rand()函数,但是发现这个函数并不能产生真正的随机数。求高手用CryptGenRandom函数给个产生随机数的示例!谢谢!
展开
2个回答
展开全部
从MSDN上给你摘一段吧,没用过
#include <wincrypt.h>
HCRYPTPROV hProv = 0;
HCRYPTKEY hKey = 0;
DWORD dwMode;
BYTE pbData[16];
DWORD dwCount;
DWORD i;
// Get a handle to the user default provider using CryptAcquireContext.
// For sample code, see CryptAcquireContext.
...
...
// Create a random block cipher session key.
if(!CryptGenKey(hProv, CALG_RC2, CRYPT_EXPORTABLE, &hKey)) {
printf("Error %x during CryptGenKey!\n", GetLastError());
goto done;
}
// Set the cipher mode.
dwMode = CRYPT_MODE_ECB;
if(!CryptSetKeyParam(hKey, KP_MODE, &dwMode, 0)) {
printf("Error %x during CryptSetKeyParam!\n", GetLastError());
goto done;
}
// Generate a random initialization vector.
if(!CryptGenRandom(hProv, 8, pbData)) {
printf("Error %x during CryptGenRandom!\n", GetLastError());
goto done;
}
// Set the initialization vector.
if(!CryptSetKeyParam(hKey, KP_IV, pbData, 0)) {
printf("Error %x during CryptSetKeyParam!\n", GetLastError());
goto done;
}
// Use 'hKey' to encrypt a message.
...
done:
// Destroy the session key.
if(hKey != 0) CryptDestroyKey(hKey);
// Free the provider handle.
if(hProv != 0) CryptReleaseContext(hProv, 0);
#include <wincrypt.h>
HCRYPTPROV hProv = 0;
HCRYPTKEY hKey = 0;
DWORD dwMode;
BYTE pbData[16];
DWORD dwCount;
DWORD i;
// Get a handle to the user default provider using CryptAcquireContext.
// For sample code, see CryptAcquireContext.
...
...
// Create a random block cipher session key.
if(!CryptGenKey(hProv, CALG_RC2, CRYPT_EXPORTABLE, &hKey)) {
printf("Error %x during CryptGenKey!\n", GetLastError());
goto done;
}
// Set the cipher mode.
dwMode = CRYPT_MODE_ECB;
if(!CryptSetKeyParam(hKey, KP_MODE, &dwMode, 0)) {
printf("Error %x during CryptSetKeyParam!\n", GetLastError());
goto done;
}
// Generate a random initialization vector.
if(!CryptGenRandom(hProv, 8, pbData)) {
printf("Error %x during CryptGenRandom!\n", GetLastError());
goto done;
}
// Set the initialization vector.
if(!CryptSetKeyParam(hKey, KP_IV, pbData, 0)) {
printf("Error %x during CryptSetKeyParam!\n", GetLastError());
goto done;
}
// Use 'hKey' to encrypt a message.
...
done:
// Destroy the session key.
if(hKey != 0) CryptDestroyKey(hKey);
// Free the provider handle.
if(hProv != 0) CryptReleaseContext(hProv, 0);
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询