简体   繁体   English

Python XOR加密程序有时不起作用

[英]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. 我正在尝试使用python创建一个简单的xor加密程序,而现在我的工作几乎可以正常工作,只是有时不能,我只是想不出原因。 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'. 例如,如果我输入“ hello”和密钥“ 1234”,它将把它加密为YW_X ^,然后如果我使用相同的密钥对其进行解密,它将打印“ 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. 但是,如果我将密钥更改为“ qwer”,则加密的消息类似于“ ^ Y ^ R ^^^^”,并且如果尝试对其进行解密,则会出现“ heERQWERoi”。 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. 可能工作正常,但是您收到的字符可能无法直接重新输入到终端中,因为它们与通常可输入的ASCII字符不对应。 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 ). 特别是,使用键qwerord的值变为[25, 18, 9, 30, 30] qwer [25, 18, 9, 30, 30] ,您可能很难输入(请参阅此表 )。

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. 如果使用1234作为键,则不会发生类似的问题,因为在这种情况下,值是[89, 87, 95, 88, 94] ,它们对应于“正常”字符。

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: 您可以将密文编码为仅使用字符abcdef0123456789的格式,这使您可以毫无问题地显示密文:

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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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