Skip to content

Instantly share code, notes, and snippets.

@renatoargh
Created April 13, 2023 13:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save renatoargh/901bf9289ce65683f77aa898d0c77146 to your computer and use it in GitHub Desktop.
Save renatoargh/901bf9289ce65683f77aa898d0c77146 to your computer and use it in GitHub Desktop.
Shows how to retrieve a public key from KMS, encrypt a random string outside of AWS, decrypt using the Decrypt command and to format the key as JWK
const { createPublicKey, publicEncrypt } = require('crypto')
import {
KMSClient,
DecryptCommand,
GetPublicKeyCommand,
} from '@aws-sdk/client-kms'
// Change the next 2 lines
const keyId = '00000000-0000-0000-0000-000000000000';
const region = 'us-east-1';
const plaintext = 'potato'
async function main() {
const client = new KMSClient({ region })
const getPublicKeyCommand = new GetPublicKeyCommand({ KeyId: keyId })
const { PublicKey: publicKeyBuffer } = await client.send(getPublicKeyCommand);
if (!publicKeyBuffer) {
throw new Error('Public key data was not returned')
}
const publicKey = createPublicKey({
key: Buffer.from(publicKeyBuffer),
format: 'der',
type: 'spki'
})
console.log('ORIGINAL PLAIN TEXT:', plaintext, '\n')
const nodeEncrypted = publicEncrypt(publicKey, Buffer.from(plaintext))
console.log('NODEJS ENCRYPTED:', nodeEncrypted.toString('base64'), '\n')
const decryptCommand = new DecryptCommand({
KeyId: keyId,
CiphertextBlob: nodeEncrypted,
EncryptionAlgorithm: 'RSAES_OAEP_SHA_1',
})
const { Plaintext: awsDecryptedBuffer } = await client.send(decryptCommand);
if (!awsDecryptedBuffer) {
throw new Error('No plantext returned from decryption')
}
const awsDecrypted = Buffer.from(awsDecryptedBuffer).toString()
console.log('AWS DECRYPTED:', awsDecrypted, '\n')
console.log('ENCRYPTION-DECRYPTION WORKS:', plaintext === awsDecrypted, '\n')
const jwk = publicKey.export({ format: 'jwk' })
console.log('JWK ENCODED PUBLIC KEY:', JSON.stringify(jwk, null, 2))
}
main()
@renatoargh
Copy link
Author

Example Output:

ORIGINAL PLAIN TEXT: potato 

NOD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miAnyoYKxfJuZmvblwjg-d6fEP8CQyzomdUbXgBJDk7kh5FlwS0YcaAxMapDMkaFm4GSx_QJC0HFRmw7R1EBAO1MpQ91dJZgUrWW6Pn0y2cijCyBZLzMQp6f1bugAG7peAxsRjXGfCzD1FML3U1fksotTu_XH5NcUCOFGs-Ogk4sBZPYymSLvVw3zkIN6iGcGRGyLFqOdZq9WQEOcvJ9gMuJpa_OAYYWWFjZdRTEdMd4ZFpAVJ3ulotCZp25mg4ppZDddeQz81EyIkchmmTdvN9k1u979CpN5sw-1rhY3tvr1B2BKD1JomhEwAhYAwdKe_a93fT8XR--Vk8Rtf-TD-OSOKheK8wekS0bYcCSrVyQzhfq7r-eU",
  "e": "AQAB"
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment