removed roundup
[python-cryptoplus.git] / src / CryptoPlus / Util / util.py
blob6a012664e711aa6d9236d3362bf79287a86a1e37
1 def number2string(i):
2 """Convert a number to a string
4 Input: long or integer
5 Output: string (big-endian)
6 """
7 s=hex(i)[2:].rstrip('L')
8 if len(s) % 2:
9 s = '0' + s
10 return s.decode('hex')
12 def number2string_N(i, N):
13 """Convert a number to a string of fixed size
15 i: long or integer
16 N: length of string
17 Output: string (big-endian)
18 """
19 s = '%0*x' % (N*2, i)
20 return s.decode('hex')
22 def string2number(i):
23 """ Convert a string to a number
25 Input: string (big-endian)
26 Output: long or integer
27 """
28 return int(i.encode('hex'),16)
30 def xorstring(a,b):
31 """XOR two strings of same length
33 For more complex cases, see CryptoPlus.Cipher.XOR"""
34 assert len(a) == len(b)
35 return number2string_N(string2number(a)^string2number(b), len(a))
37 class Counter(str):
38 #found here: http://www.lag.net/pipermail/paramiko/2008-February.txt
39 """Necessary for CTR chaining mode
41 Initializing a counter object (ctr = Counter('xxx'), gives a value to the counter object.
42 Everytime the object is called ( ctr() ) it returns the current value and increments it by 1.
43 Input/output is a raw string.
45 Counter value is big endian"""
46 def __init__(self, initial_ctr):
47 if not isinstance(initial_ctr, str):
48 raise TypeError("nonce must be str")
49 self.c = int(initial_ctr.encode('hex'), 16)
50 def __call__(self):
51 # This might be slow, but it works as a demonstration
52 ctr = ("%032x" % (self.c,)).decode('hex')
53 self.c += 1
54 return ctr