1 ## lrw.py - The LRW cryptographic mode.
2 ## Copyright (c) 2008 Bjorn Edstrom <be@bjrn.se>
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
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.
26 ## Jan 4 2008: Initial version. Plenty of room for improvements.
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.
39 def LRW(cipherfunc
, lrwkey
, i
, block
):
40 """Perform a LRW operation."""
52 str = chr(N
& 0xff) + str
56 def xorstring16(a
, b
):
59 new
+= chr(ord(a
[p
]) ^
ord(b
[p
]))
62 assert len(block
) == 16
63 assert len(lrwkey
) == 16
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
):
72 assert length
% 16 == 0
74 for b
in xrange(length
/ 16):
75 data
+= LRW(cipherfunc
, lrwkey
, i
+ b
, blocks
[0:16])