Skip to content

Instantly share code, notes, and snippets.

@tomarv2
Created January 27, 2023 19:22
Show Gist options
  • Save tomarv2/b9c6ec6cab9446ac71ef4f64d6cc767f to your computer and use it in GitHub Desktop.
Save tomarv2/b9c6ec6cab9446ac71ef4f64d6cc767f to your computer and use it in GitHub Desktop.
encrypt_decrypt_using_kms.py
import base64
import boto3
REGION_NAME = "us-east-2"
# Decrypt value using AWS KMS Key
kmsclient = boto3.client('kms', region_name=REGION_NAME)
ciphertext = "encryted_value"
binary_data = base64.b64decode(ciphertext)
meta = kmsclient.decrypt(CiphertextBlob=binary_data)
plaintext = meta[u'Plaintext']
print(plaintext.decode())
decrypted_value = kmsclient.decrypt(CiphertextBlob=base64.b64decode(ciphertext))['Plaintext'].decode('utf-8')
print(decrypted_value)
# Encrypt value using AWS KMS Key
decrypted_value = "HelloWorld!"
kmsclient = boto3.client('kms', region_name=REGION_NAME)
key_id = 'arn:aws:kms:<aws_region>:XXXXXXXXXXXXXX:key/demokey'
stuff = kmsclient.encrypt(KeyId=key_id, Plaintext=decrypted_value)
binary_encrypted = stuff[u'CiphertextBlob']
encrypted_password = base64.b64encode(binary_encrypted)
print(encrypted_password.decode())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment