【问题标题】:Ciphertext using XOR displaying binary and decimal numbers使用 XOR 显示二进制和十进制数的密文
【发布时间】: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


【解决方案1】:

您将 K 的转换值打印出来,但实际上从未将 K 更新为新值。因此,您正在使用字符串而不是 int 执行 XOR。只需添加k = bin(k)

【讨论】:

  • 我不需要对纯文本也这样做吗?
  • @JacobGellhaus 一个 char 基本上是一个二进制数,但我认为 python 确实有区别,所以是的,你应该
  • 我做了这些更改,这是我仍然遇到的错误 - ValueError: invalid literal for int() with base 10: 'fed'
  • @JacobGellhaus 那么它必须要以 2 为底,试试 bin()
  • plaintextk 都是字符串。他需要先ord() 每个字符,然后应用异或键遍历它们。
猜你喜欢
  • 2017-10-20
  • 2014-03-11
  • 2021-10-02
  • 1970-01-01
  • 2015-01-21
  • 2014-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多