12

I know there is a built in xor operator that can be imported in Python. I'm trying to execute the xor encryption/decryption. So far I have:

 def xor_attmpt():
 message = raw_input("Enter message to be ciphered: ")
 cipher = []
 for i in message:
 cipher.append(bin(ord(i))[2::])#add the conversion of the letters/characters
#in your message from ascii to binary withoout the 0b in the front to your ciphered message list
 cipher = "".join(cipher) 
 privvyKey = raw_input("Enter the private key: ")
 keydecrypt = []
 for j in privvyKey:
 keydecrypt.append(bin(ord(j))[2::]) #same
 keydecrypt = "".join(keydecrypt )#same
 print "key is '{0}'" .format(keydecrypt) #substitute values in string
 print "encrypted text is '{0}'" .format(cipher)
 from operator import xor
 for letter in message:
 print xor(bool(cipher), bool(keydecrypt))

This:

> for letter in message:
 print xor(bool(cipher), bool(keydecrypt))

is where my python starts to go wrong.

The ouput looks like this

 Enter message to be ciphered: hello
Enter the private key: \@154>
key is '10111001000000110001110101110100111110'
encrypted text is '11010001100101110110011011001101111'
False
False
False
False
False

What I'm messing up on is trying to get these two binary(key and encrypted) to be compared and give true(1) or false(being 0). The xor should then give me a resulting 1 and 0 binary list from comparing the two. Any input?

asked Dec 13, 2013 at 2:20
1
  • How is your private key represented in Python? Integer, string of bytes, something else? Ultimately you're looking at the ^ operator for bitwise XOR but you need to make sure your arguments are compatible. Commented Dec 13, 2013 at 2:25

4 Answers 4

11

Here's a variation of the code example from XOR Cipher Wikipedia article:

def xor(data, key): 
 return bytearray(a^b for a, b in zip(*map(bytearray, [data, key]))) 

Example (Python 2):

>>> one_time_pad = 'shared secret' 
>>> plaintext = 'unencrypted' 
>>> ciphertext = xor(plaintext, one_time_pad) 
>>> ciphertext 
bytearray(b'\x06\x06\x04\x1c\x06\x16Y\x03\x11\x06\x16') 
>>> decrypted = xor(ciphertext, one_time_pad) 
>>> decrypted
bytearray(b'unencrypted')
>>> plaintext == str(decrypted)
True
answered Dec 13, 2013 at 16:14
Sign up to request clarification or add additional context in comments.

2 Comments

This will truncate data so you need something like itertools.cycle for the secret key.
@HTF no. Think, why the variable is called one_time_pad. To be explicit, a ValueError may be raised if len(data)>len(key)
8

Code below works both ways and does not need length checking as cycle is used.

from itertools import cycle, izip
cryptedMessage = ''.join(chr(ord(c)^ord(k)) for c,k in izip(message, cycle(key)))
answered Aug 24, 2014 at 19:57

1 Comment

Use builtin zip for Python 3
5
somecode = 'asdfln3j34tnonfdkjnflksdfnla'
message = 'this is my message'
def str_xor(s1, s2):
 return "".join([chr(ord(c1) ^ ord(c2)) for (c1,c2) in zip(s1,s2)])
encoded = str_xor(message, somecode)
# encoded == '\x15\x1b\r\x15L\x07@J^MT\x03\n\x1d\x15\x05\x0c\x0f'
decoded = str_xor(encoded, somecode)
# decoded == 'this is my message'

This is a naive / minimalistic implementation without error checking. Here len(somecode)>= len(message) is required.

answered Dec 13, 2013 at 2:25

5 Comments

thank you. Even if this has no error checking, it is a solution in my eyes! :D One question, what exactly does the "".join do?
"".join(['a','b','c']) == 'abc'
oh. I've been seeing this in multiple places regarding python. thnx
Nitpicky, but I would use "".join(chr(ord(s1) ^ ord(s2)) for (s1, s2) in zip(somecode, message)) - zip is generally more Pythonic for lockstep iterating over two sequences than range(len(...)). Though pay attention to what you want to happen if the sequences are of different lengths, using either zip or the range call.
Peter: yes, I agree. Answer fixed.
5

for Python 3

from itertools import cycle
cryptedMessage = ''.join(chr(ord(c)^ord(k)) for c,k in zip(message, cycle(key)))
answered Dec 24, 2020 at 9:05

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.