CryptGenRandom windows下生成随机数的函数使用

来源:互联网 发布:开淘宝c店 编辑:程序博客网 时间:2024/05/01 14:08
// test_CryptGenRandom.cpp : 定义控制台应用程序的入口点。
//


#include "stdafx.h"


#include "windows.h"
#include "wincrypt.h"


#include <iostream>
using namespace std;


class CCryptRandom 
{
public:
    BOOL Random(void *lpBuffer,DWORD dwLen);
    CCryptRandom();
    virtual~CCryptRandom();
private:
    HCRYPTPROV hCryptProv;
};


CCryptRandom::CCryptRandom()
{
    hCryptProv=NULL;
    CryptAcquireContext((HCRYPTPROV*)&hCryptProv,NULL,NULL,PROV_RSA_FULL,0);
}


CCryptRandom::~CCryptRandom()
{if(hCryptProv!=NULL)CryptReleaseContext(hCryptProv,0);
}


BOOL CCryptRandom::Random(void *lpBuffer, DWORD dwLen)

    if(hCryptProv==NULL)return FALSE;
    BOOL bRet=CryptGenRandom(hCryptProv,dwLen,(BYTE*)lpBuffer);///reinterpret_cast<LPBYTE>lpBuffer);
    return bRet;
}


int _tmain(int argc, _TCHAR* argv[])
{
    CCryptRandom crypt;
    BYTE byte[MAX_PATH];


    BOOL bReturnValue = crypt.Random(&byte, MAX_PATH);
    for (DWORD i = 0; i < 8; ++i)
        std::cout << std::dec << static_cast<unsigned int>(byte[i]) << std::endl;


return 0;
}
0 0
原创粉丝点击