萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

深度剖析 .NET 授權編譯器 (LC.exe) 原理與源碼架構

LC.exe 角色與定位

License Compiler (LC.exe) 是 .NET Framework SDK 內建工具,專責將 **授權許可證資訊 (.licx 文字檔)** 編譯為 **二進位 `.licenses` 資源**,嵌入組件中。執行階段 `LicenseManager` 讀取嵌入資源驗證授權,保護商業控制項/元件智慧財產權。

授權檔格式 (.licx)


# 每行一個受授權型別,格式:完整型別名稱, 組件完整名稱
MyCompany.Controls.GridControl, MyCompany.Controls, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1234567890abcdef
MyCompany.Charts.ChartEngine, MyCompany.Charts, Version=2.0.0.0, Culture=neutral, PublicKeyToken=1234567890abcdef
  • 型別必須實作 `System.ComponentModel.LicenseProvider` 或標記 `[LicenseProvider]`。
  • 編譯時 LC.exe 會載入組件、實例化型別、呼叫 `LicenseManager.CreateWithContext` 取得授權字串。

命令列參數完整解析

參數說明範例
/complist:file指定 .licx 檔案 (可多個)/complist:Controls.licx
/i:assembly參考組件路徑 (可多個,供型別解析)/i:bin\MyControls.dll
/target:exe目標輸出組件檔名 (決定 .licenses 命名)/target:MyApp.exe
/outdir:path輸出目錄/outdir:obj\Debug
/v詳細輸出/v
/nologo隱藏版權資訊/nologo

核心流程原始碼邏輯 (簡化自 Reference Source)

1. 參數解析 → 建構編譯上下文


public class LicenseCompiler
{
    private ArrayList _compLists;   // .licx 檔案清單
    private ArrayList _assemblies;  // 參考組件清單
    private string _targetPE;       // 目標組件名
    private string _outputDir;      // 輸出目錄

    public int Main(string[] args)
    {
        if (!ProcessArgs(args)) return 1; // 解析失敗
        
        // 註冊組件解析事件 (處理 /i 指定的參考組件)
        AppDomain.CurrentDomain.AssemblyResolve += OnAssemblyResolve;

        // 建立設計時授權上下文
        var context = new DesigntimeLicenseContext();
        
        // 處理每個 .licx 檔案
        foreach (string licxFile in _compLists)
        {
            ProcessLicxFile(licxFile, context);
        }

        // 產出 .licenses 資源檔
        WriteLicensesResource();
        return 0;
    }
}

2. 處理 .licx:載入型別 → 建立授權


private void ProcessLicxFile(string licxPath, DesigntimeLicenseContext context)
{
    using (var reader = new StreamReader(licxPath, Encoding.UTF8))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            line = line.Trim();
            if (string.IsNullOrEmpty(line) || line.StartsWith("#")) continue; // 註解支援
            
            // 解析 "TypeName, AssemblyFullName"
            var type = Type.GetType(line, throwOnError: true, ignoreCase: false);
            
            // 關鍵:觸發 LicenseProvider 建立授權
            // 此時 LicenseProvider.LicenseProviderAttribute 指定的 Provider 會被實例化
            // 並呼叫 GetLicense(LicenseContext, Type, object, bool)
            LicenseManager.CreateWithContext(type, context);
            
            // 授權物件會被 context 內部收集 (ICollection _licenses)
        }
    }
}

3. 組件解析回呼


private Assembly OnAssemblyResolve(object sender, ResolveEventArgs args)
{
    // 依 /i 指定的組件清單嘗試載入
    foreach (string asmPath in _assemblies)
    {
        try 
        {
            var asmName = new AssemblyName(args.Name);
            if (AssemblyName.GetAssemblyName(asmPath).FullName == args.Name)
                return Assembly.LoadFrom(asmPath);
        }
        catch { /* 忽略 */ }
    }
    return null; // 讓 CLR 繼續嘗試預設探索
}

4. 產出 .licenses 資源二進位格式


private void WriteLicensesResource()
{
    string outputPath = Path.Combine(_outputDir ?? ".", 
        Path.GetFileNameWithoutExtension(_targetPE) + ".licenses");

    using (var stream = new FileStream(outputPath, FileMode.Create))
    using (var writer = new BinaryWriter(stream, Encoding.UTF8))
    {
        // 1. Magic Header
        writer.Write("Microsoft.NET Licenses"); // 識別標記
        
        // 2. 授權數量
        var licenses = context.GetLicenses(); // 內部收集的 License 物件集合
        writer.Write(licenses.Count);
        
        foreach (License lic in licenses)
        {
            // 3. 型別完整名稱
            writer.Write(lic.GetType().FullName); // 實際為授權型別名稱
            
            // 4. 授權金鑰字串 (LicenseKey)
            string key = lic.LicenseKey;
            writer.Write(key ?? "");
            
            // 5. 額外資料 (可選,視 Provider 而定)
            // ...
        }
    }
}

.licenses 資源嵌入與執行階段驗證

  1. **編譯階段**:CSC/MSBuild 透過 `/res:MyApp.exe.licenses` 將檔案嵌入組件 Manifest Resource。
  2. **執行階段**:`LicenseManager.Validate(type)` → 讀取呼叫組件的 `.licenses` 資源流 → `BinaryReader` 解析 → 比對型別名稱與 LicenseKey → 呼叫 Provider `GetLicense` 驗證。
  3. **設計階段**:VS 設計器同樣讀取 `.licenses` 或即時呼叫 `LicenseManager.CreateWithContext` 顯示授權狀態。

現代替代方案與現狀

時代授權機制工具
.NET Framework 1.x - 4.xLC.exe + .licx + LicenseProviderLC.exe, VS 建置整合
.NET Core / .NET 5+**無內建對應機制**廠商自行實作 (License Key 驗證 API、簽章驗證、硬體指紋)
現代商業元件NuGet 套件授權、離線授權檔、雲端驗證自有 CLI/SDK、CI/CD 整合

LC.exe 屬於 **Legacy 技術**,新專案**不建議**採用。若維護舊專案需修改授權邏輯,理解其「編譯期產生授權資源 → 執行期驗證」雙階段架構,才能正確客製化 `LicenseProvider` 或繞過測試環境授權檢查。

安全性考量

  • .licenses 資源**未加密**,僅二進位序列化,可用 ILSpy/資源提取工具讀出 LicenseKey。
  • 驗證邏輯在用戶端執行,**無法防止破解** (移除驗證呼叫、修補 IL、偽造 LicenseKey)。
  • 真正保護需結合:**代碼混淆**、關鍵邏輯移至 Server/API、硬體綁定、線上驗證、簽章驗證完整性。

理解 LC.exe 內部運作,不僅能解決舊專案授權建置問題,更能深入掌握 .NET 元件授權模型的設計哲學與局限,為現代軟體授權架構選型提供歷史參考。

copyright © 萬盛學電腦網 all rights reserved