做软件的小伙伴们,有没有想过有一天你开发出来的软件,别人需要注册才能使用?而注册的话,除了传统方式的输入用户名和注册码,还需要插入指定的U盘才能打开软件?
如果你已经工作了,并且还是在销售部门里坐办公室之类的。你很可能已经见识过公司里的一些管理系统,除了需要输入用户名和密码验证以外,其实电脑后面的USB接口还插着一个U盘(这个U盘叫密匙U盘,或者叫加密狗)
那么,这个加密狗又是怎么回事呢??
简单来说,加密狗的作用就是,你打开软件,软件会检测你的电脑是否已经插入了带有密匙信息的U盘,如果没有插入,那么软件启动失败!插入了不正确的U盘,即验证失败!只有插入正确的带有指定信息的U盘,你的程序才能正常打开。
大家是不是已经对这个加密狗很感兴趣了??或者有些童鞋可能会担忧,貌似那些功能都是企业用的比较多,技术上,会不会很难呀??关于这点,看完本帖子,大家就清楚了。
好了,废话说了,原理也说了,下面就给大家展示一下干货吧!!
首先打开VB,新建一个窗体,在上面添加一个标签(命名为U盘序列号),再添加一个textbox,如下图:
接着添加代码,新建一个标准模块(命名为GetUDiskNum),输入代码如下:
----------------------------------------------------------------
Public Function GetUSBPath() '获取U盘盘符
Dim d, i As Integer
Set d = CreateObject("Scripting.FileSystemObject")
For i = 68 To 90
If d.DriveExists(Chr(i)) Then
If (d.GetDrive(Chr(i)).DriveType = 1) Then
'Print "发现可移动磁盘:" & Chr(i)
GetUSBPath = Chr(i) & ":"
End If
End If
Next
End Function
Public Function GetUSBVID() 'GetUSBVID() '根据U盘盘符获取序列号
Dim objWMIService As Object
Dim USBDevices As Object, USBDevice As Object, USBDiskPartitions As Object, USBDiskPartition As Object, LogicalUSBDisks As Object, LogicalUSBDisk As Object
Dim strID() As String
Dim Finded As Boolean
Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
Set USBDevices = objWMIService.execquery("Select * From Win32_DiskDrive where InterfaceType='USB'")
For Each USBDevice In USBDevices
If Finded Then Exit For
Set USBDiskPartitions = objWMIService.execquery("Associators of {Win32_DiskDrive.DeviceID='" & USBDevice.DeviceId & "'} where AssocClass = Win32_DiskDriveToDiskPartition")
For Each USBDiskPartition In USBDiskPartitions
Set LogicalUSBDisks = objWMIService.execquery("Associators of {Win32_DiskPartition.DeviceID='" & USBDiskPartition.DeviceId & "'} where AssocClass = Win32_LogicalDiskToPartition")
For Each LogicalUSBDisk In LogicalUSBDisks
If LogicalUSBDisk.DeviceId = UCase(GetUSBPath) Then
strID = Split(USBDevice.PNPDeviceID, "\")
strID = Split(strID(UBound(strID)), "&")
GetUSBVID = strID(0)
Finded = True
End If
Next
Next
DoEvents
Next
Set USBDevices = Nothing
Set USBDevice = Nothing
Set USBDiskPartitions = Nothing
Set USBDiskPartition = Nothing
Set LogicalUSBDisks = Nothing
Set LogicalUSBDisk = Nothing
End Function
----------------------------------------------------------------
写好标准模块代码之后,再回来窗体这,双击窗体(或者右击打开代码界面),输入代码如下:
Private Sub Form_Load()
If GetUSBVID = "" Then
MsgBox "未插入U盘,请插入U盘后重新打开软件!", vbExclamation + vbOKOnly, "错误提示"
Else
Text1.Text = GetUSBVID
End If
End Sub