-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
22 additions
and
17 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,24 +1,29 @@ | ||
import struct | ||
|
||
MASK32 = (1 << 32) - 1 | ||
|
||
class XTEA: | ||
def __init__(self, key, rounds=32): | ||
self.keywords = struct.unpack('<IIII', key) | ||
if len(key) != 16: | ||
raise Exception('Expecting the 128 bit (16 bytes) key') | ||
|
||
key = int.from_bytes(key, 'little', signed=False) | ||
keywords = (key >> 0) & MASK32, (key >> 32) & MASK32, (key >> 64) & MASK32, (key >> 96) & MASK32, | ||
|
||
schkey = [] | ||
# schedule the key for 32 rounds to move it out of enc loop | ||
sum = 0 | ||
delta = 0x9E3779B9 | ||
for round in range(rounds): | ||
k0 = (sum + self.keywords[sum & 3]) & MASK32 | ||
k0 = (sum + keywords[sum & 3]) & MASK32 | ||
sum = (sum + delta) & MASK32 | ||
k1 = (sum + self.keywords[(sum>>11) & 3]) & MASK32 | ||
k1 = (sum + keywords[(sum>>11) & 3]) & MASK32 | ||
schkey.append((k0, k1)) | ||
self.schkey = schkey | ||
|
||
def encrypt(self, pt): | ||
v0, v1 = struct.unpack('<II', pt) | ||
pt = int.from_bytes(pt, 'little', signed=False) | ||
v0, v1 = (pt >> 0) & MASK32, (pt >> 32) & MASK32 | ||
for schkey in self.schkey: | ||
v0 = (v0 + ((((v1<<4) ^ (v1>>5)) + v1) ^ schkey[0])) & MASK32 | ||
v1 = (v1 + ((((v0<<4) ^ (v0>>5)) + v0) ^ schkey[1])) & MASK32 | ||
return struct.pack('<II', v0, v1) | ||
ct = (v1 << 32) | v0 | ||
return ct.to_bytes(8, 'little') |