Ticket #4173: fast_xor.diff

File fast_xor.diff, 1.1 KB (added by aprilmay, 22 months ago)

Use long words for xor masking

Line 
1118,122c118,135
2<     key = [ord(i) for i in key]
3<     buf = list(buf)
4<     for i, char in enumerate(buf):
5<         buf[i] = chr(ord(char) ^ key[i % 4])
6<     return "".join(buf)
7---
8>     ## Please don't bring back the xor vs encryption masking debate... :0
9>     k = unpack('!Q', key * 2)[0]
10>     ## Some long data to process, use long xor
11>     div, mod = divmod(len(buf), 8)
12>     if mod:
13>         ## The buffer legth is not a 8 bytes multiple, need to adjust with rest
14>         if div:
15>             ## More than 8 bytes: unmask all long words except last
16>             longs = [pack('!Q', k ^ unpack('!Q', buf[i:i+8])[0]) for i in range(0, div*8, 8)]
17>             ## Append the rest (last 0..7 bytes)
18>             longs.append(pack('!Q', k ^ unpack('!Q', buf[div*8:] + " "*(8-mod))[0])[:mod])
19>             return "".join(longs)
20>         else:
21>             ## Short: all bytes at once
22>             return pack('!Q', k ^ unpack('!Q', buf[div*8:] + " "*(8-mod))[0])[:mod]
23>     else:
24>         ## The buffer legth is a 8 bytes multiple
25>         return "".join(pack('!Q', k ^ unpack('!Q', buf[i:i+8])[0]) for i in xrange(0, div*8, 8))