Skip to content

Instantly share code, notes, and snippets.

@raphaelgabbarelli
Created May 23, 2020 21:41
Show Gist options
  • Save raphaelgabbarelli/bc5a41d93789046f9c71e4685f1463e7 to your computer and use it in GitHub Desktop.
Save raphaelgabbarelli/bc5a41d93789046f9c71e4685f1463e7 to your computer and use it in GitHub Desktop.
encrypt and dectypt with AWS KMS
import boto3
import base64
key_id = 'de5bb9e8-6526-49bc-822f-4e8a70ea7a19'
def hello_kms():
session = boto3.session.Session(profile_name='caveman')
client = session.client('kms')
encryption_result = client.encrypt(KeyId=key_id,
Plaintext='hello, kms!')
blob = encryption_result['CiphertextBlob']
print(base64.b64encode(blob))
encrypted_text = 'AQICAHiSlodFOEUS/C7q2g4iQJwHune3s0bOhgRrXt1frVNdEQHe24+3H6mXLL2Y02Ck4qenAAAAaTBnBgkqhkiG9w0BBwagWjBYAgEAMFMGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMKXU3aoKqQeEFtkduAgEQgCbxscVZZNctXP9sslbd34hAbIaidVYteEokvBkzykdZMGbPHq9hcA=='
decrypted = client.decrypt(CiphertextBlob=base64.b64decode(encrypted_text))
print(decrypted['Plaintext'])
if __name__ == "__main__":
hello_kms()
@cafruv
Copy link

cafruv commented Dec 1, 2022

I was trapped to use cli command aws kms encrypt --key-id xxxx --plaintext testext --output text and got a string very similar to the encrypted_text above.
Finally I have to use this script to regenerate the encrypted_text and my code worked.
Thank you.

@cafruv
Copy link

cafruv commented Dec 1, 2022

Then trapped by running aws kms decrypt --ciphertext-blob xxxx and got good result.
But when I used the wrong encrypted_text in my python code. Broken.
This caused me 4 hours.

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