Win32dll.dll 複製至系統目錄 (如 C:\Windows\System32\)。
\SafeNet China\SoftDog SDK V3.1\Win32\Win32dll\HighDll\Win32dll.dll
不同廠商的加密狗原理大同小異:皆提供 API 介面 (DLL) 供應用程式呼叫,差異僅在介面定義與加密演算法。
using System;
using System.Runtime.InteropServices;
public unsafe class Dog
{
public uint DogBytes, DogAddr; // 讀寫長度與起始位址
public byte[] DogData; // 資料緩衝區
public uint RetCode; // 回傳碼
// 導入非受控 DLL 函式
[DllImport("Win32dll.dll", CharSet = CharSet.Ansi)]
public static extern uint DogRead(uint iDogBytes, uint iDogAddr, byte* pDogData);
[DllImport("Win32dll.dll", CharSet = CharSet.Ansi)]
public static extern uint DogWrite(uint iDogBytes, uint iDogAddr, byte* pDogData);
public Dog(ushort num)
{
DogBytes = num;
DogData = new byte[DogBytes];
}
// 讀取加密狗資料
public void ReadDog()
{
fixed (byte* pDogData = &DogData[0])
{
RetCode = DogRead(DogBytes, DogAddr, pDogData);
}
}
// 寫入加密狗資料
public void WriteDog()
{
fixed (byte* pDogData = &DogData[0])
{
RetCode = DogWrite(DogBytes, DogAddr, pDogData);
}
}
}
Dog d = new Dog(10);
d.DogAddr = 0;
for (int i = 0; i < d.DogData.Length; i++) d.DogData[i] = (byte)i;
d.WriteDog();
Dog d = new Dog(10);
d.ReadDog();
byte[] b = new byte[d.DogData.Length];
for (int i = 0; i < d.DogData.Length; i++) b[i] = d.DogData[i];
extern:指示方法在外部 DLL 實作。unsafe / fixed:使用指標直接操作記憶體,繞過 GC 移動陣列,確保 DLL 能正確存取緩衝區位址。CharSet.Ansi:符合 DLL 導出函式的字元集約定。RetCode,異常時記錄日誌並拒絕執行核心功能。