Skip to content

Instantly share code, notes, and snippets.

@faheemsharif-me
Created August 23, 2022 03:38
Show Gist options
  • Select an option

  • Save faheemsharif-me/a1b0a418876f923328f9ee8d63aa261e to your computer and use it in GitHub Desktop.

Select an option

Save faheemsharif-me/a1b0a418876f923328f9ee8d63aa261e to your computer and use it in GitHub Desktop.
KMS Encryption with Python - Encrypt Plain text with KMS and encodes the Cipher Text to Base64
import base64
import boto3
from botocore.exceptions import ClientError
AWS_REGION = 'us-east-1'
kms_client = boto3.client("kms", region_name=AWS_REGION)
def encrypt(secret, key_id):
try:
cipher_text = kms_client.encrypt(
KeyId=key_id,
Plaintext=bytes(secret, encoding='utf8'),
)
except ClientError:
logger.exception('Could not encrypt the string.')
raise
else:
return base64.b64encode(cipher_text["CiphertextBlob"])
if __name__ == '__main__':
SECRET = 'plain-text-secret@#$%^&(02)'
KEY_ID = '<Place KMS Key ID or Alias here>' ## When Using alias, prefix it with "alias/"
logger.info('Encrypting...')
kms = encrypt(SECRET, KEY_ID)
print('Encrypted string: ' + kms)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment