Bottleneck: easy obscurity "encryption" via xor

Bengt Richter bokr at
Wed Jul 30 01:05:42 CEST 2003

On Wed, 30 Jul 2003 00:25:59 +0200, Irmen de Jong <irmen at> wrote:

>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:
>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):
 def xorcrypt(s, salt = 255):       # better name choice, even though string module may not be used
>     if salt <0 or salt> 255:
>         raise "Invalid salt! Must be 0<=salt<=255!"
>     return ''.join( [ chr(ord(c) ^ salt) for c in string ] )
      return s.translate(''.join([chr(ic^salt) for ic in xrange(256)]))
>1) salt must be 0..255 not only <=255
>2) forget about map & lambda, use a list comprehension.
forget about list comprehension, use str.translate ;-)
>That implementation runs about 20 times faster than your original one;
>0.11 seconds for 100 Kb source data. (python 2.3)
s.translate ought to a good deal faster yet ;-)

Bengt Richter

More information about the Python-list mailing list