shark/shark.py

37 lines
985 B
Python
Raw Normal View History

2021-09-20 11:32:55 +02:00
import hashlib
import math
import os
import random
2021-09-20 11:32:55 +02:00
bs = int(256/8)
2021-09-20 11:32:55 +02:00
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')
2021-09-20 11:32:55 +02:00
def enc(plaintext, key, iv):
ciphertext = bytes()
for i in range(math.ceil(len(plaintext)/bs)):
2021-09-20 11:32:55 +02:00
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
2021-09-20 11:32:55 +02:00
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)