使用適當的程式設計驗證認證來建立 KeyClient,然後建立 CryptographyClient 及使用用戶端在 Azure Key Vault 中設定、更新及輪替金鑰。
簽署資料
簽署資料的一些建議:
- 簽署前雜湊大型資料
- 簽署前雜湊單向資料,例如密碼
- 可以直接簽署小型雙向資料
使用金鑰簽署及驗證大型或單向資料
若要簽署及驗證摘要訊息,請使用下列方法:
針對摘要訊息:
import { createHash } from "crypto";
import { DefaultAzureCredential } from '@azure/identity';
import {
CryptographyClient,
KeyClient,
KnownSignatureAlgorithms
} from '@azure/keyvault-keys';
// get service client
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 with key
const cryptoClient = new CryptographyClient(keyVaultKey, credential);
// get digest
const digestableData = "MyLargeOrOneWayData";
const digest = createHash('sha256')
.update(digestableData)
.update(process.env.SYSTEM_SALT || '')
.digest();
// sign digest
const { result: signature } = await cryptoClient.sign(KnownSignatureAlgorithms.RS256, digest);
// store signed digest in database
// verify signature
const { result: verified } = await cryptoClient.verify(KnownSignatureAlgorithms.RS256, digest, signature);
console.log(`Verification ${verified ? 'succeeded' : 'failed'}.`);
}
使用金鑰簽署及驗證小型資料
若要簽署及驗證您的資料,請使用下列方法:
針對資料:
- signData 用以簽署資料區塊。
- verifyData 用以驗證資料。
import { createHash } from "crypto";
import { DefaultAzureCredential } from '@azure/identity';
import {
CryptographyClient,
KeyClient,
KnownSignatureAlgorithms
} from '@azure/keyvault-keys';
// get service client
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 with key
const cryptoClient = new CryptographyClient(keyVaultKey, credential);
const data = 'Hello you bright big beautiful world!';
// sign
const { result: signature } = await cryptoClient.signData(
KnownSignatureAlgorithms.RS256,
Buffer.from(data, 'utf8')
);
// verify signature
const { result: verified } = await cryptoClient.verifyData(
KnownSignatureAlgorithms.RS256,
Buffer.from(data, 'utf8'),
signature
);
console.log(`Verification ${verified ? 'succeeded' : 'failed'}.`);
}