lazarus/xorCorrelator.py

63 lines
1.6 KiB
Python
Raw Permalink Normal View History

2020-06-26 15:59:11 +02:00
import secrets
2020-07-04 22:45:33 +02:00
import hashlib
2020-06-26 15:59:11 +02:00
def xor(a: bytes, b: bytes):
if len(a)!=len(b):
raise Exception("Bad Length")
return bytes([a[i]^b[i] for i in range(len(a))])
def cbcXor(blocks, key: bytes, iv: bytes = None, BS=16):
if len(key)!=BS:
raise Exception("Bad key len")
if not iv:
iv = secrets.token_bytes(16)
lastBlock = iv
res = []
for block in blocks:
if len(block)!=BS:
raise Exception("Bad block length")
mid = xor(block, lastBlock)
enc = xor(mid, key)
lastBlock = enc
res.append(enc)
return res
2020-07-04 22:45:33 +02:00
def decCbcXor(blocks, key: bytes, iv: bytes = None, BS: int = 16):
2020-06-26 15:59:11 +02:00
if len(key)!=BS:
raise Exception("Bad key len")
if not iv:
iv = secrets.token_bytes(16)
lastBlock = iv
res = []
for block in blocks:
if len(block)!=BS:
raise Exception("Bad block length")
mid = xor(block, key)
enc = xor(mid, lastBlock)
lastBlock = block
res.append(enc)
return res
2020-07-04 22:45:33 +02:00
def randBlocks(num: int = 64, BS: int = 16):
2020-06-26 15:59:11 +02:00
return [secrets.token_bytes(16) for i in range(num)]
2020-07-04 22:45:33 +02:00
def hashsum(blocks):
return hashlib.sha3_256("".join(blocks)).digest()
def buildCollisionMatrix(blocks):
mat = []
for b in range(0,len(blocks)-1):
line = []
for c in range(b+1,len(blocks)):
block = blocks[b]
compr = blocks[c]
collLen = 0
for d in range(len(block)):
if block[d]!=compr[d]:
break
collLen+=1
line.append(collLen)
mat.append(line)
return mat