Quote Originally Posted by Steve Grant View Post
@Tanner: As always you are a wise man. Point taken!

@Passel: Yes I am on AMD.

I don't need this function, I was just curious. Now I've just done a forum search and find that Ben has submitted this in the past and been rebuked for his not doing the job properly. I feel like a fool.
Have you checked for the actual API level error yet? You CLAIMED you were going to do so, but have not yet posted it here. PLEASE DO SO. It will help me to figure out EXACTLY why the default crypto provider failed to allow for random number generation (or why it failed to even get a crypto provider, if in fact it didn't get one).


Until that's figured out though. Here's the revised code, which does not depend on getting a default crypto provider, but rather explicitly specifies one by name. In this case, it's the Microsoft Base crypt provider.

Code:
Private Declare Function CryptAcquireContext Lib "advapi32.dll" Alias "CryptAcquireContextA" (ByRef phProv As Long, ByVal pszContainer As String, ByVal pszProvider As String, ByVal dwProvType As Long, ByVal dwFlags As Long) As Long
Private Declare Function CryptReleaseContext Lib "advapi32.dll" (ByVal hProv As Long, ByVal dwFlags As Long) As Long
Private Declare Function CryptGenRandom Lib "advapi32.dll" (ByVal hProv As Long, ByVal dwLen As Long, ByRef pbBuffer As Any) As Long

Private Declare Sub Sleep Lib "kernel32.dll" (ByVal dwMilliseconds As Long)

Private Const BaseProvider As String = "Microsoft Base Cryptographic Provider v1.0"
Private Const EnhancedProvider As String = "Microsoft Enhanced Cryptographic Provider v1.0"
Private Const StrongProvider As String = "Microsoft Strong Cryptographic Provider"




Dim hProv As Long
Dim Quit As Boolean

Private Sub Form_Load()
    Dim a As Long
    CryptAcquireContext hProv, vbNullString, BaseProvider, 1, 0
    
    If hProv = 0 Then
        Unload Me
        Exit Sub
    End If
    
    Show
    Do Until Quit
        CryptGenRandom hProv, 4, a
        Cls
        Print a
        Sleep 100
        DoEvents
    Loop

End Sub

Private Sub Form_Unload(Cancel As Integer)
    Quit = True
    If hProv Then CryptReleaseContext hProv, 0
End Sub
Just copy and paste this code into your form. and make sure your form's AutoRedraw property is set to True.

If for some reason the Base provider isn't working, go to the line that says
Code:
CryptAcquireContext hProv, vbNullString, BaseProvider, 1, 0
and change BaseProvider to either EnhancedProvider or StrongProvider.