Bottleneck: easy obscurity "encryption" via xor

Bob Gailer bgailer at alum.rpi.edu
Wed Jul 30 13:09:26 EDT 2003


At 12:25 AM 7/30/2003 +0200, Irmen de Jong 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:
>
>''.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 ] )

Great minds think alike? I came up with (independently!):
     return ''.join([chr(ord(char) ^ salt) for char in txt])
I also favor comprehension because it is more readable.

>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
>
>
>--
>http://mail.python.org/mailman/listinfo/python-list
>
>
>
>
>---
>Incoming mail is certified Virus Free.
>Checked by AVG anti-virus system (http://www.grisoft.com).
>Version: 6.0.500 / Virus Database: 298 - Release Date: 7/10/2003

Bob Gailer
bgailer at alum.rpi.edu
303 442 2625
-------------- next part --------------

---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.500 / Virus Database: 298 - Release Date: 7/10/2003


More information about the Python-list mailing list