【发布时间】:2018-01-25 11:43:42
【问题描述】:
我无法理解如何异或我的两个输出。该程序让用户输入他们自己的明文和密钥。例如,用户会为他们的 2 个输入输入“bad”和“fed”。然后程序会将 PT 和 K 的每个字符转换为二进制和十进制数字表示。我的代码中有这部分工作。我遇到的问题是,当我尝试使用 XOR 或 ^ 时,它说我的可执行文件出现错误。我想我需要先存储每个字符的二进制表示,然后才能对两者进行异或? XOR 的输出应该是二进制和十进制形式。有什么帮助吗??
最后两行代码是我尝试实现异或的方式
我收到的错误是:TypeError:不支持的操作数类型 对于 ^: 'str' 和 'str'
key = 'abcdefghijklmnopqrstuvwxyzz0123456789'
def encrypt(n, plaintext):
"""Encrypt the string and return the ciphertext"""
result = ''
for l in plaintext.lower():
try:
i = (key.index(l) + n) % 26
result += key[i]
except ValueError:
result += l
return result.lower()
def decrypt(n, ciphertext):
"""Decrypt the string and return the plaintext"""
result = ''
for l in ciphertext:
try:
i = (key.index(l) - n) % 26
result += key[i]
except ValueError:
result += l
return result
plaintext = input('Enter Plaintext: ')
k = input('Enter Key Varaible:')
offset = 5
encrypted = encrypt(offset, plaintext)
#print('Encrypted:', encrypted)
decrypted = decrypt(offset, encrypted)
#print('Decrypted:', decrypted)
print("Decimal and Binary number representation of PT")
print(["{0} {0:06b} ".format(ord(c)-ord('a')) for c in plaintext])
print("Decimal and Binary number representation of K")
print(["{0} {0:06b} ".format(ord(c)-ord('a')) for c in k])
print(["{0:06b} ".format(ord(c)-ord('a')) for c in k])
playing = True
while playing:
choice = input("Would you like to see the encrypted PT? y/n: ")
if choice == "n":
#print("Thanks for running my program")
playing = False
else:
print("Encrypted Result:" + encrypted)
playing = True
while playing:
choice = input("Would you like to see the decrypted PT? y/n: ")
if choice == "n":
#print("Thanks for running my program")
playing = False
else:
print("Decrypted Result:" + decrypted)
CT = (plaintext ^ k)
print("Ciphertext : " + CT)
【问题讨论】:
-
错误到底是什么意思
-
^: 'str' add 'str' 的操作数类型不受支持
标签: python encryption cryptography caesar-cipher