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

时间:2018-01-25 03:33:36

标签: python encryption cryptography caesar-cipher

我很难理解如何对我的两个输出进行异或。该程序让用户输入自己的明文和密钥。例如,用户将为其2个输入输入“bad”和“fed”。然后程序将PT和K的每个字符转换为二进制和十进制数字表示。我有一部分在我的代码中工作。我遇到的问题是,当我尝试使用XOR或^时,我说我的可执行文件中出现错误。我想我需要先存储每个角色的二进制表示,然后才能对这两个角色进行异或? XOR'd输出应为二进制和十进制形式。任何帮助?

最后两行代码是我如何尝试实现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)

1 个答案:

答案 0 :(得分:0)

您打印K out的转换值但从未实际将K更新为新值。所以你用字符串而不是int来执行XOR。只需添加k = bin(k)

即可