Skip to content

Instantly share code, notes, and snippets.

@nmarley
Last active May 29, 2024 06:01
Show Gist options
  • Save nmarley/99cec84a0b1b9fd87d3ae51c88d68fbb to your computer and use it in GitHub Desktop.
Save nmarley/99cec84a0b1b9fd87d3ae51c88d68fbb to your computer and use it in GitHub Desktop.
AWS KMS encryption/decryption using Python/Boto3
import boto3
import base64
if __name__ == '__main__':
session = boto3.session.Session()
kms = session.client('kms')
encrypted_password = 'AQECAHjgTiiE7TYRGp5Irf8jQ3HzlaQaHGYgsUJDaavnHcFm0gAAAGswaQYJKoZIhvcNAQcGoFwwWgIBADBVBgkqhkiG9w0BBwEwHgYJYIZIAWUDBAEuMBEEDDwxVQuG0oVwpkU7nQIBEIAoVGk1/wpserb+GVUOzE7PiL/Nr9fTDFKZfpKpF0ip2ct4B2q0Wn6ZZw=='
binary_data = base64.b64decode(encrypted_password)
meta = kms.decrypt(CiphertextBlob=binary_data)
plaintext = meta[u'Plaintext']
print(plaintext.decode())
import boto3
import base64
if __name__ == '__main__':
session = boto3.session.Session()
kms = session.client('kms')
key_id = 'alias/timesheets'
stuff = kms.encrypt(KeyId=key_id, Plaintext='S00pers33kr1t')
binary_encrypted = stuff[u'CiphertextBlob']
encrypted_password = base64.b64encode(binary_encrypted)
print(encrypted_password.decode())
boto3==1.4.8
botocore==1.8.1
docutils==0.14
futures==3.1.1
jmespath==0.9.3
python-dateutil==2.6.1
s3transfer==0.1.11
six==1.11.0
@onema
Copy link

onema commented Feb 27, 2018

This is a great gist, thank you!
Just an observation, I think the only requirement you need here is boto3.

@sithik4git
Copy link

It helps me. solving my issue. Tnx.
It seems it is not required to pass the key alias while decrypting. Is it so? Why?

@techypaul
Copy link

@sithik4git Yes, the encrypted data has the required key encoded within it.

@luisgradossalinas
Copy link

What a great contribution, I just needed this.
It helped me a lot, friend.

@balosh-daniel
Copy link

YES, thank you

@RajivReports
Copy link

Im trying to decrypt the data using AWS KMS key (encrypted). the above code is not working which gives below error. Can anyone pls help me on this.
" raise error_class(parsed_response, operation_name)
botocore.errorfactory.InvalidCiphertextException: An error occurred (InvalidCiph
ertextException) when calling the Decrypt operation:"

@bipeenmishra
Copy link

I have table in one database which has column level security applied to it, now I am performing some ETL operation on this table using glue job and writing this new table into another database after running glue job I am getting below error Py4JjavaError:An error occurred while calling 065.getDynamicFrame.java.lang.reflect.Invocation Target Exception

so my question is it is possible to perform ETL operation on column level security if yes than how can I do that plz inform me and give some reference.

Advance Thanks & regards

@YJL33
Copy link

YJL33 commented Nov 12, 2021

Great gist!

@satoshi-iwashita
Copy link

Thanks 🔥

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