因为学校的原因,我开始学习如何使用 python,而且我真的没有遇到任何问题;然而,上周我们被分配制作一个流密码,但我真的很难使用它。代码如下:
import binascii
mode = 0
def asktodo():
while True:
print('Do you wish to encrypt or decrypt your message?')
mode = input().lower()
if mode in 'encrypt e decrypt d'.split():
return mode
else:
print('Enter either "encrypt" or "e", or "decrypt" or "d".')
def message():
inp = input('Input your message:\n')
inp = inp.lower()
return inp
def gkey():
nkey = int(input('Input your key:\n'))
return nkey
def encrypt(plaintext,key):
ciphered=""
for x in plaintext:
ptd=ord(x)
cip=ptd^key
ciphered=ciphered+chr(cip)
ciphered=bytes(ciphered, 'utf-8')
return binascii.hexlify(ciphered)
def decrypt(ciphered,key):
ciphered=binascii.unhexlify(ciphered)
ciphered=str(ciphered, 'utf-8')
plain=''
for x in ciphered:
ctd=ord(x)
descip=ctd^key
plain=plain+chr(descip)
return plain
mode = asktodo()
mess= message()
xkey = gkey()
if mode == 'e' or mode == 'encrypt':
print(' ')
print('Your encrypted message is:')
print(encrypt(mess, xkey))
else:
print(' ')
print('Your decrypted message is:')
print(decrypt(mess, xkey))
input()
加密部分工作完美。但是,当我尝试解密任何消息时,会弹出以下错误:
--line 33, in decrypt
- ciphered=binascii.unhexlify(ciphered)
Error: Odd-length string
我已经尝试了很多方法并遵循了很多建议,但我就是无法解决它。
P.S.:在为您提供加密消息之前,代码会将值更改为十六进制。
最佳答案
我无法重现你的错误:
In [12]: import binascii
...:
...: def asktodo():
...: while True:
...: mode = input('Do you wish to encrypt or decrypt your message?')
...: mode = mode.lower()
...: if mode in 'encrypt e decrypt d'.split():
...: return mode
...: else:
...: print('Enter either "encrypt" or "e", or "decrypt" or "d".')
...:
...: def message():
...: inp = input('Input your message:\n')
...: inp = inp.lower()
...: return inp
...:
...: def gkey():
...: nkey = int(input('Input your key:\n'))
...: return nkey
...:
...: def encrypt(plaintext,key):
...: ciphered=""
...: for x in plaintext:
...: ptd=ord(x)
...: cip=ptd^key
...: ciphered=ciphered+chr(cip)
...: ciphered=bytes(ciphered, 'utf-8')
...: return binascii.hexlify(ciphered)
...:
...: def decrypt(ciphered,key):
...: ciphered=binascii.unhexlify(ciphered)
...: ciphered=str(ciphered, 'utf-8')
...: plain=''
...: for x in ciphered:
...: ctd=ord(x)
...: descip=ctd^key
...: plain=plain+chr(descip)
...: return plain
...:
...: print('')
...: mess= message()
...: xkey = gkey()
...: print('Your encrypted message is:')
...: print(encrypt(mess, xkey))
...:
...: print('')
...: mess= message()
...: xkey = gkey()
...: print('Your decrypted message is:')
...: print(decrypt(mess, xkey))
...:
...:
Input your message:
test1
Input your key:
123
Your encrypted message is:
b'0f1e080f4a'
Input your message:
0f1e080f4a
Input your key:
123
Your decrypted message is:
test1
我猜,您很可能正在输入字节字符串表示形式,包括 b
和撇号。也就是说,在解密部分你可能输入:
Input your message:
b'0f1e080f4a'
那个 字符串有奇数个字符(不应该)。
关于python - 生成流密码时出现错误 : Odd-length string (Python 3,),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52395578/