简体   繁体   中英

Python XOR Encryption program sometimes doesn't work

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:

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

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

It's probably working fine, but you are getting characters which you may not be able to re-input into your terminal directly as they don't correspond to the ordinarily inputtable ASCII characters. In particular, with the key qwer , the values of ord become [25, 18, 9, 30, 30] , which you may have a hard time inputting (cf. this table ).

The similar problem will not occur if you use 1234 as a key as in that case the values are [89, 87, 95, 88, 94] which correspond to "normal" characters.

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 abcdef0123456789 , which lets you display it without issue:

print encrypted_message.encode('hex')

You can then decode it when the user types it in once more:

todecrypt = raw_input('Enter a message to be decrypted:   ').decode('hex')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM