新建From1(窗体),新建Command1(按钮CommandButton),代码:
Private Sub Command1_Click()
Debug.Print f_GenerateRandom(8)
Debug.Print f_GenerateRandomLong
Debug.Print f_GenerateRandomInteger
End Sub
新建模块 modRandom.bas,代码:
Option Explicit
Private Const ALG_TYPE_ANY As Long = 0
Private Const ALG_SID_MD5 As Long = 3
Private Const ALG_CLASS_HASH As Long = 32768
Private Const HP_HASHVAL As Long = 2
Private Const HP_HASHSIZE As Long = 4
Private Const CRYPT_VERIFYCONTEXT = &HF0000000
Private Const PROV_RSA_FULL As Long = 1
Private Const MS_ENHANCED_PROV As String = "Microsoft Enhanced Cryptographic Provider v1.0"
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 CryptCreateHash Lib "advapi32.dll" (ByVal hProv As Long, ByVal Algid As Long, ByVal hKey As Long, ByVal dwFlags As Long, ByRef phHash As Long) As Long
Private Declare Function CryptDestroyHash Lib "advapi32.dll" (ByVal hHash As Long) As Long
Private Declare Function CryptGetHashParam Lib "advapi32.dll" (ByVal pCryptHash As Long, ByVal dwParam As Long, ByRef pbData As Any, ByRef pcbData As Long, ByVal dwFlags As Long) As Long
Private Declare Function CryptGenRandom Lib "advapi32.dll" (ByVal pCryptHash As Long, ByVal dwLength As Long, ByRef pbData As Any) As Long
Private Declare Function CryptHashData Lib "advapi32.dll" (ByVal hHash As Long, ByVal pbData As String, ByVal dwDataLen 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
Public Function f_GenerateRandom(ByVal lByteCount As Long) As Byte()
'产生指定字节的随机数
Dim hCrypt As Long
Dim b() As Byte
ReDim b(lByteCount - 1)
If CryptAcquireContext(hCrypt, vbNullString, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT) Then
If CryptGenRandom(hCrypt, lByteCount, b(0)) <> 0 Then
f_GenerateRandom = b
End If
End If
If hCrypt Then CryptReleaseContext hCrypt, 0
End Function
Public Function f_GenerateRandomLong() As Long
'产生一个LONG类型的随机数
Dim hCrypt As Long
If CryptAcquireContext(hCrypt, vbNullString, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT) Then
Call CryptGenRandom(hCrypt, 4, f_GenerateRandomLong)
End If
If hCrypt Then CryptReleaseContext hCrypt, 0
End Function
Public Function f_GenerateRandomInteger() As Integer
'产生一个INT的随机数
Dim hCrypt As Long
If CryptAcquireContext(hCrypt, vbNullString, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT) Then
Call CryptGenRandom(hCrypt, 2, f_GenerateRandomInteger)
End If
If hCrypt Then CryptReleaseContext hCrypt, 0
End Function
运行结果:
撵釩??
1845100102
-10891