Encryption with Python

Till Plewe till at score.is.tsukuba.ac.jp
Thu Jun 24 22:46:44 EDT 2004


On Wed, Jun 23, 2004 at 12:56:49PM -0700, Kamilche wrote:
> Peter Hansen <peter at engcorp.com> wrote in message news:<TdqdnZROdf28kUTdRVn-hQ at powergate.ca>...
> 
> > Besides, what you say is not possible.  On my machine,
> > which is about a P4 2500MHz, scanning an array.array('c') with
> > 22MB of data in it, doing nothing but reading each byte and
> > ignoring it, takes about 8 seconds.  So does converting the
> > array to a list, which is pretty much all C code.  Strings
> > are immutable, so you can't be working with one of them...
> > 
> > Doing anything meaningful with real data, no matter how trivial
> > the algorithm, would definitely take longer.
> 
> But I DON'T manipulate the data byte by byte, only the encryption
> tables.
> Ah, the power of algorithms!  ;-) 
> Take a look at this:
> 
> def encrypt(s, offset = 0, _tables = []):

...
>     # Tables initialized - encrypt the data.
>     return s.translate(_tables[offset % cnt])
> 

I apologize for my previous post (of course I don't know when it will
actually show up). The only rather weak excuse I have is that I have
spent my entire last month using nothing but C. (Of course, the real
culprit is www.python.org for not sending your message above earlier).

In any case I still have one or two comments. 

I think it is not quite "the power of algorithms" but rather making
good use of the speed of string.translate which makes your encryption
function fast. string.translate allows you to use a loop programmed in
C rather than a loop you have to program yourself in python.

If you are happy xoring then there is an even faster method: use
numarray. For me xoring a numarray.array is twice as fast as
string.translate is on the corresponding string for UInt8 arrays and
four times as fast for UInt64 arrays. (But adding the two conversions
between strings and numarrays makes the two methods comparable).


>>> import numarray
>>> Nin=numarray.fromstring(mystring,type=numarray.numerictypes.UInt64)
>>> Nout=xormask^N
>>> mysecretstrin=N.out.tostring()

- Till




More information about the Python-list mailing list