#include <iostream>
#include <string>
#include <windows.h>
#include <windef.h>
#include <wincrypt.h>
using namespace std;
#define RANDOM_NUM 1 ///< 每次获取短信验证码随机数个数, 目前取值只能用1,每次取一个随机数
#define RANDOM_NUM_LENGTH 4 ///< 短信验证码长度
#define SMS_MAX_SENDTIMES 5 ///< 同类型的短信验证码每天可发送的次数
class CCryptRandom
{
public:
CCryptRandom();
virtual~CCryptRandom();
BOOL Random(void *lpBuffer,DWORD dwLen)
{
if(hCryptProv==NULL)
return FALSE;
BOOL bRet = CryptGenRandom(hCryptProv, dwLen, (BYTE*)lpBuffer);///reinterpret_cast<LPBYTE>lpBuffer);
return bRet;
}
private:
HCRYPTPROV hCryptProv;
};
CCryptRandom::CCryptRandom()
{
hCryptProv=NULL;
if(!CryptAcquireContext(&hCryptProv, 0, 0, PROV_RSA_FULL, CRYPT_DELETEKEYSET))
{
cout << "Err: CryptAcquireContext(CRYPT_DELETEKEYSET),dwErr = " << GetLastError() << endl;
}
if(!CryptAcquireContext(&hCryptProv, 0, 0, PROV_RSA_FULL, CRYPT_NEWKEYSET))
{
cout << "Err: CryptAcquireContext(CRYPT_NEWKEYSET),dwErr = " << GetLastError() << endl;
}
}
CCryptRandom::~CCryptRandom()
{
if (hCryptProv != NULL)
{
CryptReleaseContext(hCryptProv, 0);
}
}
int main()
{
CCryptRandom obj;
int i = 0;
while (i < 10000)
{
///< 产生验证码
BYTE byte[RANDOM_NUM];
BOOL bRet = obj.Random(&byte, RANDOM_NUM);
char buf[MAX_PATH] = {0};
sprintf(buf, "%08d", static_cast<unsigned int>(byte[0] * 100.00 / 255 * 10000) % 10000);
string strRandNum = buf;
strRandNum = strRandNum.substr(strRandNum.length() - RANDOM_NUM_LENGTH, RANDOM_NUM_LENGTH);
cout << strRandNum << '\t';
i++;
}
return 0;
}
产生短信验证码
最新推荐文章于 2024-03-18 11:45:40 发布