mcpField
A
azure-security-keyvault-keys-dotnet

azure-security-keyvault-keys-dotnet

github.com/sickn33安全48.7k57 次安装今天更新
代码仓库

关于 azure-security-keyvault-keys-dotnet

Azure.Security.KeyVault.Keys 是用于在 Azure Key Vault 和 Managed HSM 中管理加密密钥的 .NET 客户端库。它支持密钥生命周期操作,并可通过客户端执行加密操作。

主要功能

  1. 01创建和获取密钥
  2. 02更新密钥属性
  3. 03删除、备份和还原密钥
  4. 04加密、解密、签名和验证
  5. 05轮换密钥并管理策略

适用场景

  1. 01管理 Azure Key Vault 中的密钥生命周期
  2. 02使用保管库密钥加密或解密数据
  3. 03签署数据并验证签名

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/sickn33/agentic-awesome-skills --skill azure-security-keyvault-keys-dotnet

安装后在 Claude Code 中输入/azure-security-keyvault-keys-dotnet确认已加载。

详细介绍

Azure.Security.KeyVault.Keys(.NET)

用于管理 Azure Key Vault 和 Managed HSM 中加密密钥的客户端库。

在进行更改前,请确认保管库/Managed HSM 的功能、租户/RBAC、密钥名称/版本及生命周期范围。对称 Oct 密钥和硬件保护需要兼容的服务/层级;不要假设所有示例都适用于普通保管库。密钥操作必须与实际算法匹配;范围受限的 RSA 加密/解密选项也无法在没有相应允许操作的情况下用于签名/密钥封装。请将版本 ID 与密文/签名一并保留,并在数据不再需要旧密钥之前保留旧密钥。备份文件属于敏感信息,且受服务还原限制。RSA 适用于小型负载;批量数据请使用经过身份验证的信封加密。

安装

dotnet add package Azure.Security.KeyVault.Keys
dotnet add package Azure.Identity

示例 SDK 版本:4.7.0;请确认目标项目支持的包版本/API。

环境变量

KEY_VAULT_NAME=<your-key-vault-name>
# Or full URI
AZURE_KEYVAULT_URL=https://<vault-name>.vault.azure.net

客户端层次结构

KeyClient (key management)
├── CreateKey / CreateRsaKey / CreateEcKey
├── GetKey / GetKeys
├── UpdateKeyProperties
├── DeleteKey / PurgeDeletedKey
├── BackupKey / RestoreKey
└── GetCryptographyClient() → CryptographyClient

CryptographyClient (cryptographic operations)
├── Encrypt / Decrypt
├── WrapKey / UnwrapKey
├── Sign / Verify
└── SignData / VerifyData

KeyResolver (key resolution)
└── Resolve(keyId) → CryptographyClient

身份验证

DefaultAzureCredential(推荐)
using Azure.Identity;
using Azure.Security.KeyVault.Keys;

var keyVaultName = Environment.GetEnvironmentVariable("KEY_VAULT_NAME");
var kvUri = $"https://{keyVaultName}.vault.azure.net";

var client = new KeyClient(new Uri(kvUri), new DefaultAzureCredential());
服务主体
var credential = new ClientSecretCredential(
    tenantId: "<tenant-id>",
    clientId: "<client-id>",
    clientSecret: "<client-secret>");

var client = new KeyClient(new Uri(kvUri), credential);

密钥管理

创建密钥
// Create RSA key
KeyVaultKey rsaKey = await client.CreateKeyAsync("my-rsa-key", KeyType.Rsa);
Console.WriteLine($"Created key: {rsaKey.Name}, Type: {rsaKey.KeyType}");

// Create RSA key with options
var rsaOptions = new CreateRsaKeyOptions("my-rsa-key-2048")
{
    KeySize = 2048,
    HardwareProtected = false, // true for HSM-backed
    ExpiresOn = DateTimeOffset.UtcNow.AddYears(1),
    NotBefore = DateTimeOffset.UtcNow,
    Enabled = true
};
rsaOptions.KeyOperations.Add(KeyOperation.Encrypt);
rsaOptions.KeyOperations.Add(KeyOperation.Decrypt);

KeyVaultKey rsaKey2 = await client.CreateRsaKeyAsync(rsaOptions);

// Create EC key
var ecOptions = new CreateEcKeyOptions("my-ec-key")
{
    CurveName = KeyCurveName.P256,
    HardwareProtected = true // HSM-backed
};
KeyVaultKey ecKey = await client.CreateEcKeyAsync(ecOptions);

// Create Oct (symmetric) key for wrap/unwrap
var octOptions = new CreateOctKeyOptions("my-oct-key")
{
    KeySize = 256,
    HardwareProtected = true
};
KeyVaultKey octKey = await client.CreateOctKeyAsync(octOptions);
获取密钥
// Get specific key (latest version)
KeyVaultKey key = await client.GetKeyAsync("my-rsa-key");
Console.WriteLine($"Key ID: {key.Id}");
Console.WriteLine($"Key Type: {key.KeyType}");
Console.WriteLine($"Version: {key.Properties.Version}");

// Get specific version
KeyVaultKey keyVersion = await client.GetKeyAsync("my-rsa-key", "version-id");

// List all keys
await foreach (KeyProperties keyProps in client.GetPropertiesOfKeysAsync())
{
    Console.WriteLine($"Key: {keyProps.Name}, Enabled: {keyProps.Enabled}");
}

// List key versions
await foreach (KeyProperties version in client.GetPropertiesOfKeyVersionsAsync("my-rsa-key"))
{
    Console.WriteLine($"Version: {version.Version}, Created: {version.CreatedOn}");
}
更新密钥属性
KeyVaultKey key = await client.GetKeyAsync("my-rsa-key");

key.Properties.ExpiresOn = DateTimeOffset.UtcNow.AddYears(2);
key.Properties.Tags["environment"] = "production";

KeyVaultKey updatedKey = await client.UpdateKeyPropertiesAsync(key.Properties);
删除和清除密钥
// Start delete operation
DeleteKeyOperation operation = await client.StartDeleteKeyAsync("my-rsa-key");

// Wait for deletion to complete (required before purge)
await operation.WaitForCompletionAsync();
Console.WriteLine($"Deleted key scheduled purge date: {operation.Value.ScheduledPurgeDate}");

// Purge is a separate irreversible operation, subject to purge protection.
// await client.PurgeDeletedKeyAsync("my-rsa-key");

// Or recover deleted key
RecoverDeletedKeyOperation recovery = await client.StartRecoverDeletedKeyAsync("my-rsa-key");
await recovery.WaitForCompletionAsync();
KeyVaultKey recoveredKey = recovery.Value;
备份和还原
// Backup key
byte[] backup = await client.BackupKeyAsync("my-rsa-key");
await File.WriteAllBytesAsync("key-backup.bin", backup);

// Restore key
byte[] backupData = await File.ReadAllBytesAsync("key-backup.bin");
KeyVaultKey restoredKey = await client.RestoreKeyBackupAsync(backupData);

加密操作

获取 CryptographyClient
// From KeyClient
KeyVaultKey key = await client.GetKeyAsync("my-rsa-key");
CryptographyClient cryptoClient = client.GetCryptographyClient(
    key.Name, 
    key.Properties.Version);

// Or create directly with key ID
CryptographyClient cryptoClient = new CryptographyClient(
    new Uri("https://myvault.vault.azure.net/keys/my-rsa-key/version"),
    new DefaultAzureCredential());
加密和解密
byte[] plaintext = Encoding.UTF8.GetBytes("Secret message to encrypt");

// Encrypt
EncryptResult encryptResult = await cryptoClient.EncryptAsync(
    EncryptionAlgorithm.RsaOaep256, 
    plaintext);
Console.WriteLine($"Encrypted: {Convert.ToBase64String(encryptResult.Ciphertext)}");

// Decrypt
DecryptResult decryptResult = await cryptoClient.DecryptAsync(
    EncryptionAlgorithm.RsaOaep256, 
    encryptResult.Ciphertext);
string decrypted = Encoding.UTF8.GetString(decryptResult.Plaintext);
// Consume decrypted plaintext without logging it.
封装和解封装密钥
// Key to wrap (e.g., AES key)
byte[] keyToWrap = new byte[32]; // 256-bit key
RandomNumberGenerator.Fill(keyToWrap);

// Wrap key
WrapResult wrapResult = await cryptoClient.WrapKeyAsync(
    KeyWrapAlgorithm.RsaOaep256, 
    keyToWrap);

// Unwrap key
UnwrapResult unwrapResult = await cryptoClient.UnwrapKeyAsync(
    KeyWrapAlgorithm.RsaOaep256, 
    wrapResult.EncryptedKey);
签名和验证
// Data to sign
byte[] data = Encoding.UTF8.GetBytes("Data to sign");

// Sign data (computes hash internally)
SignResult signResult = await cryptoClient.SignDataAsync(
    SignatureAlgorithm.RS256, 
    data);

// Verify signature
VerifyResult verifyResult = await cryptoClient.VerifyDataAsync(
    SignatureAlgorithm.RS256, 
    data, 
    signResult.Signature);
Console.WriteLine($"Signature valid: {verifyResult.IsValid}");

// Or sign pre-computed hash
using var sha256 = SHA256.Create();
byte[] hash = sha256.ComputeHash(data);

SignResult signHashResult = await cryptoClient.SignAsync(
    SignatureAlgorithm.RS256, 
    hash);

密钥解析器

using Azure.Security.KeyVault.Keys.Cryptography;

var resolver = new KeyResolver(new DefaultAzureCredential());

// Resolve key by ID to get CryptographyClient
var resolvedKey = await resolver.ResolveAsync(
    new Uri("https://myvault.vault.azure.net/keys/my-key/version"));

// The resolver returns a key-encryption-key interface for wrap/unwrap.
// For Encrypt/Decrypt, construct CryptographyClient with a validated key ID.

密钥轮换

// Rotate key (creates new version)
KeyVaultKey rotatedKey = await client.RotateKeyAsync("my-rsa-key");
Console.WriteLine($"New version: {rotatedKey.Properties.Version}");

// Get rotation policy
KeyRotationPolicy policy = await client.GetKeyRotationPolicyAsync("my-rsa-key");

// Update rotation policy
policy.ExpiresIn = "P90D"; // 90 days
policy.LifetimeActions.Add(new KeyRotationLifetimeAction
{
    Action = KeyRotationPolicyAction.Rotate,
    TimeBeforeExpiry = "P30D" // Rotate 30 days before expiry
});

await client.UpdateKeyRotationPolicyAsync("my-rsa-key", policy);

密钥类型参考

类型用途
KeyClient密钥管理操作
CryptographyClient加密操作
KeyResolver将密钥 ID 解析为 CryptographyClient
KeyVaultKey包含加密材料的密钥
KeyProperties密钥元数据(不含加密材料)
CreateRsaKeyOptionsRSA 密钥创建选项
CreateEcKeyOptionsEC 密钥创建选项
CreateOctKeyOptions对称密钥选项
EncryptResult加密结果
DecryptResult解密结果
SignResult签名结果
VerifyResult验证结果
WrapResult密钥封装结果
UnwrapResult密钥解封装结果

算法参考

加密算法
算法密钥类型描述
RsaOaepRSARSA-OAEP
RsaOaep256RSARSA-OAEP-256
Rsa15RSARSA 1.5(旧版)
A128GcmOctAES-128-GCM
A256GcmOctAES-256-GCM
签名算法
算法密钥类型描述
RS256RSARSASSA-PKCS1-v1_5 SHA-256
RS384RSARSASSA-PKCS1-v1_5 SHA-384
RS512RSARSASSA-PKCS1-v1_5 SHA-512
PS256RSARSASSA-PSS SHA-256
ES256ECECDSA P-256 SHA-256
ES384ECECDSA P-384 SHA-384
ES512ECECDSA P-521 SHA-512
密钥封装算法
算法密钥类型描述
RsaOaepRSARSA-OAEP
RsaOaep256RSARSA-OAEP-256
A128KWOctAES-128 密钥封装
A256KWOctAES-256 密钥封装

最佳实践

  1. 使用托管标识 — 优先使用 DefaultAzureCredential,而非机密
  2. 启用软删除 — 防止意外删除
  3. 使用 HSM 支持的密钥 — 对敏感密钥设置 HardwareProtected = true
  4. 实施密钥轮换 — 使用自动轮换策略
  5. 限制密钥操作 — 仅启用所需的 KeyOperations
  6. 设置过期日期 — 始终为密钥设置 ExpiresOn
  7. 使用特定版本 — 在生产环境中固定到特定版本
  8. 缓存 CryptographyClient — 重复用于多个操作

错误处理

using Azure;

try
{
    KeyVaultKey key = await client.GetKeyAsync("my-key");
}
catch (RequestFailedException ex) when (ex.Status == 404)
{
    Console.WriteLine("Key not found");
}
catch (RequestFailedException ex) when (ex.Status == 403)
{
    Console.WriteLine("Access denied - check RBAC permissions");
}
catch (RequestFailedException ex)
{
    Console.WriteLine($"Key Vault error: {ex.Status} - {ex.Message}");
}

必需的 RBAC 角色

角色权限
Key Vault Crypto Officer完整的密钥管理权限
Key Vault Crypto User使用密钥执行加密操作
Key Vault Reader读取密钥元数据

相关 SDK

SDK用途安装
Azure.Security.KeyVault.Keys密钥(此 SDK)dotnet add package Azure.Security.KeyVault.Keys
Azure.Security.KeyVault.Secrets机密dotnet add package Azure.Security.KeyVault.Secrets
Azure.Security.KeyVault.Certificates证书dotnet add package Azure.Security.KeyVault.Certificates
Azure.Identity身份验证dotnet add package Azure.Identity

参考链接

资源URL
NuGet 包https://www.nuget.org/packages/Azure.Security.KeyVault.Keys
API 参考https://learn.microsoft.com/dotnet/api/azure.security.keyvault.keys
快速入门https://learn.microsoft.com/azure/key-vault/keys/quick-create-net
GitHub 源码https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/keyvault/Azure.Security.KeyVault.Keys

适用场景

当要执行概述中描述的工作流或操作时,可使用此技能。

限制

  • 仅当任务明确符合上述范围时,才使用此技能。
  • 不要将输出视为可替代针对特定环境的验证、测试或专家审核。
  • 如果缺少必需的输入、权限、安全边界或成功标准,请暂停并请求澄清。

评论

支持 Markdown