XOR Binascii Hex Strings using the PyCrypto module

yaipa yaipa at yahoo.com
Fri Feb 16 14:03:21 EST 2007


I snipped this bit of code out of Andrew Kuchling 'pyCrypto' test
fixture.  Having a need to XOR Binascii Hex strings in my current
project, I found it very helpful to cut down on a bit of code
clutter.

So if you have a need for a Crypto module, this one seems to work off
the self without much effort and it comes /w a nice XOR function too
boot.  :-)

PyCrypto can be found at:   http://www.amk.ca/python/code/crypto

import binascii
from Crypto.Cipher import XOR

def die(string):
    import sys
    print '***ERROR: ', string
#    sys.exit(0)   # Will default to continuing onward...

testdata_xor = [('ffffffffffffffff',
'a5a5a5a5a5a5a5a5','5a5a5a5a5a5a5a5a')]

for entry in testdata_xor:
    key,plain,cipher=entry
    key=binascii.a2b_hex(key)
    plain=binascii.a2b_hex(plain)
    cipher=binascii.a2b_hex(cipher)
    obj=XOR.new(key)
    ciphertext=obj.encrypt(plain)
    print binascii.b2a_hex(ciphertext)

    if (ciphertext!=cipher):
        die('XOR failed on entry '+`entry`)




More information about the Python-list mailing list