-
Notifications
You must be signed in to change notification settings - Fork 0
/
MT19937.py
29 lines (22 loc) · 837 Bytes
/
MT19937.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from Crypto.Util.strxor import strxor
from challenge21 import MT19937
from struct import pack
class MT19937Cipher:
def __init__(self, key):
self._rng = MT19937(key & 0xffff)
self._keybytes = b''
def encrypt(self, plaintext):
# Work around strxor() not handling zero-length strings
# gracefully.
if len(plaintext) == 0:
return b''
keystream = self._keybytes
while len(keystream) < len(plaintext):
keyblock = pack('<L', self._rng.random())
keystream += keyblock
if len(keystream) > len(plaintext):
self._keybytes = keystream[len(plaintext):]
keystream = keystream[:len(plaintext)]
return strxor(plaintext, keystream)
def decrypt(self, ciphertext):
return self.encrypt(ciphertext)