使用適當的程式設計驗證認證來建立 KeyClient,然後建立 CryptographyClient 及使用用戶端在 Azure Key Vault 中設定、更新及輪替金鑰。
選取加密演算法
若要充分利用 SDK 及其提供的列舉和類型,請先選取您的加密演算法,再繼續進行下一節。
- RSA - Rivest–Shamir–Adleman
- AES GCM - 進階加密標準 Galois 計數器模式
- AES CBC - 進階加密標準加密區塊鏈結
使用 KnownEncryptionAlgorithms 列舉來選取特定演算法。
import {
KnownEncryptionAlgorithms
} from '@azure/keyvault-keys';
const myAlgorithm = KnownEncryptionAlgorithms.RSAOaep256
取得加密金鑰
從 Key Vault 建立或取得 KeyVaultKey 加密金鑰,以用於加密和解密。
使用金鑰加密和解密
加密需要下列其中一項參數物件:
這三個參數物件都需要用於加密的 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 物件會設定加密參數。 使用下列加密參數物件來設定屬性。
decryptParams 物件會設定解密參數。 使用下列解密參數物件來設定屬性。