在用Python编写的XOR加密程序中似乎存在一个错误

时间:2013-10-08 05:04:41

标签: python encryption xor

我一直在尝试用Python编写一个简单的加密程序,当我尝试在Linux上执行代码时,它不会打印任何东西。有人可以告诉我为什么吗?

    #!/usr/bin/env python2
import binascii
def encrypt():
    text = raw_input("Please input your information to encrypt: ")
    for i in text:
        #Convert text into a binary sequence
        i = bin(int(binascii.hexlify(i),16))
    key = raw_input("Please input your key for decryption: ")
    for j in key:
        #Convert key into a binary sequence
        j = bin(int(binascii.hexlify(j),16))
    #This is only here for developmental purposes
    print key
    print text

修改 我做了其中一个用户说的,但是我的代码似乎仍然没有像我想要的那样将我的纯文本转换为二进制文件。

#!/usr/bin/env python2
def encrypt():
    text = raw_input("Please input your information to encrypt: ")
    for i in text:
        #Convert text into a binary sequence
        i = bin(ord(i))
    key = raw_input("Please input your key for decryption: ")
    for j in key:
        #Convert key into a binary sequence
        j = bin(ord(j))
    #This is only here for developmental purposes
    print key
    print text

encrypt()

2 个答案:

答案 0 :(得分:2)

您的计划存在许多重大问题:

  1. 您正在定义一个名为encrypt()的函数,但从不调用它。

  2. 你的两个循环都没有实际修改字符串。他们修改循环变量,这不是一回事!

  3. int(binascii.hexlify(x), 16)是一种过于复杂的撰写方式ord(x)

  4. bin()没有按照您的意愿行事。

  5. 这里没有任何东西被砍掉。你的计划尚未完成。

答案 1 :(得分:0)

我认为这就是你要做的事情

def encrypt():
  cleartext = raw_input("Please input your information to encrypt: ")
  ciphertext = []
  for char in cleartext:
    ciphertext.append(bin(ord(char))[2:])
  ciphertext = ''.join(ciphertext)

  key = raw_input("Please input your key for decryption: ")
  decryptionKey = []
  for char in key:
    decryptionKey.append(bin(ord(char))[2:])
  decryptionKey = ''.join(decryptionKey)

  print "The key is '%s'" %decryptionKey
  print "The encrypted text is '%s'" %ciphertext