다음을 통해 공유


JavaScript를 사용하여 Azure Key Vault에서 키의 속성 만들기, 순환 및 업데이트

적절한 프로그래매틱 인증 자격 증명을 사용하여 KeyClient를 만든 다음, 클라이언트를 사용하여 Azure Key Vault에서 키를 설정, 업데이트 및 순환합니다.

키를 순환한다는 것은 새 버전의 키를 만들고 이 버전을 최신 버전으로 설정하는 것을 의미합니다. 이전 버전은 삭제되지 않지만 더 이상 활성 버전이 아닙니다.

순환 정책을 사용하여 키 만들기

Azure Key Vault에서 키를 만들려면 KeyClient 클래스의 createKey 메서드를 사용합니다. 선택 사항인 createKeyOptions 개체를 사용하여 속성을 설정합니다. 키를 만든 후 순환 정책으로 키를 업데이트합니다.

KeyVaultKey가 반환됩니다. 알림이 포함된 정책과 함께 updateKeyRotationPolicy를 사용하여 키를 업데이트합니다.

해당 키 형식과 연결된 속성을 설정하는 다음 키 형식에 편리한 create 메서드를 사용할 수 있습니다.

// Azure client libraries
import { DefaultAzureCredential } from '@azure/identity';
import {
  CreateKeyOptions,
  KeyClient,
  KeyRotationPolicyProperties,
  KnownKeyOperations,
  KnownKeyTypes
} from '@azure/keyvault-keys';

// Day/time manipulation
import dayjs from 'dayjs';
import duration from 'dayjs/plugin/duration';
dayjs.extend(duration);

// Authenticate to Azure Key Vault
const credential = new DefaultAzureCredential();
const client = new KeyClient(
    `https://${process.env.AZURE_KEYVAULT_NAME}.vault.azure.net`,
    credential
);

// Name of key
const keyName = `mykey-${Date.now().toString()}`;

// Set key options
const keyOptions: CreateKeyOptions = {
enabled: true,
expiresOn: dayjs().add(1, 'year').toDate(),
exportable: false,
tags: {
    project: 'test-project'
},
keySize: 2048,
keyOps: [
    KnownKeyOperations.Encrypt,
    KnownKeyOperations.Decrypt
    // KnownKeyOperations.Verify,
    // KnownKeyOperations.Sign,
    // KnownKeyOperations.Import,
    // KnownKeyOperations.WrapKey,
    // KnownKeyOperations.UnwrapKey
]
};

// Set key type
const keyType = KnownKeyTypes.RSA; //  'EC', 'EC-HSM', 'RSA', 'RSA-HSM', 'oct', 'oct-HSM'

// Create key
const key = await client.createKey(keyName, keyType, keyOptions);
if (key) {
    // Set rotation policy properties: KeyRotationPolicyProperties
    const rotationPolicyProperties: KeyRotationPolicyProperties = {
        expiresIn: 'P90D',
        lifetimeActions: [
        {
            action: 'Rotate',
            timeAfterCreate: 'P30D'
        },
        {
            action: 'Notify',
            timeBeforeExpiry: dayjs.duration({ days: 7 }).toISOString()
        }
    ]};
    
    // Set rotation policy: KeyRotationPolicy
    const keyRotationPolicy = await client.updateKeyRotationPolicy(
        key.name,
        rotationPolicyProperties
    );
    console.log(keyRotationPolicy);
}

수동으로 키 순환

키를 순환해야 하는 경우 rotateKey 메서드를 사용합니다. 그러면 새 버전의 키가 만들어지고 해당 버전이 활성 버전으로 설정됩니다.

// Azure client libraries
import { DefaultAzureCredential } from '@azure/identity';
import {
  KeyClient
} from '@azure/keyvault-keys';

// Authenticate to Azure Key Vault
const credential = new DefaultAzureCredential();
const client = new KeyClient(
    `https://${process.env.AZURE_KEYVAULT_NAME}.vault.azure.net`,
    credential
);

// Get existing key
let key = await client.getKey(`MyKey`);
console.log(key);

if(key?.name){

    // rotate key
    key = await client.rotateKey(key.name);
    console.log(key);
}

키 속성 업데이트

updateKeyProperties를 사용하여 최신 버전의 키 속성을 업데이트하거나 updateKeyProperties를 사용하여 특정 버전의 키를 업데이트합니다. 지정되지 않은 UpdateKeyPropertiesOptions 속성은 변경되지 않은 상태로 유지됩니다. 그러면 키 값이 변경되지 않습니다.

// Azure client libraries
import { DefaultAzureCredential } from '@azure/identity';
import {
  KeyClient
} from '@azure/keyvault-keys';

// Authenticate to Azure Key Vault
const credential = new DefaultAzureCredential();
const client = new KeyClient(
    `https://${process.env.AZURE_KEYVAULT_NAME}.vault.azure.net`,
    credential
);

// Get existing key
const key = await client.getKey('MyKey');

if (key) {

    // 
    const updateKeyPropertiesOptions = {
        enabled: false,
        // expiresOn,
        // keyOps,
        // notBefore, 
        // releasePolicy, 
        tags: { 
            ...key.properties.tags, subproject: 'Health and wellness' 
        }
    }
    
    // update properties of latest version
    await client.updateKeyProperties(
        key.name,
        updateKeyPropertiesOptions
    );
    
    // update properties of specific version
    await client.updateKeyProperties(
        key.name,
        key?.properties?.version,
        {
            enabled: true
        }
    );
}

키 값 업데이트

키 값을 업데이트하려면 rotateKey 메서드를 사용합니다. 현재 버전의 키에서 유지하려는 모든 속성을 사용하여 새 값을 전달해야 합니다. rotateKey에 대한 추가 호출에 설정되지 않은 현재 속성은 모두 손실됩니다.

이렇게 하면 새 버전의 키가 생성됩니다. 반환된 KeyVaultKey 개체에는 새 버전 ID가 포함됩니다.

다음 단계