zvodd
12/19/2017 - 7:26 AM

Simple example of using pycrytodome to do AES encryption in python

Simple example of using pycrytodome to do AES encryption in python

# -*- coding: utf-8 -*-
from io import BytesIO
from Cryptodome import Random
from Cryptodome.Cipher import AES
from Cryptodome.Hash import SHA256


class SimpleCryptor(object):

    def __init__(self, secret_text):
        self.random_file = Random.new()
        self.secret_key = self.text_to_key(secret_text)

    def encrypt(self, payload, nonce_len=20):
        nonce = self.random_file.read(nonce_len)
        ciper = AES.new(self.secret_key, AES.MODE_GCM, nonce)
        crypted = ciper.encrypt(payload.encode('latin-1'))
        return nonce + crypted

    def decrypt(self, payload, nonce_len=20):
        payload = BytesIO(payload)
        nonce = payload.read(nonce_len)
        ciper = AES.new(self.secret_key, AES.MODE_GCM, nonce)
        return ciper.decrypt(payload.read())

    def text_to_key(self, text):
        h = SHA256.new()
        h.update(text.encode('latin-1'))
        return h.digest()


def dumb_example():
    cyptor = SimpleCryptor("THIS IS A SECERET KEY")

    import codecs
    print(codecs.encode(cyptor.secret_key, 'hex'))

    import json
    payload = json.dumps({
        "session_id": "WTF BANANA PANCAKE",
        "beeees": "🐝🐝🐝🐝🐝🐝🐝🐝🐝",
        "A Number": 1901908745190,
        "🔥🔥🔥🔥🔥": "🔥🔥🔥🔥 THIS IS UNICODE!!! 🔥🔥🔥🔥"
    })

    ctext = cyptor.encrypt(payload)
    print(ctext)

    dtext = cyptor.decrypt(ctext)
    print(json.loads(dtext))


if __name__ == '__main__':
    dumb_example()