Fog Creek Software
Discussion Board




ASP components trouble with Windows API

I can't get getBytes to return anything..

' -- This is clsStrongRNG

Option Explicit
Private Const PROV_RSA_FULL = 1
Private Const CRYPT_NEWKEYSET = &H8
Private Const MS_DEF_PROV = "Microsoft Enhanced Cryptographic Provider v1.0"
Private Const API_ERROR = 0

Private Declare Function CryptAcquireContext Lib "advapi32.dll" Alias "CryptAcquireContextA" ( _
    phProv As Long, ByVal pszContainer As Long, 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, _
    ByVal pbBuffer As String) As Long

Private Declare Function GetLastError Lib "kernel32" () As Long

Public Function getBytes(lngSaltLen As Variant) As Variant
    On Error GoTo getSaltError
    Dim lngCryptContextHandle As Long
    Dim lngReturnCode As Long
    Dim strTemp As String
    Dim strProvider As String
    strTemp = 0&
    strProvider = MS_DEF_PROV & vbNullChar
    Dim strBuffer As String
    getBytes = ""
    lngSaltLen = Abs(lngSaltLen)
    strBuffer = String(lngSaltLen, vbNull)
    If Not CBool(CryptAcquireContext(lngCryptContextHandle, strTemp, strProvider, PROV_RSA_FULL, 0)) Then
        If GetLastError = 0 Then
            If Not CBool(CryptAcquireContext(lngCryptContextHandle, strTemp, strProvider, PROV_RSA_FULL, CRYPT_NEWKEYSET)) Then
                GoTo getSaltError
            End If
        End If
    End If
    If Not CBool(CryptGenRandom(lngCryptContextHandle, lngSaltLen, strBuffer)) Then
        GoTo getSaltError
    Else
        getBytes = strBuffer
    End If

getSaltError:
    If lngCryptContextHandle Then
        If Not CBool(CryptReleaseContext(lngCryptContextHandle, 0)) Then
            getBytes = API_ERROR
        End If
    End If
End Function

Not good at ASP components
Wednesday, October 01, 2003

*  Recent Topics

*  Fog Creek Home