Skip to content

Instantly share code, notes, and snippets.

@APAC-GOLD
Last active November 10, 2023 16:19
Show Gist options
  • Save APAC-GOLD/bed0bda2225fdc5ee292bc3b899cf4cb to your computer and use it in GitHub Desktop.
Save APAC-GOLD/bed0bda2225fdc5ee292bc3b899cf4cb to your computer and use it in GitHub Desktop.
Symmetric Encryption
#How To - perform a symmetric encryption using AES256 algorithm in Python
##Step 1 - use terminal and the command <pip install pycryptodome> to install a library that provides access to the AES256 algorithm.
##Step 2 - create an AES256 key and save it.
import os
key = os.urandom(32)
with open('key.bin', 'wb') as f:
f.write(key)
print(key) #not sure if I need this step but I want to see the output
##Step 3 - create a string to test encryption.
from Crypto.Cipher import AES
with open('key.bin', 'rb') as f:
key = f.read()
cipher = AES.new(key, AES.MODE_EAX)
plaintext = b'Hello, world!'
ciphertext, tag = cipher.encrypt_and_digest(plaintext)
print(plaintext) #to see the output
##Step 4 - perform AES256 symmetric decryption on the cipher text to get the original text.
from Crypto.Cipher import AES
with open('key.bin', 'rb') as f:
key = f.read()
cipher = AES.new(key, AES.MODE_EAX, nonce=cipher.nonce)
plaintext = cipher.decrypt(ciphertext)
print(ciphertext) #to see the output
##Step 5 - use the command <assert> to check if decrypted data is the same as the original string.
assert plaintext == b'Hello, world!'
print (plaintext) #to see the output
@APAC-GOLD
Copy link
Author

How do I use python to perform symmetric encryption operation in the order below:

  • Find the right library that provide you with access to AES256 algorithm.
  • Create and save your AES256 key.
  • Create a string to test encryption.

Perform AES256 symmetric encryption on the data to get cipher text.

  • Use AES256 symmetric decryption on the cipher text to get original text.
  • Use assert to check if decrypted data is the same as original string.

AWS re/Start Course Homework, 10 November 2023

@APAC-GOLD
Copy link
Author

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