Last active
August 8, 2023 13:54
-
-
Save Parassharmaa/fe693f6afc9cd358efd0427d0f57dbfb to your computer and use it in GitHub Desktop.
AWS KMS (Encryption and Decryption)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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' | |
| ''' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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