forked from Varbin/xtea
-
Notifications
You must be signed in to change notification settings - Fork 0
/
counter.py
49 lines (40 loc) · 1.22 KB
/
counter.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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
################ Basic counter for CTR mode
from xtea import from_bytes, to_bytes
class Counter:
"""Small counter for CTR mode, based on arrays
Example:
>>> from xtea3 import Counter
>>> nonce = b"$2dUI84e" # This should be random
>>> c = Counter(nonce)
>>> c()
b'%2dUI84e'
>>> c()
b'&2dUI84e'
>>> c()
b"'2dUI84e"
>>> c.reset()
>>> c()
b'%2dUI84e'
"""
def __init__(self, nonce, byteorder='big'):
"""Constructor for a counter which is suitable for CTR mode.
Args:
nonce (bytes): The start value, \
it MUST be random if it should be secure, for example, use *os.urandom* for it.
"""
self.__nonce = nonce
self.byteorder = byteorder
self.reset()
def __call__(self):
"""The method that makes it callable.
Returns:
bytes
"""
value = to_bytes(self.__current, 8, self.byteorder)
self.__current += 1
self.__current %= 2**64
return value
def reset(self):
"""Reset the counter to the nonce
"""
self.__current = from_bytes(self.__nonce, self.byteorder)