Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025 #include "DcCrypto.h"
00026
00027 #define NUM_OF_DIGITS 10
00028 #define NUM_OF_LETTERS 26
00029
00030 HCRYPTPROV CdcCrypto::hProv;
00031
00032 void CdcCrypto::Init ()
00033 {
00034
00035 if (!CryptAcquireContext (&hProv, NULL, NULL, PROV_RSA_FULL,
00036 CRYPT_VERIFYCONTEXT))
00037 throw CdcException ("Cannot get a handle to the default provider.");
00038
00039 }
00040
00041
00042 void CdcCrypto::Destroy ()
00043 {
00044 CryptReleaseContext (hProv, 0);
00045 }
00046
00047
00048 CdcString CdcCrypto::GetRandomString (int len)
00049 {
00050 if (len >= BUFF_LEN) len = BUFF_LEN - 1;
00051 unsigned char temp [BUFF_LEN];
00052
00053
00054 if (!CryptGenRandom (hProv, len, temp))
00055 throw CdcException ("Cannot generate random string.");
00056
00057
00058 for (int i = 0; i < len; ++i)
00059 {
00060 temp[i] = temp[i] % ((NUM_OF_LETTERS * 2) + NUM_OF_DIGITS);
00061 if (temp[i] < NUM_OF_DIGITS) temp[i] += '0';
00062 else if (temp[i] < (NUM_OF_DIGITS + NUM_OF_LETTERS))
00063 temp[i] += 'A' - NUM_OF_DIGITS;
00064 else temp[i] += 'a' - (NUM_OF_DIGITS + NUM_OF_LETTERS);
00065 }
00066
00067 temp[len] = '\0';
00068 return CdcString ((char*)temp);
00069 }
00070
00071 CdcString CdcCrypto::MakeHash (const CdcString& buff)
00072 {
00073 HCRYPTHASH hHash = 0;
00074
00075
00076 if (!CryptCreateHash (hProv, CALG_MD5, 0, 0, &hHash))
00077 throw CdcException ("Cannot create hash object.");
00078
00079
00080 if (!CryptHashData (hHash, (unsigned char*)buff.GetBuffer (),
00081 buff.GetLength (), 0))
00082 throw CdcException ("Cannot put the buffer into hash object.");
00083
00084
00085 unsigned char hash_buff [BUFF_LEN];
00086 DWORD len = BUFF_LEN;
00087 if (!CryptGetHashParam (hHash, HP_HASHVAL, hash_buff, &len, 0))
00088 throw CdcException ("Cannot read the hash value.");
00089
00090
00091 if (hHash) CryptDestroyHash(hHash);
00092
00093
00094 CdcString hex_hash;
00095 char temp[10];
00096 for (int i = 0; i < len; ++i)
00097 {
00098 sprintf (temp, "%2x", hash_buff[i]);
00099 if (temp[0] == ' ') temp[0] = '0';
00100 hex_hash += temp;
00101 }
00102 return hex_hash;
00103 }