適用于 .NET 的 Azure 金鑰保存庫金鑰用戶端程式庫 - 4.5.0 版

Azure 金鑰保存庫是一項雲端服務,可提供加密資料的金鑰安全儲存體。 多個金鑰和相同金鑰的多個版本可以保留在 Azure 金鑰保存庫中。 Azure 金鑰保存庫中的密碼編譯金鑰會以JSON Web 金鑰表示, (JWK) 物件。

Azure 金鑰保存庫受控 HSM 是完全受控、高可用性、符合標準的標準雲端服務,可讓您使用 FIPS 140-2 層級 3 驗證的 HSM 來保護雲端應用程式的密碼編譯金鑰。

Azure 金鑰保存庫金鑰程式庫用戶端支援 RSA 金鑰和橢圓曲線 (EC) 金鑰,每個金鑰都有硬體安全性模組 (HSM) 的對應支援。 它提供建立、擷取、更新、刪除、清除、備份、還原,以及列出金鑰及其版本的作業。

| 原始程式碼套件 (NuGet) | API 參考檔 | 產品檔 | 樣品 | 移轉指南

開始使用

安裝套件

使用NuGet安裝適用于 .NET 的 Azure 金鑰保存庫 金鑰用戶端程式庫:

dotnet add package Azure.Security.KeyVault.Keys

必要條件

  • Azure 訂用帳戶
  • 現有的 Azure 金鑰保存庫。 如果您需要建立 Azure 金鑰保存庫,您可以使用 Azure 入口網站或Azure CLI
  • 使用RBAC (建議) 或存取控制授權給現有的 Azure 金鑰保存庫。

如果您要建立標準金鑰保存庫資源,請執行下列 CLI 命令,並以 <your-resource-group-name> 您自己的唯一名稱取代 和 <your-key-vault-name>

az keyvault create --resource-group <your-resource-group-name> --name <your-key-vault-name>

如果您要建立受控 HSM 資源,請執行下列 CLI 命令:

az keyvault create --hsm-name <your-key-vault-name> --resource-group <your-resource-group-name> --administrators <your-user-object-id> --location <your-azure-location>

若要取得 <your-user-object-id> ,您可以執行下列 CLI 命令:

az ad user show --id <your-user-principal> --query id

驗證用戶端

若要與 Azure 金鑰保存庫 服務互動,您必須建立KeyClient類別的實例。 您需要保存 庫 URL,您可能會在入口網站中看到「DNS 名稱」,以及具現化用戶端物件的認證。

以下顯示的範例會使用 DefaultAzureCredential ,適用于大部分案例,包括使用受控識別驗證的本機開發和生產環境。 此外,我們建議在生產環境中使用受控識別進行驗證。 您可以在 Azure 身分識別 檔中,找到不同驗證方式及其對應認證類型的詳細資訊。

若要使用如下所示的 DefaultAzureCredential 提供者,或其他 Azure SDK 提供的認證提供者,您必須先安裝 Azure.Identity 套件:

dotnet add package Azure.Identity

啟動您的受控 HSM

只有在您建立受控 HSM 時,才適用本節。 在 HSM 啟動前,所有資料平面命令都會停用。 您將無法建立金鑰或指派角色。 只有在 create 命令執行期間指派的指定管理員,才可以啟用 HSM。 若要啟用 HSM,您必須下載安全性網域。

若要啟動 HSM,您需要:

  • 至少 3 個 RSA 金鑰組 (最多 10 個)
  • 指定解密安全性網域所需的金鑰數目下限 (仲裁)

若要啟動 HSM,您至少必須將 3 個 (最多 10 個) RSA 公開金鑰傳送至 HSM。 HSM 會使用這些金鑰將安全性網域加密,並加以傳回。 成功下載此安全性網域之後,您的 HSM 即可供使用。 您也需要指定仲裁,這是解密安全性網域所需的私密金鑰數目下限。

下列範例示範如何使用 openssl 來產生 3 個自我簽署憑證。

openssl req -newkey rsa:2048 -nodes -keyout cert_0.key -x509 -days 365 -out cert_0.cer
openssl req -newkey rsa:2048 -nodes -keyout cert_1.key -x509 -days 365 -out cert_1.cer
openssl req -newkey rsa:2048 -nodes -keyout cert_2.key -x509 -days 365 -out cert_2.cer

使用 az keyvault security-domain download 命令下載安全性網域,並啟動您的受控 HSM。 下列範例使用 3 個 RSA 金鑰組, (此命令只需要公開金鑰) ,並將仲裁設定為 2。

az keyvault security-domain download --hsm-name <your-key-vault-name> --sd-wrapping-keys ./certs/cert_0.cer ./certs/cert_1.cer ./certs/cert_2.cer --sd-quorum 2 --security-domain-file ContosoMHSM-SD.json

建立 KeyClient

具現化 DefaultAzureCredential 以傳遞至用戶端。 如果權杖認證的實例會使用相同的身分識別進行驗證,則可以與多個用戶端搭配使用。

// Create a new key client using the default credential from Azure.Identity using environment variables previously set,
// including AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, and AZURE_TENANT_ID.
var client = new KeyClient(vaultUri: new Uri(vaultUrl), credential: new DefaultAzureCredential());

// Create a new key using the key client.
KeyVaultKey key = client.CreateKey("key-name", KeyType.Rsa);

// Retrieve a key using the key client.
key = client.GetKey("key-name");

建立 CryptographyClient

在 Azure 金鑰保存庫 中建立 KeyVaultKey 之後,您也可以建立CryptographyClient

// Create a new cryptography client using the same Key Vault or Managed HSM endpoint, service version,
// and options as the KeyClient created earlier.
CryptographyClient cryptoClient = client.GetCryptographyClient(key.Name, key.Properties.Version);

重要概念

KeyVaultKey

Azure 金鑰保存庫支援多個金鑰類型和演算法,並可針對高價值金鑰使用硬體安全性模組 (HSM) 。

KeyClient

KeyClient SDK 中同時提供同步和非同步作業的 ,允許根據應用程式的使用案例來選取用戶端。 初始化 KeyClient 之後,您就可以與 Azure 金鑰保存庫中的主要資源類型互動。

CryptographyClient

CryptographyClient SDK 中同時提供同步和非同步作業的 ,允許根據應用程式的使用案例來選取用戶端。 初始化 CryptographyClient 之後,您可以使用它搭配 Azure 金鑰保存庫中儲存的金鑰來執行密碼編譯作業。

執行緒安全

我們保證所有用戶端實例方法都是安全線程,且彼此獨立 (指導方針) 。 這可確保重複使用用戶端實例的建議一律是安全的,即使是跨執行緒也一樣。

其他概念

用戶端選項 | 存取回應 | 長時間執行的作業 | 處理失敗 | 診斷 | 嘲笑 | 用戶端存留期

範例

Azure.Security.KeyVault.Keys 套件支援同步和非同步 API。

下一節提供使用 client上述所建立的數個程式碼片段,涵蓋一些最常見的 Azure 金鑰保存庫金鑰服務相關工作:

同步範例

非同步範例

建立金鑰

建立要儲存在 Azure 金鑰保存庫中的金鑰。 如果具有相同名稱的金鑰已經存在,則會建立新版本的金鑰。

// Create a key. Note that you can specify the type of key
// i.e. Elliptic curve, Hardware Elliptic Curve, RSA
KeyVaultKey key = client.CreateKey("key-name", KeyType.Rsa);

Console.WriteLine(key.Name);
Console.WriteLine(key.KeyType);

// Create a software RSA key
var rsaCreateKey = new CreateRsaKeyOptions("rsa-key-name", hardwareProtected: false);
KeyVaultKey rsaKey = client.CreateRsaKey(rsaCreateKey);

Console.WriteLine(rsaKey.Name);
Console.WriteLine(rsaKey.KeyType);

// Create a hardware Elliptic Curve key
// Because only premium Azure Key Vault supports HSM backed keys , please ensure your Azure Key Vault
// SKU is premium when you set "hardwareProtected" value to true
var echsmkey = new CreateEcKeyOptions("ec-key-name", hardwareProtected: true);
KeyVaultKey ecKey = client.CreateEcKey(echsmkey);

Console.WriteLine(ecKey.Name);
Console.WriteLine(ecKey.KeyType);

擷取金鑰

GetKey會擷取先前儲存在 Azure 金鑰保存庫中的金鑰。

KeyVaultKey key = client.GetKey("key-name");

Console.WriteLine(key.Name);
Console.WriteLine(key.KeyType);

更新現有的金鑰

UpdateKeyProperties會更新先前儲存在 Azure 金鑰保存庫中的金鑰。

KeyVaultKey key = client.CreateKey("key-name", KeyType.Rsa);

// You can specify additional application-specific metadata in the form of tags.
key.Properties.Tags["foo"] = "updated tag";

KeyVaultKey updatedKey = client.UpdateKeyProperties(key.Properties);

Console.WriteLine(updatedKey.Name);
Console.WriteLine(updatedKey.Properties.Version);
Console.WriteLine(updatedKey.Properties.UpdatedOn);

刪除金鑰

StartDeleteKey會啟動長時間執行的作業,以刪除先前儲存在 Azure 金鑰保存庫 中的金鑰。 您可以立即擷取金鑰,而不需要等待作業完成。 當 Azure 金鑰保存庫未啟用虛刪除時,此作業會永久刪除金鑰。

DeleteKeyOperation operation = client.StartDeleteKey("key-name");

DeletedKey key = operation.Value;
Console.WriteLine(key.Name);
Console.WriteLine(key.DeletedOn);

刪除和清除金鑰

您必須等候長時間執行的作業完成,才能嘗試清除或復原金鑰。

DeleteKeyOperation operation = client.StartDeleteKey("key-name");

// You only need to wait for completion if you want to purge or recover the key.
while (!operation.HasCompleted)
{
    Thread.Sleep(2000);

    operation.UpdateStatus();
}

DeletedKey key = operation.Value;
client.PurgeDeletedKey(key.Name);

列出金鑰

此範例會列出指定之 Azure 金鑰保存庫中的所有金鑰。

Pageable<KeyProperties> allKeys = client.GetPropertiesOfKeys();

foreach (KeyProperties keyProperties in allKeys)
{
    Console.WriteLine(keyProperties.Name);
}

加密和解密

此範例會 CryptographyClient 建立 ,並使用它以 Azure 金鑰保存庫中的金鑰加密和解密。

// Create a new cryptography client using the same Key Vault or Managed HSM endpoint, service version,
// and options as the KeyClient created earlier.
var cryptoClient = client.GetCryptographyClient(key.Name, key.Properties.Version);

byte[] plaintext = Encoding.UTF8.GetBytes("A single block of plaintext");

// encrypt the data using the algorithm RSAOAEP
EncryptResult encryptResult = cryptoClient.Encrypt(EncryptionAlgorithm.RsaOaep, plaintext);

// decrypt the encrypted data.
DecryptResult decryptResult = cryptoClient.Decrypt(EncryptionAlgorithm.RsaOaep, encryptResult.Ciphertext);

以非同步方式建立金鑰

非同步 API 與其同步對應專案相同,但會傳回非同步方法的一般 「Async」 尾碼,並傳回 Task。

// Create a key of any type
KeyVaultKey key = await client.CreateKeyAsync("key-name", KeyType.Rsa);

Console.WriteLine(key.Name);
Console.WriteLine(key.KeyType);

// Create a software RSA key
var rsaCreateKey = new CreateRsaKeyOptions("rsa-key-name", hardwareProtected: false);
KeyVaultKey rsaKey = await client.CreateRsaKeyAsync(rsaCreateKey);

Console.WriteLine(rsaKey.Name);
Console.WriteLine(rsaKey.KeyType);

// Create a hardware Elliptic Curve key
// Because only premium Azure Key Vault supports HSM backed keys , please ensure your Azure Key Vault
// SKU is premium when you set "hardwareProtected" value to true
var echsmkey = new CreateEcKeyOptions("ec-key-name", hardwareProtected: true);
KeyVaultKey ecKey = await client.CreateEcKeyAsync(echsmkey);

Console.WriteLine(ecKey.Name);
Console.WriteLine(ecKey.KeyType);

以非同步方式列出金鑰

列出索引鍵不依賴等候 GetPropertiesOfKeysAsync 方法,而是傳回 AsyncPageable<KeyProperties> 您可以搭配 語句使用的 await foreach

AsyncPageable<KeyProperties> allKeys = client.GetPropertiesOfKeysAsync();

await foreach (KeyProperties keyProperties in allKeys)
{
    Console.WriteLine(keyProperties.Name);
}

以非同步方式刪除金鑰

在清除金鑰之前,以非同步方式刪除金鑰時,您可以等候 WaitForCompletionAsync 作業上的 方法。 根據預設,此迴圈會無限期地執行,但您可以傳遞 CancellationToken 來取消它。

DeleteKeyOperation operation = await client.StartDeleteKeyAsync("key-name");

// You only need to wait for completion if you want to purge or recover the key.
await operation.WaitForCompletionAsync();

DeletedKey key = operation.Value;
await client.PurgeDeletedKeyAsync(key.Name);

疑難排解

如需如何診斷各種失敗案例的詳細資料,請參閱 我們的疑難排解指南

一般

當您使用 .NET SDK 與 Azure 金鑰保存庫金鑰用戶端程式庫互動時,服務傳回的錯誤會對應至針對REST API要求傳回的相同 HTTP 狀態碼。

例如,如果您嘗試擷取 Azure 金鑰保存庫中不存在的金鑰, 404 則會傳回錯誤,指出「找不到」。

try
{
    KeyVaultKey key = client.GetKey("some_key");
}
catch (RequestFailedException ex)
{
    Console.WriteLine(ex.ToString());
}

您會發現會記錄其他資訊,例如作業的用戶端要求識別碼。

Message:
    Azure.RequestFailedException : Service request failed.
    Status: 404 (Not Found)
Content:
    {"error":{"code":"KeyNotFound","message":"Key not found: some_key"}}

Headers:
    Cache-Control: no-cache
    Pragma: no-cache
    Server: Microsoft-IIS/10.0
    x-ms-keyvault-region: westus
    x-ms-request-id: 625f870e-10ea-41e5-8380-282e5cf768f2
    x-ms-keyvault-service-version: 1.1.0.866
    x-ms-keyvault-network-info: addr=131.107.174.199;act_addr_fam=InterNetwork;
    X-AspNet-Version: 4.0.30319
    X-Powered-By: ASP.NET
    Strict-Transport-Security: max-age=31536000;includeSubDomains
    X-Content-Type-Options: nosniff
    Date: Tue, 18 Jun 2019 16:02:11 GMT
    Content-Length: 75
    Content-Type: application/json; charset=utf-8
    Expires: -1

下一步

此 GitHub 存放庫中有數個 Azure 金鑰保存庫 金鑰用戶端程式庫範例可供您使用。 這些範例提供使用 Azure 金鑰保存庫時常見之其他案例的範例程式碼:

  • Sample1_HelloWorld.md - 用於使用 Azure 金鑰保存庫,包括:

    • 建立金鑰
    • 取得現有的金鑰
    • 更新現有的金鑰
    • 刪除金鑰
  • Sample2_BackupAndRestore.md - 包含使用 Azure 金鑰保存庫金鑰的程式碼片段,包括:

    • 備份和復原金鑰
  • Sample3_GetKeys.md - 使用 Azure 金鑰保存庫金鑰的範例程式碼,包括:

    • 建立金鑰
    • 列出金鑰保存庫中的所有索引鍵
    • 更新金鑰保存庫中的金鑰
    • 列出指定索引鍵的版本
    • 從金鑰保存庫刪除金鑰
    • 列出金鑰保存庫中刪除的金鑰
  • Sample4_EncryptDecrypt.md - 使用 Azure 金鑰保存庫 金鑰執行密碼編譯作業的範例程式碼,包括:

    • 使用 CryptographyClient 加密和解密資料
  • Sample5_SignVerify.md - 使用 Azure 金鑰保存庫金鑰的範例程式碼,包括:

    • 簽署預先計算的摘要,並使用簽署和驗證來驗證簽章
    • 使用 SignData 和 VerifyData 簽署原始資料並驗證簽章
  • Sample6_WrapUnwrap.md - 使用 Azure 金鑰保存庫金鑰的範例程式碼,包括:

    • 包裝和解除包裝對稱金鑰

其他文件

參與

如需建置、測試及參與這些程式庫的詳細資訊,請參閱 CONTRIBUTING.md

此專案歡迎參與和提供建議。 大部分的參與都要求您同意「參與者授權合約 (CLA)」,宣告您有權且確實授與我們使用投稿的權利。 如需詳細資料,請前往 https://cla.microsoft.com

當您提交提取要求時,CLA Bot 會自動判斷您是否需要提供 CLA,並適當地裝飾 PR (例如標籤、註解)。 請遵循 bot 提供的指示。 您只需要使用我們的 CLA 在所有存放庫上執行此動作一次。

此專案採用 Microsoft Open Source Code of Conduct (Microsoft 開放原始碼管理辦法)。 如需詳細資訊,請參閱管理辦法常見問題集,如有任何其他問題或意見請連絡 opencode@microsoft.com。

曝光數