公式ドキュメント の Source Code
では、ファイル経由で暗号化/複合化しますが、Base64 の方法も記録します。
公式ドキュメントの例
File
// [START kms_decrypt]
async function decrypt(
projectId = 'your-project-id', // Your GCP projectId
keyRingId = 'my-key-ring', // Name of the crypto key's key ring
cryptoKeyId = 'my-key', // Name of the crypto key, e.g. "my-key"
ciphertextFileName = './path/to/plaintext.txt.encrypted',
plaintextFileName = './path/to/plaintext.txt.decrypted'
) {
const fs = require('fs');
const {promisify} = require('util');
// Import the library and create a client
const kms = require('@google-cloud/kms');
const client = new kms.KeyManagementServiceClient();
// The location of the crypto key's key ring, e.g. "global"
const locationId = 'global';
// Reads the file to be decrypted
const readFile = promisify(fs.readFile);
const ciphertext = await readFile(ciphertextFileName);
const name = client.cryptoKeyPath(
projectId,
locationId,
keyRingId,
cryptoKeyId
);
// Decrypts the file using the specified crypto key
const [result] = await client.decrypt({name, ciphertext});
// Writes the decrypted file to disk
const writeFile = promisify(fs.writeFile);
await writeFile(plaintextFileName, result.plaintext);
console.log(
`Decrypted ${ciphertextFileName}, result saved to ${plaintextFileName}.`
);
}
// [END kms_decrypt]
Base64の例
Base64
const kms = require('@google-cloud/kms');
const PROJECT_ID = 'kms-project';
const KMS_KEYRING_LOCATION = 'asia-northeast1';
const KMS_KEYRING_ID = 'keyring-envs';
const KMS_KEY_ID = 'api-key';
const decode = async (text: string) => {
const client = new kms.KeyManagementServiceClient();
// 複合化キー情報
const name = client.cryptoKeyPath(PROJECT_ID, KMS_KEYRING_LOCATION, KMS_KEYRING_ID, KMS_KEY_ID);
// 複合する
const [result] = await client.decrypt({ name, ciphertext: text });
// Base64から変換する
return Buffer.from(result.plaintext, 'base64').toString();
};