.NET용 Azure Key Vault 키 클라이언트 라이브러리 - 버전 4.5.0

Azure Key Vault 데이터를 암호화하기 위한 키의 보안 스토리지를 제공하는 클라우드 서비스입니다. 여러 키와 동일한 키의 여러 버전을 Azure Key Vault 유지할 수 있습니다. Azure Key Vault 암호화 키는 JWK(JSON 웹 키) 개체로 표시됩니다.

Azure Key Vault 관리형 HSM은 FIPS 140-2 수준 3 유효성 검사 HSM을 사용하여 클라우드 애플리케이션에 대한 암호화 키를 보호할 수 있는 완전 관리형 고가용성 단일 테넌트 표준 규격 클라우드 서비스입니다.

Azure Key Vault 키 라이브러리 클라이언트는 RSA 키 및 EC(타원 곡선) 키를 지원하며, 각각 HSM(하드웨어 보안 모듈)에서 해당 지원을 제공합니다. 키와 해당 버전을 만들고, 검색, 업데이트, 삭제, 제거, 백업, 복원 및 나열하는 작업을 제공합니다.

소스 코드 | 패키지(NuGet) | API 참조 설명서 | 제품 설명서 | 샘플 | 마이그레이션 가이드

시작

패키지 설치

NuGet을 사용하여 .NET용 Azure Key Vault 키 클라이언트 라이브러리를 설치합니다.

dotnet add package Azure.Security.KeyVault.Keys

필수 구성 요소

  • Azure 구독.
  • 기존 Azure Key Vault. Azure Key Vault 만들어야 하는 경우 Azure Portal 또는 Azure CLI를 사용할 수 있습니다.
  • RBAC(권장) 또는 액세스 제어를 사용하여 기존 Azure Key Vault 권한 부여

표준 Key Vault 리소스를 만드는 경우 및 를 고유한 고유한 이름으로 바꾸는 <your-resource-group-name><your-key-vault-name> 다음 CLI 명령을 실행합니다.

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 Key Vault 서비스와 상호 작용하려면 KeyClient 클래스의 instance 만들어야 합니다. 포털에서 "DNS 이름"으로 표시할 수 있는 자격 증명 모음 URL과 클라이언트 개체를 인스턴스화하기 위한 자격 증명이 필요합니다.

아래에 표시된 예제에서는 관리 ID 인증을 DefaultAzureCredential활용하는 로컬 개발 및 프로덕션 환경을 비롯한 대부분의 시나리오에 적합한 를 사용합니다. 또한 프로덕션 환경에서 인증에 관리 ID를 사용하는 것이 좋습니다. Azure ID 설명서에서 다양한 인증 방법 및 해당 자격 증명 형식에 대한 자세한 정보를 찾을 수 있습니다.

아래에 표시된 공급자 또는 Azure SDK와 함께 제공되는 다른 자격 증명 공급자를 사용 DefaultAzureCredential 하려면 먼저 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 하여 클라이언트에 전달합니다. 동일한 ID로 인증하는 경우 토큰 자격 증명의 동일한 instance 여러 클라이언트에서 사용할 수 있습니다.

// 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 Key Vault 만든 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 Key Vault 여러 키 유형 및 알고리즘을 지원하며 높은 값의 키에 HSM(하드웨어 보안 모듈)을 사용할 수 있습니다.

KeyClient

동기 및 비동기 작업을 모두 제공하는 는 KeyClient 애플리케이션의 사용 사례에 따라 클라이언트를 선택할 수 있도록 SDK에 존재합니다. 를 초기화KeyClient한 후에는 Azure Key Vault 기본 리소스 유형과 상호 작용할 수 있습니다.

CryptographyClient

동기 및 비동기 작업을 모두 제공하는 는 CryptographyClient 애플리케이션의 사용 사례에 따라 클라이언트를 선택할 수 있도록 SDK에 존재합니다. 를 초기화CryptographyClient한 후에는 Azure Key Vault 저장된 키로 암호화 작업을 수행하는 데 사용할 수 있습니다.

스레드로부터의 안전성

모든 클라이언트 instance 메서드는 스레드로부터 안전하고 서로 독립적임을 보장합니다(지침). 이렇게 하면 스레드 간에 클라이언트 인스턴스를 다시 사용하는 것이 항상 안전합니다.

추가 개념

클라이언트 옵션 | 응답 | 에 액세스 장기 실행 작업 | 오류 | 처리 진단 | 조롱 | 클라이언트 수명

예제

Azure.Security.KeyVault.Keys 패키지는 동기 및 비동기 API를 지원합니다.

다음 섹션에서는 위에서 만든 를 사용하여 client 가장 일반적인 Azure Key Vault 주요 서비스 관련 작업을 다루는 여러 코드 조각을 제공합니다.

동기화 예제

비동기 예제

키 만들기

Azure Key Vault 저장할 키를 만듭니다. 이름이 같은 키가 이미 있는 경우 새 버전의 키가 만들어집니다.

// 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 Key Vault 저장된 키를 검색합니다.

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

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

기존 키 업데이트

UpdateKeyProperties는 이전에 Azure Key Vault 저장된 키를 업데이트합니다.

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 Key Vault 이전에 저장된 키를 삭제하는 장기 실행 작업을 시작합니다. 작업이 완료 될 때까지 기다리지 않고 키를 즉시 검색 할 수 있습니다. Azure Key Vault 일시 삭제를 사용하도록 설정하지 않으면 이 작업은 키를 영구적으로 삭제합니다.

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 Key Vault 모든 키를 나열합니다.

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

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

암호화 및 암호 해독

이 예제에서는 을 CryptographyClient 만들고 Azure Key Vault 키로 암호화하고 암호 해독하는 데 사용합니다.

// 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는 동기 API와 동일하지만 비동기 메서드에 대한 일반적인 "비동기" 접미사를 사용하여 반환하고 작업을 반환합니다.

// 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 의존하지 않지만 문과 함께 사용할 수 있는 을 await foreach 반환 AsyncPageable<KeyProperties> 합니다.

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 Key Vault 키 클라이언트 라이브러리와 상호 작용하는 경우 서비스에서 반환되는 오류는 REST API 요청에 대해 반환된 동일한 HTTP 상태 코드에 해당합니다.

예를 들어 Azure Key Vault 존재하지 않는 키를 검색하려고 하면 "찾을 수 없음"을 404 나타내는 오류가 반환됩니다.

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

작업의 클라이언트 요청 ID와 같은 추가 정보가 기록됩니다.

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 Key Vault 키 클라이언트 라이브러리 샘플을 사용할 수 있습니다. 이러한 샘플은 Azure Key Vault 작업하는 동안 일반적으로 발생하는 추가 시나리오에 대한 예제 코드를 제공합니다.

  • Sample1_HelloWorld.md - 다음을 포함하여 Azure Key Vault 작업하기 위한 것입니다.

    • 키 만들기
    • 기존 키 가져오기
    • 기존 키 업데이트
    • 키 삭제
  • Sample2_BackupAndRestore.md - 다음을 포함하여 Azure Key Vault 키로 작업하는 코드 조각을 포함합니다.

    • 키 백업 및 복구
  • Sample3_GetKeys.md - 다음을 포함하여 Azure Key Vault 키 작업을 위한 예제 코드입니다.

    • 키 만들기
    • Key Vault 모든 키 나열
    • Key Vault 키 업데이트
    • 지정된 키의 버전 나열
    • Key Vault 키 삭제
    • Key Vault 삭제된 키 나열
  • Sample4_EncryptDecrypt.md - 다음을 포함하여 Azure Key Vault 키를 사용하여 암호화 작업을 수행하기 위한 예제 코드입니다.

    • CryptographyClient를 사용하여 데이터 암호화 및 암호 해독
  • Sample5_SignVerify.md - 다음을 포함하여 Azure Key Vault 키로 작업하기 위한 예제 코드입니다.

    • 미리 계산된 다이제스트에 서명하고 서명 및 확인을 사용하여 서명을 확인합니다.
    • 원시 데이터에 서명하고 SignData 및 VerifyData를 사용하여 서명을 확인합니다.
  • Sample6_WrapUnwrap.md - 다음을 포함하여 Azure Key Vault 키 작업을 위한 예제 코드입니다.

    • 대칭 키 래핑 및 래핑 해제

추가 설명서

참여

이러한 라이브러리를 빌드, 테스트 및 기여하는 방법에 대한 자세한 내용은 CONTRIBUTING.md 참조하세요.

이 프로젝트에 대한 기여와 제안을 환영합니다. 대부분의 경우 기여하려면 권한을 부여하며 실제로 기여를 사용할 권한을 당사에 부여한다고 선언하는 CLA(기여자 라이선스 계약)에 동의해야 합니다. 자세한 내용은 https://cla.microsoft.com 을 참조하세요.

끌어오기 요청을 제출하면 CLA-bot은 CLA를 제공하고 PR을 적절하게 데코레이팅해야 하는지 여부를 자동으로 결정합니다(예: 레이블, 설명). 봇에서 제공하는 지침을 따르기만 하면 됩니다. 이 작업은 CLA를 사용하여 모든 리포지토리에서 한 번만 수행하면 됩니다.

이 프로젝트에는 Microsoft Open Source Code of Conduct(Microsoft 오픈 소스 준수 사항)가 적용됩니다. 자세한 내용은 Code of Conduct FAQ(규정 FAQ)를 참조하세요. 또는 추가 질문이나 의견은 opencode@microsoft.com으로 문의하세요.

Impressions