Skip to content

Instantly share code, notes, and snippets.

@stupidbodo
Last active August 7, 2020 11:09
Show Gist options
  • Save stupidbodo/46ffe9b43bc11b43cb02 to your computer and use it in GitHub Desktop.
Save stupidbodo/46ffe9b43bc11b43cb02 to your computer and use it in GitHub Desktop.
AES Encryption Example in Python
from base64 import urlsafe_b64encode, urlsafe_b64decode
from Crypto.Cipher import AES
from Crypto import Random
BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s: s[:-ord(s[len(s) - 1:])]
base64pad = lambda s: s + '=' * (4 - len(s) % 4)
base64unpad = lambda s: s.rstrip("=")
encrypt_key = 'LKHlhb899Y09olUi'
def encrypt(key, msg):
iv = Random.new().read(BS)
cipher = AES.new(key, AES.MODE_CFB, iv, segment_size=AES.block_size * 8)
encrypted_msg = cipher.encrypt(pad(str(msg)))
return base64unpad(urlsafe_b64encode(iv + encrypted_msg))
# when incorrect encryption key is used, `decrypt` will return empty string
def decrypt(key, msg):
decoded_msg = urlsafe_b64decode(base64pad(msg))
iv = decoded_msg[:BS]
encrypted_msg = decoded_msg[BS:]
cipher = AES.new(key, AES.MODE_CFB, iv, segment_size=AES.block_size * 8)
return unpad(cipher.decrypt(encrypted_msg))
hidden_msg = encrypt(encrypt_key, "Hello World")
print decrypt(encrypt_key, hidden_msg) # Hello World
@yamyamyuo
Copy link

good job!

@Sunrise17
Copy link

Is it possible to make decryption in MicroPython (esp32 board)?

@chaitanya2593
Copy link

Hi ,
Is there anyway we can hide the encrypt_key ??

@0xlane
Copy link

0xlane commented Jan 15, 2019

pad(32chr(65)): len(s)%BS = 0 and BS-0 = 16 ->> s+16chr(*)

@SeakyLuo
Copy link

What's the value of AES.block_size?

@Patelriki28
Copy link

I this this code in google colab the so in line 31 is wrong error is syntax invalid.

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