gpt4 book ai didi

python - XOR Python 文本加密/解密

转载 作者:太空狗 更新时间:2023-10-29 19:35:57 25 4
gpt4 key购买 nike

我知道有一个可以在 Python 中导入的内置 xor 运算符。我正在尝试执行异或加密/解密。到目前为止,我有:

 def xor_attmpt():
message = raw_input("Enter message to be ciphered: ")
cipher = []
for i in message:
cipher.append(bin(ord(i))[2::])#add the conversion of the letters/characters
#in your message from ascii to binary withoout the 0b in the front to your ciphered message list
cipher = "".join(cipher)
privvyKey = raw_input("Enter the private key: ")
keydecrypt = []
for j in privvyKey:
keydecrypt.append(bin(ord(j))[2::]) #same
keydecrypt = "".join(keydecrypt )#same

print "key is '{0}'" .format(keydecrypt) #substitute values in string
print "encrypted text is '{0}'" .format(cipher)
from operator import xor
for letter in message:
print xor(bool(cipher), bool(keydecrypt))

这个:

>  for letter in message:
print xor(bool(cipher), bool(keydecrypt))

是我的 python 开始出错的地方。

输出看起来像这样

    Enter message to be ciphered: hello
Enter the private key: \@154>
key is '10111001000000110001110101110100111110'
encrypted text is '11010001100101110110011011001101111'
False
False
False
False
False

我搞砸的是试图比较这两个二进制文件( key 和加密)并给出 true(1) 或 false(为 0)。然后 xor 应该通过比较两者给我一个结果 1 和 0 二进制列表。有什么意见吗?

最佳答案

这是来自 XOR Cipher Wikipedia article 的代码示例的变体:

def xor(data, key): 
return bytearray(a^b for a, b in zip(*map(bytearray, [data, key])))

示例(Python 2):

>>> one_time_pad = 'shared secret' 
>>> plaintext = 'unencrypted'
>>> ciphertext = xor(plaintext, one_time_pad)
>>> ciphertext
bytearray(b'\x06\x06\x04\x1c\x06\x16Y\x03\x11\x06\x16')
>>> decrypted = xor(ciphertext, one_time_pad)
>>> decrypted
bytearray(b'unencrypted')
>>> plaintext == str(decrypted)
True

关于python - XOR Python 文本加密/解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20557999/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com