(
projectId = 'my-project',
locationId = 'us-east1',
keyRingId = 'my-key-ring',
keyId = 'my-key',
plaintextBuffer = Buffer.from('...')
)
| 15 | 'use strict'; |
| 16 | |
| 17 | async function main( |
| 18 | projectId = 'my-project', |
| 19 | locationId = 'us-east1', |
| 20 | keyRingId = 'my-key-ring', |
| 21 | keyId = 'my-key', |
| 22 | plaintextBuffer = Buffer.from('...') |
| 23 | ) { |
| 24 | // [START kms_encrypt_symmetric] |
| 25 | // |
| 26 | // TODO(developer): Uncomment these variables before running the sample. |
| 27 | // |
| 28 | // const projectId = 'my-project'; |
| 29 | // const locationId = 'us-east1'; |
| 30 | // const keyRingId = 'my-key-ring'; |
| 31 | // const keyId = 'my-key'; |
| 32 | // const plaintextBuffer = Buffer.from('...'); |
| 33 | |
| 34 | // Imports the Cloud KMS library |
| 35 | const {KeyManagementServiceClient} = require('@google-cloud/kms'); |
| 36 | |
| 37 | // Instantiates a client |
| 38 | const client = new KeyManagementServiceClient(); |
| 39 | |
| 40 | // Build the key name |
| 41 | const keyName = client.cryptoKeyPath(projectId, locationId, keyRingId, keyId); |
| 42 | |
| 43 | // Optional, but recommended: compute plaintext's CRC32C. |
| 44 | const crc32c = require('fast-crc32c'); |
| 45 | const plaintextCrc32c = crc32c.calculate(plaintextBuffer); |
| 46 | |
| 47 | async function encryptSymmetric() { |
| 48 | const [encryptResponse] = await client.encrypt({ |
| 49 | name: keyName, |
| 50 | plaintext: plaintextBuffer, |
| 51 | plaintextCrc32c: { |
| 52 | value: plaintextCrc32c, |
| 53 | }, |
| 54 | }); |
| 55 | |
| 56 | const ciphertext = encryptResponse.ciphertext; |
| 57 | |
| 58 | // Optional, but recommended: perform integrity verification on encryptResponse. |
| 59 | // For more details on ensuring E2E in-transit integrity to and from Cloud KMS visit: |
| 60 | // https://cloud.google.com/kms/docs/data-integrity-guidelines |
| 61 | if (!encryptResponse.verifiedPlaintextCrc32c) { |
| 62 | throw new Error('Encrypt: request corrupted in-transit'); |
| 63 | } |
| 64 | if ( |
| 65 | crc32c.calculate(ciphertext) !== |
| 66 | Number(encryptResponse.ciphertextCrc32c.value) |
| 67 | ) { |
| 68 | throw new Error('Encrypt: response corrupted in-transit'); |
| 69 | } |
| 70 | |
| 71 | console.log(`Ciphertext: ${ciphertext.toString('base64')}`); |
| 72 | return ciphertext; |
| 73 | } |
| 74 |
no test coverage detected