Created
April 13, 2023 13:48
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example Output: