Skip to content

Instantly share code, notes, and snippets.

@diekmann
Created June 21, 2017 09:09
Show Gist options
  • Save diekmann/96747a4bf3f9153b9c40287ec14d807e to your computer and use it in GitHub Desktop.
Save diekmann/96747a4bf3f9153b9c40287ec14d807e to your computer and use it in GitHub Desktop.
AES decryption with random keys gives unique entropy for each key (over 90% unique in test case)
#!/usr/bin/env python3
from collections import Counter
import math
from Crypto.Cipher import AES
from Crypto import Random
def multlog2(x):
if x == 0:
return 0
return x*math.log2(x)
def entropy(bstr):
#entropy of BYTES! Because plaintext is probably ascii or utf8.
#bstr must be bytes
cnt = Counter(bstr)
entr = 0
for c in range(256):
p = cnt[c]/len(bstr)
entr += multlog2(p)
return -entr
def newaes(k):
return AES.new(k, IV=b'0'*16, mode=AES.MODE_CBC)
aes = newaes(b'k'*16)
c = aes.encrypt(b'\x00'*16*42)
def dec(k, c):
return newaes(k).decrypt(c)
es = []
for i in range(256):
k = bytes((i for _ in range(16)))
es.append(entropy(dec(k, c)))
for _ in range(100000):
k = Random.new().read(16)
es.append(entropy(dec(k, c)))
print(sorted(es))
numdups = len(es) - len(set(es))
print(numdups)
print("unique entropy: {}%".format((len(set(es))/len(es))*100))
@diekmann
Copy link
Author

For 100000 random keys, entropy is about 92%.
For 1000000 random keys, unique entropy drops to 60%. Textlength probably needs to be increased.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment