Initial import of truecrypt cracking project.
[delutions.git] / tc / python / lrw.py
blobca492934192d0581e2a6f08d6f650035cc038d54
1 ## lrw.py - The LRW cryptographic mode.
2 ## Copyright (c) 2008 Bjorn Edstrom <be@bjrn.se>
3 ##
4 ## Permission is hereby granted, free of charge, to any person
5 ## obtaining a copy of this software and associated documentation
6 ## files (the "Software"), to deal in the Software without
7 ## restriction, including without limitation the rights to use,
8 ## copy, modify, merge, publish, distribute, sublicense, and/or sell
9 ## copies of the Software, and to permit persons to whom the
10 ## Software is furnished to do so, subject to the following
11 ## conditions:
13 ## The above copyright notice and this permission notice shall be
14 ## included in all copies or substantial portions of the Software.
16 ## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 ## EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
18 ## OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19 ## NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
20 ## HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
21 ## WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22 ## FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
23 ## OTHER DEALINGS IN THE SOFTWARE.
24 ## --
25 ## Changelog
26 ## Jan 4 2008: Initial version. Plenty of room for improvements.
28 try:
29 import psyco
30 psyco.full()
31 except ImportError:
32 pass
34 from gf2n import *
36 # C_i = E_K1(P_i ^ (K2 x i)) ^ (K2 x i).
37 # Note that cipherfunc = E_K1, that is the key should already be set in E.
38 # lrwkey = K2.
39 def LRW(cipherfunc, lrwkey, i, block):
40 """Perform a LRW operation."""
42 def str2int(str):
43 N = 0
44 for c in str:
45 N <<= 8
46 N |= ord(c)
47 return N
49 def int2str(N):
50 str = ''
51 while N:
52 str = chr(N & 0xff) + str
53 N >>= 8
54 return str
56 def xorstring16(a, b):
57 new = ''
58 for p in xrange(16):
59 new += chr(ord(a[p]) ^ ord(b[p]))
60 return new
62 assert len(block) == 16
63 assert len(lrwkey) == 16
64 K2 = str2int(lrwkey)
65 # C_i = E_K1(P_i ^ K2i) ^ K2i
66 K2i = int2str(gf2pow128mul(K2, i))
67 K2i = '\x00' * (16 - len(K2i)) + K2i
68 return xorstring16(K2i, cipherfunc(xorstring16(K2i, block)))
70 def LRWMany(cipherfunc, lrwkey, i, blocks):
71 length = len(blocks)
72 assert length % 16 == 0
73 data = ''
74 for b in xrange(length / 16):
75 data += LRW(cipherfunc, lrwkey, i + b, blocks[0:16])
76 blocks = blocks[16:]
77 return data