Add phnxdeco with debian patch set (version 0.33-3).
[delutions.git] / tc / python / xts.py
blobf3d4d26e472f19c6cd5141727d54fd87555da096
1 ## xts.py - The XTS 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 ## Feb 13 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 *
35 import struct
37 def gf2pow128powof2(n):
38 """2^n in GF(2^128)."""
39 if n < 128:
40 return 2**n
41 return reduce(gf2pow128mul, (2 for x in xrange(n)), 1)
43 ## C = E_K1(P xor (E_K2(n) mul (a pow i))) xor (E_K2(n) mul (a pow i))
44 def XTSDecrypt(cipher1, cipher2, i, n, block):
45 """Perform a XTS decrypt operation."""
47 def str2int(str):
48 N = 0
49 for c in reversed(str):
50 N <<= 8
51 N |= ord(c)
52 return N
54 def int2str(N):
55 str = ''
56 while N:
57 str += chr(N & 0xff)
58 N >>= 8
59 return str
61 def xorstring16(a, b):
62 new = ''
63 for p in xrange(16):
64 new += chr(ord(a[p]) ^ ord(b[p]))
65 return new
67 # e_k2_n = E_K2(n)
68 n_txt = struct.pack('< Q', n) + '\x00' * 8
69 e_k2_n = cipher2.encrypt(n_txt)
71 # a_i = (a pow i)
72 a_i = gf2pow128powof2(i)
74 # e_mul_a = E_K2(n) mul (a pow i)
75 e_mul_a = gf2pow128mul(str2int(e_k2_n), a_i)
76 e_mul_a = int2str(e_mul_a)
77 e_mul_a = '\x00' * (16 - len(e_mul_a)) + e_mul_a
79 # C = E_K1(P xor e_mul_a) xor e_mul_a
80 return xorstring16(e_mul_a, cipher1.decrypt(xorstring16(e_mul_a, block)))
82 def XTSDecryptMany(cipher1, cipher2, n, blocks):
83 length = len(blocks)
84 assert length % 16 == 0
85 data = ''
86 for i in xrange(length / 16):
87 data += XTSDecrypt(cipher1, cipher2, i, n, blocks[0:16])
88 blocks = blocks[16:]
89 return data