教學課程:使用具有安全記憶體保護區的 Always Encrypted 開發 .NET Framework 應用程式

適用於:SQL Server 2019 (15.x) 和更新版本 - 僅限 Windows Azure SQL Database

本教學課程會教您如何開發應用程式來發出資料庫查詢,其針對具有安全記憶體保護區的 Always Encrypted 使用伺服器端安全記憶體保護區。

注意

.NET Framework 不支援在沒有證明的情況下使用 Always Encrypted 搭配 VBS 記憶體保護區。 只有在您是使用 Microsoft Azure Attestation (在 Azure SQL Database 中有 Intel SGX 記憶體保護區) 或主機守護者服務 (在 SQL Server 中有 VBS 記憶體保護區) 時,才適用本教學課程。

必要條件

遵循本教學課程中的下列步驟之前,請確定您已完成開始使用 Always Encrypted 與安全記憶體保護區教學課程的其中一個。

您還需要 Visual Studio (建議使用 2022 版),其可從 https://visualstudio.microsoft.com/ 下載。 您的應用程式開發電腦必須執行 .NET Framework 4.7.2 或更新版本。

步驟 1:設定 Visual Studio 專案

若要在 .NET Framework 應用程式中使用具有安全記憶體保護區的 Always Encrypted,您需要確定應用程式是針對 .NET Framework 4.7.2 所建置,並已與 Microsoft.SqlServer.Management.AlwaysEncrypted.EnclaveProviders NuGet 相整合。 此外,如果您將資料行主要金鑰儲存至 Azure Key Vault,則也需要整合應用程式與 Microsoft.SqlServer.Management.AlwaysEncrypted.AzureKeyVaultProvider NuGet、版本 2.4.0 或更新版本。

  1. 開啟 Visual Studio。

  2. 建立新的 C# 主控台應用程式 (.NET Framework) 專案。

  3. 請確定您專案的目標至少為 .NET Framework 4.7.2。 以滑鼠右鍵按一下 [方案總管] 中的專案,然後選取 [屬性],並將 [目標 Framework] 設定為 .NET Framework 4.7.2。

  4. 移至 [工具] (主功能表) > [NuGet 套件管理員] > [套件管理員主控台],以安裝下列 NuGet 套件。 在 [套件管理員主控台] 中,執行下列程式碼。

    Install-Package Microsoft.SqlServer.Management.AlwaysEncrypted.EnclaveProviders -IncludePrerelease
    
  5. 如果您使用 Azure Key Vault 來儲存資料行主要金鑰,請移至 [工具] (主功能表) > [NuGet 套件管理員] > [套件管理員主控台],以安裝下列 NuGet 套件。 在 [套件管理員主控台] 中,執行下列程式碼。

    Install-Package Microsoft.SqlServer.Management.AlwaysEncrypted.AzureKeyVaultProvider -IncludePrerelease -Version 2.4.0
    Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory
    
  6. 開啟您專案的 App.config 檔。

  7. 找到 <configuration> 區段,然後新增或更新這些 <configSections> 區段。

    1. <configuration> 區段包含 <configSections> 區段,請緊接在 <configuration> 的下方新增下列內容。

      <configSections>
        <section name="SqlColumnEncryptionEnclaveProviders" type="System.Data.SqlClient.SqlColumnEncryptionEnclaveProviderConfigurationSection, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
      </configSections>
      
    2. 如果 <configuration> 區段已包含 <configSections> 區段,請在 <configSections> 區段內新增下行程式碼:

      <section name="SqlColumnEncryptionEnclaveProviders"  type="System.   Data.SqlClient.   SqlColumnEncryptionEnclaveProviderConfigurationSection, System.   Data,  Version=4.0.0.0, Culture=neutral,    PublicKeyToken=b77a5c561934e089" />
      
  8. <configuration> 區段內的 </configSections> 下方新增區段,其指定要用來證明以及與伺服器端安全記憶體保護區互動的記憶體保護區提供者。

    1. 如果您是使用 SQL Server 和主機守護者服務 (HGS) (您使用的是教學課程:在 SQL Server 中開始使用具有安全記憶體保護區的 Always Encrypted 中的資料庫),請新增以下部分。

      <SqlColumnEncryptionEnclaveProviders>
        <providers>
          <add name="VBS"  type="Microsoft.SqlServer.Management.AlwaysEncrypted.EnclaveProviders.HostGuardianServiceEnclaveProvider,  Microsoft.SqlServer.Management.AlwaysEncrypted.EnclaveProviders,    Version=15.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"/>
        </providers>
      </SqlColumnEncryptionEnclaveProviders>
      

      以下是簡易主控台應用程式的 app.config 檔案完整範例。

      <?xml version="1.0" encoding="utf-8" ?>
      <configuration>
        <configSections>
          <section name="SqlColumnEncryptionEnclaveProviders" type="System.Data.SqlClient.SqlColumnEncryptionEnclaveProviderConfigurationSection, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
        </configSections>
        <SqlColumnEncryptionEnclaveProviders>
          <providers>
            <add name="VBS"  type="Microsoft.SqlServer.Management.AlwaysEncrypted.EnclaveProviders.HostGuardianServiceEnclaveProvider,  Microsoft.SqlServer.Management.AlwaysEncrypted.EnclaveProviders,    Version=15.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"/>
          </providers>
        </SqlColumnEncryptionEnclaveProviders>
        <startup> 
         <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
        </startup>
      </configuration>
      
    2. 如果您是使用具有 SGX 記憶體保護區的 Azure SQL Database 和 Microsoft Azure Attestation (您使用的是教學課程:在 Azure SQL Database 中開始使用具有 Intel SGX 安全記憶體保護區的 Always Encrypted 中的資料庫),請新增以下部分。

      <SqlColumnEncryptionEnclaveProviders>
        <providers>
          <add name="SGX" type="Microsoft.SqlServer.Management.AlwaysEncrypted.EnclaveProviders.AzureAttestationEnclaveProvider, Microsoft.SqlServer.Management.AlwaysEncrypted.EnclaveProviders, Version=15.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
        </providers>
      </SqlColumnEncryptionEnclaveProviders>
      

      以下是簡易主控台應用程式的 app.config 檔案完整範例。

      <?xml version="1.0" encoding="utf-8" ?>
      <configuration>
        <configSections>
          <section name="SqlColumnEncryptionEnclaveProviders" type="System.Data.SqlClient.SqlColumnEncryptionEnclaveProviderConfigurationSection, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
        </configSections>
        <SqlColumnEncryptionEnclaveProviders>
          <providers>
            <add name="SGX" type="Microsoft.SqlServer.Management.AlwaysEncrypted.EnclaveProviders.AzureAttestationEnclaveProvider, Microsoft.SqlServer.Management.AlwaysEncrypted.EnclaveProviders, Version=15.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
          </providers>
        </SqlColumnEncryptionEnclaveProviders>
        <startup> 
         <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
        </startup>
      </configuration>
      

步驟 2:實作您的應用程式邏輯

您的應用程式將會連線到 ContosoHR 資料庫 (在其中一個教學課程中建立,請參閱必要條件),且其將會執行查詢,其中包含 SSN 資料行上的 LIKE 述詞和 Salary 資料行上的範圍比較。

  1. 將 Program.cs 檔案 (由 Visual Studio 產生) 的內容替換成以下程式碼。 使用伺服器名稱、資料庫驗證設定和環境的記憶體保護區證明 URL 更新資料庫連接字串。

    using System;
    using System.Data.SqlClient;
    using System.Data;
    
    namespace ConsoleApp1
    {
        class Program
        {
            static void Main(string[] args)
            {
    
                string connectionString = "Data Source = myserver; Initial Catalog = ContosoHR; Column Encryption Setting = Enabled;Enclave Attestation Url = http://hgs.bastion.local/Attestation; Integrated Security = true";
    
                //string connectionString = "Data Source = myserver.database.windows.net; Initial Catalog = ContosoHR; Column Encryption Setting = Enabled;Enclave Attestation Url = https://myattestationprovider.uks.attest.azure.net/attest/SgxEnclave; User ID=user; Password=password";
    
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();
    
                    SqlCommand cmd = connection.CreateCommand();
                    cmd.CommandText = @"SELECT [SSN], [FirstName], [LastName], [Salary] FROM [HR].[Employees] WHERE [SSN] LIKE @SSNPattern AND [Salary] > @MinSalary;";
    
                    SqlParameter paramSSNPattern = cmd.CreateParameter();
    
                    paramSSNPattern.ParameterName = @"@SSNPattern";
                    paramSSNPattern.DbType = DbType.AnsiStringFixedLength;
                    paramSSNPattern.Direction = ParameterDirection.Input;
                    paramSSNPattern.Value = "%9838";
                    paramSSNPattern.Size = 11;
    
                    cmd.Parameters.Add(paramSSNPattern);
    
                    SqlParameter MinSalary = cmd.CreateParameter();
    
                    MinSalary.ParameterName = @"@MinSalary";
                    MinSalary.DbType = DbType.Currency;
                    MinSalary.Direction = ParameterDirection.Input;
                    MinSalary.Value = 20000;
    
                    cmd.Parameters.Add(MinSalary);
                    cmd.ExecuteNonQuery();
    
                    SqlDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
    
                    {
                        Console.WriteLine(reader[0] + ", " + reader[1] + ", " + reader[2] + ", " + reader[3]);
                    }   
                    Console.ReadKey();
                }
            }
        }
    }
    
  2. 建置並執行應用程式。

另請參閱