使用异或显示二进制和十进制数字的密文

2024-05-29 10:45:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我很难理解如何异或我的两个输出。程序让用户输入自己的明文和密钥。例如,用户将为他们的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)

Tags: andthekeyinptforinputreturn

热门问题