Monday, September 9, 2013

@surgeterrix to XOR or not to XOR

By way of twitter


Taking 2 strings of hexadecimal characters, converting hex to binary values, then xorsum the 2 values, and convert sum back to hex.

The other XOR


So the normal xor will not work on strings, so what do you do?

from binascii import hexlify, unhexlify  
from Crypto.Cipher import XOR  
  
# you can encounter hex strings with no spaces  
encrypted = '556e6e216c606f78217264627364757216'  
# or hex strings with spaces  
key = '01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01'  
  
#let's get binary representations  
b_encrypted = unhexlify(encrypted)  
b_key = unhexlify(key.replace(' ','')) # we remove the spaces  
 
#to see a binary string output, use repr: print(repr(b_key))  
  
cosmo = XOR.new(b_key)  
bishop = cosmo.encrypt(b_encrypted) # yeah, encrypt to decrypt  
  
print hexlify(bishop)  
# the above is what was asked  
# the plain ascii decrypted message is print(bishop)  

I think the (not really) hidden references are pretty obvious...However, even in the decrypted message, there is still a question left... :)

Fran├žois
@f_dion

3 comments:

David Mitchell said...

So what I was looking for was a bit different.

If I took two equal length hex values stored as strings:
encrypted1 = '556e6e216c606f78217264627364757216'
encrypted2 = '37681ec32d927df46572a4627e6a172572'

I need to convert them to their raw binary values.
encryptedbin1 = 0b001000010111001001100100011000100111001101100100011101000000000000000000
encyptedbin2 = 0b01010111001010100100011000100111111001101010000101110000000000000000

So then I can xorsum them:
result = encryptedbin1 ^ encryptedbin2

If I convert hex to binary using an binascii, I get a string representation of the binary above '0b01010111001010100100011000100111111001101010000101110000000000000000', not the actual binary value. So
value = '0b01010111001010100100011000100111111001101010000101110000000000000000'
print value
0b01010111001010100100011000100111111001101010000101110000000000000000
vs what I want is
value = 0b01010111001010100100011000100111111001101010000101110000000000000000
print value
100494556280137383936

The xorsum function ^ doesn't work with strings, only actual binary.

Of course, once I have the result, I need to convert the binary value back to a hex string.

David Mitchell said...

I wish I could do code blocks in comments here, the formatting tore that to pieces.

Francois Dion said...

eval(value) will get you a number as python evaluates the string as a statement.