-
-
Save simandebvu/2fcad8a592ce1627bbeec1cbb93b84ae 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment