from math import ceil from urllib2 import quote, unquote from base64 import b64encode as b64enc class Lazarus(): def __init__(self, key): self.key = key self.BS = 16 self.iv = "0"*self.BS def enc(self, plaintext): t = quote(plaintext) prevBlock = self.iv c = "" for i in range(int(ceil(float(len(t))/self.BS))): block = t[i*self.BS:][:self.BS] prevBlock=self._sxor(self._rc4(block),prevBlock) c+=prevBlock return c def dec(self, ciphertext): c = ciphertext prevBlock = self.iv t = "" for i in range(int(ceil(float(len(c))/self.BS))): block = c[i*self.BS:][:self.BS] t+=self._rc4(self._sxor(block,prevBlock)) prevBlock = block return unquote(t) def _sxor(self, s1, s2): return ''.join(chr(ord(a) ^ ord(b)) for a,b in zip(s1,s2)) def _rc4(self, data): box = list(range(256)) x = 0 for i in range(256): x = (x + box[i] + ord(self.key[i % len(self.key)])) % 256 box[i], box[x] = box[x], box[i] x = 0 y = 0 out = [] for char in data: x = (x + 1) % 256 y = (y + box[x]) % 256 box[x], box[y] = box[y], box[x] out.append(chr(ord(char) ^ box[(box[x] + box[y]) % 256])) return ''.join(out)