Last active
August 7, 2020 11:09
-
-
Save stupidbodo/46ffe9b43bc11b43cb02 to your computer and use it in GitHub Desktop.
AES Encryption Example in Python
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
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 |
Is it possible to make decryption in MicroPython (esp32 board)?
Hi ,
Is there anyway we can hide the encrypt_key ??
pad(32chr(65)): len(s)%BS = 0 and BS-0 = 16 ->> s+16chr(*)
What's the value of AES.block_size
?
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
good job!