在商業軟體授權保護體系中,加密狗(硬體金鑰/軟體保護鎖)作為一種物理級防複製手段,廣泛應用於高價值軟體的授權驗證、關鍵演算法離線運算及敏感資料加密存儲。本文以賽孚耐(SafeNet/深圳市賽孚耐信息技術有限公司)主流加密狗產品為例,詳細記錄其在 .NET 專案中的整合流程、核心 API 解析、關鍵注意事項及完整 C# 封裝實戰程式碼。
該加密狗提供基於 Win32dll.dll 的非托管類庫,核心功能僅兩個:讀取與寫入用戶區資料。用戶區地址空間為 0~99,單次操作長度 1~100 位元組,且 idogAddr + idogBytes ≤ 100。
[DllImport("Win32dll.dll", CharSet = CharSet.Ansi)]
public static unsafe extern uint DogWrite(
uint idogBytes, // 寫入位元組數 (1~100)
uint idogAddr, // 起始地址 (0~99)
byte* pdogData // 資料緩衝區指標
);
// 返回值:0 成功,非 0 為錯誤碼
[DllImport("Win32dll.dll", CharSet = CharSet.Ansi)]
public static unsafe extern uint DogRead(
uint idogBytes,
uint idogAddr,
byte* pdogData
);
// 參數含義同 DogWrite,注意緩衝區必須足夠大
調用前必須完成以下部署,否則會發生 DllNotFoundException 或加密狗無法識別:
Win32dll.dll 複製至系統目錄:Windows Server 2003 範例:源路徑:\SafeNet China\SoftDog SDK V3.1\Win32\Win32dll\HighDll\Win32dll.dll目標路徑:C:\WINDOWS\system32\經驗之談:不同廠商加密狗的底層原理大同小異(皆為掛載在 USB/並行埠的安全存儲裝置,提供廠商定製 API),差異僅在於 API 介面定義與驅動模型。掌握一款即可觸類旁通。
利用 unsafe 上下文與 fixed 關鍵字釘選記憶體,實現托管陣列與非托管指標的安全互操作。
using System;
using System.Runtime.InteropServices;
public unsafe class Dog
{
// 非托管 API 宣告
[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 uint DogBytes { get; set; } // 操作長度
public uint DogAddr { get; set; } // 起始地址
public byte[] DogData { get; private set; } // 資料緩衝區
public uint RetCode { get; private set; } // 返回碼
///
/// 建構函式:初始化緩衝區大小
///
public Dog(ushort byteCount)
{
DogBytes = byteCount;
DogData = new byte[DogBytes];
}
///
/// 從加密狗讀取資料
///
public void ReadDog()
{
fixed (byte* pData = &DogData[0])
{
RetCode = DogRead(DogBytes, DogAddr, pData);
}
}
///
/// 向加密狗寫入資料
///
public void WriteDog()
{
fixed (byte* pData = &DogData[0])
{
RetCode = DogWrite(DogBytes, DogAddr, pData);
}
}
}
var dog = new Dog(10);
dog.DogAddr = 0;
for (int i = 0; i < dog.DogData.Length; i++)
{
dog.DogData[i] = (byte)i;
}
dog.WriteDog();
if (dog.RetCode != 0)
Console.WriteLine($"寫入失敗,錯誤碼:{dog.RetCode}");
else
Console.WriteLine("寫入成功");
var dog = new Dog(10);
dog.DogAddr = 0;
dog.ReadDog();
if (dog.RetCode != 0)
{
Console.WriteLine($"讀取失敗,錯誤碼:{dog.RetCode}");
return;
}
byte[] buffer = new byte[dog.DogData.Length];
Array.Copy(dog.DogData, buffer, buffer.Length);
Console.WriteLine("讀取資料:" + BitConverter.ToString(buffer));
unsafe 允許使用指標;fixed 防止 GC 移動陣列記憶體,確保非托管呼叫期間指標有效。加密狗作為軟體資產保護的「最後一道防線」,其整合核心在於非托管互操作的正確性與部署環境的標準化。本文提供的封裝類已在多個商業專案驗證穩定可靠,開發者可據此快速建立授權驗證、離線授權檢測、核心演算法離線執行等高安全性功能模組。