Python XOR Encryption program sometimes doesn't work
<p>I am trying to make a simple xor encryption program in python and what I have now is working almost fine, only sometimes it doesn't and I just can't figure out why. For example, if I input 'hello' and the key '1234' it will encrypt it to YW_X^ and if I then decrypt this with the same key it will print 'hello'. But if I change the key to 'qwer' the encrypted message is something like '^Y^R     ^^^^' and if I try to decrypt it, 'heERQWERoi' comes out. 
This is the code:</p>

<pre><code>from itertools import cycle, izip


choice = int(raw_input('Press 1 to encrypt, 2 to decrypt.  '))
if choice == 1:
    message = raw_input('Enter message to be encrypted:   ')
    privatekey = raw_input('Enter a private key:   ')
    encrypted_message = ''.join(chr(ord(c)^ord(k)) for c,k in izip(message, cycle(privatekey)))
    print 'Encrypted message:' 
    print encrypted_message
elif choice == 2:
    todecrypt = raw_input('Enter a message to be decrypted:   ')
    otherprivatekey = raw_input('Enter the private key:  ')
    decrypted_message = ''.join(chr(ord(c)^ord(k)) for c,k in izip(todecrypt, cycle(otherprivatekey)))
    print 'Decrypted message:'
    print decrypted_message
</code></pre>

<p>I have no idea what is wrong with it so I would really appreciate some help, thank you!</p>

<p>Your script is printing non-printing characters, which sometimes can't be copy/pasted. You could encode the ciphertext into a format that uses only the characters <code>abcdef0123456789</code>, which lets you display it without issue:</p>

<pre><code>print encrypted_message.encode('hex')
</code></pre>

<p>You can then decode it when the user types it in once more:</p>

<pre><code>todecrypt = raw_input('Enter a message to be decrypted:   ').decode('hex')
</code></pre>

python python-2.7 encryption cryptography xor