-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathkms.ts
51 lines (41 loc) · 1.82 KB
/
kms.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import {
serviceClients, Session, cloudApi, waitForOperation, decodeMessage,
} from '@yandex-cloud/nodejs-sdk';
import { getEnv } from './utils/get-env';
import { log } from './utils/logger';
const {
kms: {
symmetric_key_service: { CreateSymmetricKeyRequest, DeleteSymmetricKeyRequest },
symmetric_key: { SymmetricAlgorithm },
symmetric_crypto_service: { SymmetricEncryptRequest, SymmetricDecryptRequest },
},
} = cloudApi;
(async () => {
const authToken = getEnv('YC_OAUTH_TOKEN');
const folderId = getEnv('YC_FOLDER_ID');
const session = new Session({ oauthToken: authToken });
const keyClient = session.client(serviceClients.SymmetricKeyServiceClient);
const cryptoClient = session.client(serviceClients.SymmetricCryptoServiceClient);
const keyCreateOp = await keyClient.create(CreateSymmetricKeyRequest.fromPartial({
folderId,
defaultAlgorithm: SymmetricAlgorithm.AES_256,
}));
const finishedKeyCreateOp = await waitForOperation(keyCreateOp, session);
if (finishedKeyCreateOp.response) {
const key = decodeMessage<cloudApi.kms.symmetric_key.SymmetricKey>(finishedKeyCreateOp.response);
const encrypted = await cryptoClient.encrypt(SymmetricEncryptRequest.fromPartial({
keyId: key.id,
plaintext: Buffer.from('example message'),
}));
log(`Got "${encrypted.ciphertext}" from KMS`);
const decrypted = await cryptoClient.decrypt(SymmetricDecryptRequest.fromPartial({
keyId: key.id,
ciphertext: encrypted.ciphertext,
}));
log(`Got "${decrypted.plaintext}" from KMS`);
const keyRemoveOp = await keyClient.delete(DeleteSymmetricKeyRequest.fromPartial({
keyId: key.id,
}));
await waitForOperation(keyRemoveOp, session);
}
})();