views:

274

answers:

1

Hi!

does anyone have working example of CryptGenrRandom class to generate session id (need to use in my iis module).

HCRYPTPROV   hCryptProv;    
BYTE         pbData[16];

if(CryptAcquireContext( &hCryptProv,  NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) 
{       
    if(CryptGenRandom(hCryptProv, 8, pbData)) 
    {
        std::string s(( const char *) pbData);  
        printf(s.c_str());
    }
    else
    {
        MyHandleError("Error during CryptGenRandom.");
    }
}
else
{
    MyHandleError("Error during CryptAcquireContext!\n");
}   

i tried this code but, its not working quite well (i get it from msdn) and this example don't work for me ( http://www.codeproject.com/KB/security/plaintextsessionkey.aspx )

so if anyone know how to generate sessionid using this class plz let me know

tnx anyway!

A: 

You don't say what the failure is - but i'll take a stab at it - we've had problems with CryptAcquireContext in the past returing NTE_BAD_KEYSET -- if it does you need to specify CRYPT_NEWKEYSET or'd into the flags (CRYPT_VERIFYCONTEXT|CRYPT_NEWKEYSET) and call CryptAcquireContext a second time in response to the failure.

Something like:

BOOL bResult = CryptAcquireContext(&m_hProv, pszContainer, pszProvider, dwProviderType, dwFlags);
if (!bResult) 
{
    hr = GetLastError(); //already returns an HRESULT

    if (NTE_BAD_KEYSET != hr) return(hr);

    dwFlags |= CRYPT_NEWKEYSET;
    bResult = CryptAcquireContext(&m_hProv, pszContainer, pszProvider, dwProviderType, dwFlags);
    if (!bResult) return(GetLastError());
}
Ruddy
Problem with code that i posted is that i get strange output (like hexadecimal string, and i don't realy know how to convert that to session string (numbers and alfabet characters), and second problem is that the string is not large inaf (i need 15+ characters output).problem with codeproject's example is that if fails at line pbExportedKeyBlob = new BYTE[dwSize];. Error is "Unhandled exception at 0x7c812afb in SessionExample01.exe: Microsoft C++ exception: std::bad_alloc at memory location 0x0012fe08.."tnx for any helpbye
DoDo
Is there a reason you can't just a GUID? see CoCreateGuid (http://msdn.microsoft.com/en-us/library/ms688568(VS.85).aspx) - it seems that it would be better suited than a random number anyways - you could end up with the same random number session id more than once - a guid is essentially guaranteed to be unique - and its more or less random as well.
Ruddy
@Ruddy: Guids may be predictable, thus may somewhat insecure session ids.
Jennifer Zouak