ActiveState Code

Recipe 496970: xor for strings


Simple xor for strings

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Xor:
    def __init__(self, key):
        self.__key = key
        
    def __xor(self, s):
        res = ''
        for i in range(len(s)):
            res += chr(ord(s[i]) ^ ord(self.__key[i]))
        return res
            
        
    def __normkey(self, s):
        self.__key = self.__key * (len(s) / len(self.__key))
        
    def encrypt(self, s):
        self.__normkey(s)
        return self.__xor(s)
        
    decrypt = encrypt

Discussion

xor for strings

Comments

  1. 1. At 7:58 a.m. on 18 aug 2006, parappo cinesi said:

    Short is better.

    from itertools import cycle, izip
    
    def process (ss, key):
        key = cycle(key)
        return ''.join(chr(ord(x) ^ ord(y)) for (x,y) in izip(ss, key))
    
    --
    :-)
    

Sign in to comment