Bottleneck: easy obscurity "encryption" via xor

Irmen de Jong irmen at -NOSPAM-REMOVETHIS-xs4all.nl
Tue Jul 29 18:25:59 EDT 2003


Tino Lange wrote:

> It turns out not to be quick at all. I really didn't expect this to be
> a bottleneck, but it takes quite some time.

>>   return reduce(lambda x,y: operator.add(x, chr(y)), map(lambda char, _salt = salt: operator.xor(ord(char), _salt), str), "")

Running this on a large string builds up a huge list of ints,
that you are converting to chars and then concatenating them
together using +... this creates a HUGE number of temporary
string objects.
The usual pattern of fast string joining is:

''.join(list-of-fragments)

So first try:

    return ''.join(map(lambda char, _salt = salt: chr(operator.xor(ord(char), _salt)), string))

This runs MUCH faster already.

But the version I'd recommend is:

def xorcrypt(string, salt = 255):
     if salt <0 or salt> 255:
         raise "Invalid salt! Must be 0<=salt<=255!"
     return ''.join( [ chr(ord(c) ^ salt) for c in string ] )

because
1) salt must be 0..255 not only <=255
2) forget about map & lambda, use a list comprehension.

That implementation runs about 20 times faster than your original one;
0.11 seconds for 100 Kb source data. (python 2.3)

HTH,
--Irmen de Jong






More information about the Python-list mailing list