Skip to content

Instantly share code, notes, and snippets.

@h3nryza
Created July 17, 2018 17:14
Show Gist options
  • Save h3nryza/928352aa826f27a6afa8afee8b075266 to your computer and use it in GitHub Desktop.
Save h3nryza/928352aa826f27a6afa8afee8b075266 to your computer and use it in GitHub Desktop.
Python aes cryptography with pycryptodome or pycrypto
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
from Crypto.Cipher import AES
from Crypto import Random
from pkcs7 import PKCS7Encoder
import base64
#Encrypt Aes
#Get the key, iv from random, generate aes for encryption
AES.block_size = 16
key = Random.new().read(16)
iv = Random.new().read(AES.block_size)
aes = AES.new(key, AES.MODE_CBC, iv)
plainText = "Attack at dawn"
#Correct the padding
encoder = PKCS7Encoder()
pad_text = encoder.encode(plainText)
#encrypt
cipher = aes.encrypt(pad_text)
# base64 encode the cipher text for transport
enc_cipher = base64.b64encode(cipher)
print("Encrypted_Text: {}".format(enc_cipher))
print("KEY: {}".format(base64.b64encode(key)))
print("IV: {}".format(base64.b64encode(iv)))
#Decrypt AES
# Use the non-base64 IV, Key from above, decrypt the Non base64 ciper and unpad the result
aes_dec = AES.new(key, AES.MODE_CBC, iv)
dec_ciper = aes_dec.decrypt(cipher)
encoder = PKCS7Encoder()
plain_text = encoder.decode(dec_ciper)
print("Decrypted:{}".format(plain_text))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment