適切なプログラムの認証資格情報で KeyClient を作成し、次に CryptographyClient を作成します。このクライアントを使用して Azure Key Vault のキーを設定、更新、およびローテーションします。
暗号化アルゴリズムを選択する
SDK とその提供される列挙型と型を最大限に活用するため、次のセクションに進む前に暗号化アルゴリズムを選択します。
- RSA - Rivest–Shamir–Adleman
- AES GCM - Advanced Encryption Standard ガロア カウンター モード
- AES CBC - Advanced Encryption Standard 暗号ブロック チェーン
KnownEncryptionAlgorithms 列挙型を使用して、特定のアルゴリズムを選択します。
import {
KnownEncryptionAlgorithms
} from '@azure/keyvault-keys';
const myAlgorithm = KnownEncryptionAlgorithms.RSAOaep256
暗号化キーを取得する
暗号化および復号化で使用する Key Vault から KeyVaultKey 暗号化キーを作成または取得します。
キーを使用して暗号化と復号化を実施する
暗号化には、次のいずれかのパラメータ オブジェクトが必要です。
3 つのパラメータ オブジェクトはすべて、 algorithm
と plaintext
を暗号化に使用する必要があります。 RSA 暗号化パラメータの一例は以下になります。
import { DefaultAzureCredential } from '@azure/identity';
import {
CryptographyClient,
KeyClient,
KnownEncryptionAlgorithms
} from '@azure/keyvault-keys';
// get service client using AZURE_KEYVAULT_NAME environment variable
const credential = new DefaultAzureCredential();
const serviceClient = new KeyClient(
`https://${process.env.AZURE_KEYVAULT_NAME}.vault.azure.net`,
credential
);
// get existing key
const keyVaultKey = await serviceClient.getKey('myRsaKey');
if (keyVaultKey?.name) {
// get encryption client
const encryptClient = new CryptographyClient(keyVaultKey, credential);
// set data to encrypt
const originalInfo = 'Hello World';
// set encryption algorithm
const algorithm = KnownEncryptionAlgorithms.RSAOaep256;
// encrypt settings: RsaEncryptParameters | AesGcmEncryptParameters | AesCbcEncryptParameters
const encryptParams = {
algorithm,
plaintext: Buffer.from(originalInfo)
};
// encrypt
const encryptResult = await encryptClient.encrypt(encryptParams);
// ... hand off encrypted result to another process
// ... other process needs to decrypt data
// decrypt settings: DecryptParameters
const decryptParams = {
algorithm,
ciphertext: encryptResult.result
};
// decrypt
const decryptResult = await encryptClient.decrypt(decryptParams);
console.log(decryptResult.result.toString());
}
encryptParams オブジェクトは、暗号化のパラメータを設定します。 プロパティを設定するには、次の encrypt パラメータ オブジェクトを使用します。
decryptParams オブジェクトは、復号化のパラメータを設定します。 プロパティを設定するには、次の decrypt パラメータ オブジェクトを使用します。