MCPcopy Create free account
hub / github.com/GoogleCloudPlatform/nodejs-docs-samples / encryptAsymmetric

Function encryptAsymmetric

kms/encryptAsymmetric.js:51–89  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

49 );
50
51 async function encryptAsymmetric() {
52 // Get public key from Cloud KMS
53 const [publicKey] = await client.getPublicKey({
54 name: versionName,
55 });
56
57 // Optional, but recommended: perform integrity verification on publicKey.
58 // For more details on ensuring E2E in-transit integrity to and from Cloud KMS visit:
59 // https://cloud.google.com/kms/docs/data-integrity-guidelines
60 const crc32c = require('fast-crc32c');
61 if (publicKey.name !== versionName) {
62 throw new Error('GetPublicKey: request corrupted in-transit');
63 }
64 if (crc32c.calculate(publicKey.pem) !== Number(publicKey.pemCrc32c.value)) {
65 throw new Error('GetPublicKey: response corrupted in-transit');
66 }
67
68 // Import and setup crypto
69 const crypto = require('crypto');
70
71 // Encrypt plaintext locally using the public key. This example uses a key
72 // that was configured with sha256 hash with OAEP padding. Update these
73 // values to match the Cloud KMS key.
74 //
75 // NOTE: In Node < 12, this function does not properly consume the OAEP
76 // padding and thus produces invalid ciphertext. If you are using Node to do
77 // public key encryption, please use version 12+.
78 const ciphertextBuffer = crypto.publicEncrypt(
79 {
80 key: publicKey.pem,
81 oaepHash: 'sha256',
82 padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
83 },
84 plaintextBuffer
85 );
86
87 console.log(`Ciphertext: ${ciphertextBuffer.toString('base64')}`);
88 return ciphertextBuffer;
89 }
90
91 return encryptAsymmetric();
92 // [END kms_encrypt_asymmetric]

Callers 1

mainFunction · 0.85

Calls 1

toStringMethod · 0.80

Tested by

no test coverage detected