Encryption with Python
Kamilche
klachemin at home.com
Wed Jun 23 15:56:49 EDT 2004
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 = []):
' Encrypt or decrypt a string'
cnt = len(_tables)
if cnt == 0:
# Initialize static variable _tables
# Increase 'cnt' to prevent recurring patterns.
import random
cnt = 10
random.seed(257)
for i in range(cnt):
marked, table, max = [], [], 256
for j in range(max):
table.append(chr(j))
marked.append(False)
marked[0] = True
marked[255] = True
for j in range(max):
if not marked[j]:
while 1:
c = random.randint(0, 255)
if marked[c] == False:
table[j], table[c] = table[c], table[j]
marked[c] = True
marked[j] = True
break
_tables.append(''.join(table))
# Tables initialized - encrypt the data.
return s.translate(_tables[offset % cnt])
s = "This is a standard length string to encrypt."
print "\nYou need to specify an offset to avoid patterns."
print "The string is:", s
print "\nEncrypted with offsets, you get:"
for i in range(5):
print "\t", encrypt(s, i)
print "\nEncrypted without offsets, you get:"
for i in range(5):
print "\t", encrypt(s)
Most XOR algorithms could benefit from using this technique. There's
never a need to XOR a byte more than once, while building the table.
>From then on, it's a simple substitution problem, which the
'translate' function accomplishes quite nicely.
More information about the Python-list
mailing list