1 ## xts.py - The XTS 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 ## Feb 13 2008: Initial version. Plenty of room for improvements.
37 def gf2pow128powof2(n
):
38 """2^n in GF(2^128)."""
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."""
49 for c
in reversed(str):
61 def xorstring16(a
, b
):
64 new
+= chr(ord(a
[p
]) ^
ord(b
[p
]))
68 n_txt
= struct
.pack('< Q', n
) + '\x00' * 8
69 e_k2_n
= cipher2
.encrypt(n_txt
)
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
):
84 assert length
% 16 == 0
86 for i
in xrange(length
/ 16):
87 data
+= XTSDecrypt(cipher1
, cipher2
, i
, n
, blocks
[0:16])