import hashlib import math import os import random bs = int(256/8) def xor(ta,tb): return bytes(a ^ b for a, b in zip(ta, tb)) def genIV(): return random.randint(0, 2**(bs-1)).to_bytes(bs, byteorder='big') def enc(plaintext, key, iv): ciphertext = bytes() for i in range(math.ceil(len(plaintext)/bs)): m = hashlib.sha256() m.update(xor(key, iv + i.to_bytes(bs, byteorder='big'))) k = m.digest() iv = (int.from_bytes(iv, byteorder='big')+1).to_bytes(bs, byteorder='big') ciphertext += xor(k, plaintext[bs*i:][:bs].ljust(bs, b'0')) return ciphertext def dec(ciphertext, key, iv): return enc(ciphertext, key, iv) def getSample(length, src=None, key=b'VerySecureKeyMustKeepSecretDontTellAnyone'): if src==None: src = random.random() > 0.5 if not src: r = os.urandom(length*bs) return (r, 0) else: iv = genIV() b = bytes(length*bs) return (enc(b, key, iv), 1)