Skip to content

Instantly share code, notes, and snippets.

@Parassharmaa
Last active August 8, 2023 13:54
Show Gist options
  • Select an option

  • Save Parassharmaa/fe693f6afc9cd358efd0427d0f57dbfb to your computer and use it in GitHub Desktop.

Select an option

Save Parassharmaa/fe693f6afc9cd358efd0427d0f57dbfb to your computer and use it in GitHub Desktop.
AWS KMS (Encryption and Decryption)
import boto3
import base64
kms = boto3.client('kms')
keyId = kms.create_key()['KeyId']
# to encrypt data less than 4KB (usually for secret and access tokens)
randomData = 'Hello world'
base64.b64encode(kms.encrypt(KeyId=keyid, Plaintext=randomData)['CiphertextBlob'])
'''
Encrypted Data:
b'AQICAHg3OyiHM4N/5/T1gtusbsPh2/zp72dkCfbVXGpNLVChmgHJ5u/UCVGWhAzREeLHliLtAAAAaDBmBgkqhkiG9w0BBwagWTBXAgEAMFIGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMwJHnpWPmlA5PiKZ3AgEQgCX/JUXRTEWOKryUHvbnLXTXpjtgw/bWr82JM8eHj/dflU6eoF81'
'''
import boto3
import base64
kms = boto3.client('kms')
encrytedData = b'AQICAHg3OyiHM4N/5/T1gtusbsPh2/zp72dkCfbVXGpNLVChmgHJ5u/UCVGWhAzREeLHliLtAAAAaDBmBgkqhkiG9w0BBwagWTBXAgEAMFIGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMwJHnpWPmlA5PiKZ3AgEQgCX/JUXRTEWOKryUHvbnLXTXpjtgw/bWr82JM8eHj/dflU6eoF81'
#AWS decrypts it using Master Key stored in KMS
binaryData = base64.b64decode(encryptedData)
kms.decrypt(CiphertextBlob=binaryData)['Plaintext']
'''
Result:
b'Hello world'
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment