Skip to content

Commit fa6928a

Browse files
sethvargobcoe
authored andcommitted
feat(samples): add asymmetric samples (#241)
1 parent 0a43a06 commit fa6928a

7 files changed

+499
-4
lines changed

kms/asymmetricDecrypt.js

+68
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
// Copyright 2019 Google LLC
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// https://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
'use strict';
16+
17+
// [START kms_asymmetric_decrypt]
18+
async function asymmetricDecrypt(
19+
projectId = 'your-project-id', // Your GCP projectId
20+
keyRingId = 'my-key-ring', // Name of the crypto key's key ring
21+
cryptoKeyId = 'my-key', // Name of the crypto key, e.g. "my-key"
22+
cryptoKeyVersionId = '1', // Version of the crypto key to use
23+
ciphertextBuffer = '...' // Buffer containing ciphertext to decrypt
24+
) {
25+
// Import the library and create a client
26+
const kms = require('@google-cloud/kms');
27+
const client = new kms.KeyManagementServiceClient();
28+
29+
// The location of the crypto key's key ring, e.g. "global"
30+
const locationId = 'global';
31+
32+
// Construct the cyrpto key version ID
33+
const name = client.cryptoKeyVersionPath(
34+
projectId,
35+
locationId,
36+
keyRingId,
37+
cryptoKeyId,
38+
cryptoKeyVersionId
39+
);
40+
41+
// Decrypt plaintext using Cloud KMS
42+
//
43+
// NOTE: The ciphertext must be properly formatted. In Node < 12, the
44+
// crypto.publicEncrypt() function does not properly consume the OAEP padding
45+
// and thus produces invalid ciphertext. If you are using Node to do public
46+
// key encryption, please use version 12+.
47+
const [result] = await client.asymmetricDecrypt({
48+
name: name,
49+
ciphertext: ciphertextBuffer,
50+
});
51+
const plaintext = result.plaintext.toString('utf8');
52+
53+
// Example of printing results
54+
console.log(`Decrypted plaintext: ${plaintext}`);
55+
56+
return plaintext;
57+
}
58+
// [END kms_asymmetric_decrypt]
59+
60+
const args = process.argv.slice(2);
61+
62+
// Base64-decode the ciphertext argument. The tests invoke these files via the
63+
// shell, which doesn't support transferring a binary stream. As such, they
64+
// encode the data first, so we need to decode it here before passing it to the
65+
// function.
66+
args[4] = Buffer.from(args[4], 'base64');
67+
68+
asymmetricDecrypt(...args).catch(console.error);

kms/asymmetricEncrypt.js

+76
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
// Copyright 2019 Google LLC
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// https://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
'use strict';
16+
17+
// [START kms_asymmetric_encrypt]
18+
async function asymmetricEncrypt(
19+
projectId = 'your-project-id', // Your GCP projectId
20+
keyRingId = 'my-key-ring', // Name of the crypto key's key ring
21+
cryptoKeyId = 'my-key', // Name of the crypto key, e.g. "my-key"
22+
cryptoKeyVersionId = '1', // Version of the crypto key to use
23+
plaintext = 'my data to encrypt' // Plaintext data to encrypt
24+
) {
25+
// Import the library and create a client
26+
const kms = require('@google-cloud/kms');
27+
const client = new kms.KeyManagementServiceClient();
28+
29+
// The location of the crypto key's key ring, e.g. "global"
30+
const locationId = 'global';
31+
32+
// Construct the cyrpto key version ID
33+
const name = client.cryptoKeyVersionPath(
34+
projectId,
35+
locationId,
36+
keyRingId,
37+
cryptoKeyId,
38+
cryptoKeyVersionId
39+
);
40+
41+
// Get public key from Cloud KMS
42+
const [publicKey] = await client.getPublicKey({name: name});
43+
44+
// Import and setup crypto
45+
const crypto = require('crypto');
46+
const plaintextBuffer = Buffer.from(plaintext);
47+
48+
// Encrypt plaintext locally using the public key. This example uses a key
49+
// that was configured with sha256 hash with OAEP padding. Update these values
50+
// to match the Cloud KMS key.
51+
//
52+
// NOTE: In Node < 12, this function does not properly consume the OAEP
53+
// padding and thus produces invalid ciphertext. If you are using Node to do
54+
// public key encryption, please use version 12+.
55+
const encryptedBuffer = crypto.publicEncrypt(
56+
{
57+
key: publicKey.pem,
58+
oaepHash: 'sha256',
59+
padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
60+
},
61+
plaintextBuffer
62+
);
63+
64+
// Example of how to display ciphertext. Because the ciphertext is in a binary
65+
// format, you need to encode the output before printing it to a console or
66+
// displaying it on a screen.
67+
const encoded = encryptedBuffer.toString('base64');
68+
console.log(`Encrypted ciphertext: ${encoded}`);
69+
70+
// Return the ciphertext buffer
71+
return encryptedBuffer;
72+
}
73+
// [END kms_asymmetric_encrypt]
74+
75+
const args = process.argv.slice(2);
76+
asymmetricEncrypt(...args).catch(console.error);

kms/asymmetricSign.js

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
// Copyright 2019 Google LLC
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// https://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
'use strict';
16+
17+
// [START kms_asymmetric_sign]
18+
async function asymmetricSign(
19+
projectId = 'your-project-id', // Your GCP projectId
20+
keyRingId = 'my-key-ring', // Name of the crypto key's key ring
21+
cryptoKeyId = 'my-key', // Name of the crypto key, e.g. "my-key"
22+
cryptoKeyVersionId = '1', // Version of the crypto key to use
23+
message = 'my message to sign' // Message data to sign
24+
) {
25+
// Import the library and create a client
26+
const kms = require('@google-cloud/kms');
27+
const client = new kms.KeyManagementServiceClient();
28+
29+
// The location of the crypto key's key ring, e.g. "global"
30+
const locationId = 'global';
31+
32+
// Construct the cyrpto key version ID
33+
const name = client.cryptoKeyVersionPath(
34+
projectId,
35+
locationId,
36+
keyRingId,
37+
cryptoKeyId,
38+
cryptoKeyVersionId
39+
);
40+
41+
// Create a digest of the message. The digest needs to match the digest
42+
// configured for the Cloud KMS key.
43+
const crypto = require('crypto');
44+
const digest = crypto.createHash('sha384');
45+
digest.update(message);
46+
47+
// Sign the message with Cloud KMS
48+
const [result] = await client.asymmetricSign({
49+
name: name,
50+
digest: {
51+
sha384: digest.digest(),
52+
},
53+
});
54+
55+
// Example of how to display signature. Because the signature is in a binary
56+
// format, you need to encode the output before printing it to a console or
57+
// displaying it on a screen.
58+
const encoded = result.signature.toString('base64');
59+
console.log(`Signature: ${encoded}`);
60+
61+
// Return the signature buffer
62+
return result.signature;
63+
}
64+
// [END kms_asymmetric_sign]
65+
66+
const args = process.argv.slice(2);
67+
asymmetricSign(...args).catch(console.error);

kms/asymmetricVerify.js

+70
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
// Copyright 2019 Google LLC
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// https://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
'use strict';
16+
17+
// [START kms_asymmetric_verify]
18+
async function asymmetricVerify(
19+
projectId = 'your-project-id', // Your GCP projectId
20+
keyRingId = 'my-key-ring', // Name of the crypto key's key ring
21+
cryptoKeyId = 'my-key', // Name of the crypto key, e.g. "my-key"
22+
cryptoKeyVersionId = '1', // Version of the crypto key to use
23+
message = 'my message to verify', // Message data to verify
24+
signatureBuffer = '...' // Buffer containing signature to decrypt
25+
) {
26+
// Import the library and create a client
27+
const kms = require('@google-cloud/kms');
28+
const client = new kms.KeyManagementServiceClient();
29+
30+
// The location of the crypto key's key ring, e.g. "global"
31+
const locationId = 'global';
32+
33+
// Construct the cyrpto key version ID
34+
const name = client.cryptoKeyVersionPath(
35+
projectId,
36+
locationId,
37+
keyRingId,
38+
cryptoKeyId,
39+
cryptoKeyVersionId
40+
);
41+
42+
// Get public key from Cloud KMS
43+
const [publicKey] = await client.getPublicKey({name: name});
44+
45+
// Create the verifier. The algorithm must match the algorithm of the key.
46+
const crypto = require('crypto');
47+
const verify = crypto.createVerify('SHA384');
48+
verify.write(message);
49+
verify.end();
50+
51+
// Verify the signature using the public key
52+
const verified = verify.verify(publicKey.pem, signatureBuffer);
53+
54+
// Example of printing result
55+
console.log(`Signature verified: ${verified}`);
56+
57+
// Return boolean result
58+
return verified;
59+
}
60+
// [END kms_asymmetric_verify]
61+
62+
const args = process.argv.slice(2);
63+
64+
// Base64-decode the signature argument. The tests invoke these files via the
65+
// shell, which doesn't support transferring a binary stream. As such, they
66+
// encode the data first, so we need to decode it here before passing it to the
67+
// function.
68+
args[5] = Buffer.from(args[5], 'base64');
69+
70+
asymmetricVerify(...args).catch(console.error);

kms/getPublicKey.js

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
// Copyright 2019 Google LLC
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// https://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
'use strict';
16+
17+
// [START kms_get_public_key]
18+
async function getPublicKey(
19+
projectId = 'your-project-id', // Your GCP projectId
20+
keyRingId = 'my-key-ring', // Name of the crypto key's key ring
21+
cryptoKeyId = 'my-key', // Name of the crypto key, e.g. "my-key"
22+
cryptoKeyVersionId = '1' // Version of the crypto key to fetch
23+
) {
24+
// Import the library and create a client
25+
const kms = require('@google-cloud/kms');
26+
const client = new kms.KeyManagementServiceClient();
27+
28+
// The location of the crypto key's key ring, e.g. "global"
29+
const locationId = 'global';
30+
31+
// Construct the cyrpto key version ID
32+
const name = client.cryptoKeyVersionPath(
33+
projectId,
34+
locationId,
35+
keyRingId,
36+
cryptoKeyId,
37+
cryptoKeyVersionId
38+
);
39+
40+
// Get public key from Cloud KMS
41+
const [publicKey] = await client.getPublicKey({name: name});
42+
43+
// Return the public key pem
44+
return publicKey.pem;
45+
}
46+
// [END kms_get_public_key]
47+
48+
const args = process.argv.slice(2);
49+
getPublicKey(...args).catch(console.error);

kms/package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
"devDependencies": {
2020
"chai": "^4.2.0",
2121
"mocha": "^6.0.0",
22-
"uuid": "^3.2.1",
22+
"uuid": "^3.3.3",
2323
"yargs": "^15.0.0"
2424
}
2525
}

0 commit comments

Comments
 (0)