首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

專案實戰:C# 加密狗 (Hardware Key) 開發概述(二)

     編輯:關於C語言

部署注意事項

  1. 必須完整安裝加密狗隨附的 SDK 安裝程式。
  2. 將安裝目錄下的 Win32dll.dll 複製至系統目錄 (如 C:\Windows\System32\)。
    範例路徑:\SafeNet China\SoftDog SDK V3.1\Win32\Win32dll\HighDll\Win32dll.dll

不同廠商的加密狗原理大同小異:皆提供 API 介面 (DLL) 供應用程式呼叫,差異僅在介面定義與加密演算法。

C# 完整封裝範例 (SafeNet SoftDog)

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);
        }
    }
}

使用範例

寫入 10 位元組 (0~9)

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,異常時記錄日誌並拒絕執行核心功能。
  • 考慮搭配程式碼混淆與完整性驗證,防止繞過授權檢查。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved