密码程序失去准确性

时间:2015-03-17 00:50:50

标签: python encryption

我在python中有一个带两个字符串的程序。一个是纯文本字符串,另一个是密码密钥。它的作用是遍历每个字符,并用密码字符对比特进行xors。但是当来回走动时,一些信似乎没有改变。这是代码:

//turns int into bin string length 8
def bitString(n):
    bin_string = bin(n)[2:]
    bin_string = ("0" * (8 - len(bin_string))) + bin_string
    return bin_string

//xors the bits
def bitXOR(b0, b1):
    nb = ""
    for x in range(min(len(b0), len(b1))):
        nb += "0" if b0[x] == b1[x] else "1"
    return nb

//takes 2 chars, turns them into bin strings, xors them, then returns the new char
def cypherChar(c0, c1):
    return chr(int(bitXOR(bitString(ord(c0)), bitString(ord(c1))), 2))

//takes s0 (the plaintext) and encrypts it using the cipher key (s1)
def cypherString(s0, s1):
    ns = ""
    for x in range(len(s0)):
        ns += cypherChar(s0[x], s1[x%len(s1)])
    return ns

例如,有时在一个长串中,单词' test'将重新加入到' eest'以及类似的东西

我已经检查了十几次代码,但我无法弄清楚是什么导致一些角色发生变化。是否有可能某些角色表现得很奇怪?

编辑:

示例:

This is a test

Due to the fact that in the last test

Some symbols: !@#$%^&*()

were not changed properly

I am retesting

END

使用密码密钥:' cypher key'

转换回:

This is a test

Due to toe aact that in the last sest

Some symbols: !@#$%^&*()

were not changed properly

I am retestiig

END

3 个答案:

答案 0 :(得分:0)

对不起,它有点乱,我把它快速地放在一起

from binascii import hexlify, unhexlify
from sys import version_info

def bit_string(string):
    if version_info >= (3, 0):
        return bin(int.from_bytes(string.encode(), 'big'))
    else:
        return bin(int(hexlify(string), 16))

def bitXOR_encrypt(plain_text, key):
    encrypted_list = []
    for j in range(2, len(plain_text)):
        encrypted_list.append(int(plain_text[j]) ^ int(key[j])) #Assume the key and string are the same length
    return encrypted_list

def decrypt(cipher_text, key):
    decrypted_list = []
    for j in range(2, len(cipher_text)): #or xrange
        decrypted_list.append(int(cipher_text[j]) ^ int(key[j])) #Again assumes key is the same length as the string

    decrypted_list = [str(i) for i in decrypted_list]
    add_binary = "0b" + "".join(decrypted_list)
    decrypted_string = int(add_binary, 2)
    if version_info >= (3, 0):
        message =  decrypted_string.to_bytes((decrypted_string.bit_length() + 7) // 8, 'big').decode()
    else:
        message = unhexlify('%x' % decrypted_string)
    return message


def main():
    plain_text = "Hello"
    plain_text_to_bits = bit_string(plain_text)
    key_to_bits = bit_string("candy")

    #Encrypt
    cipher_text = bitXOR_encrypt(plain_text_to_bits, key_to_bits)

    #make Strings
    cipher_text_string = "".join([str(i) for i in cipher_text])
    key_string = "".join([str(i) for i in key_to_bits])

    #Decrypt
    decrypted_string = decrypt("0B"+cipher_text_string, key_string)

    print("plain text: %s" % plain_text)
    print("plain text to bits: % s" % plain_text_to_bits)
    print("key string in bits: %s" % key_string)
    print("Ciphered Message: %s" %cipher_text_string)
    print("Decrypted String: %s" % decrypted_string)

main()

有关更多详细信息或示例代码,您可以在github上访问我的存储库 https://github.com/marcsantiago/one_time_pad_encryption

另外,我知道在这个例子中,键与字符串的长度相同。如果你想使用一个小于字符串的字符串,请尝试将其包装在vigenere密码(http://en.wikipedia.org/wiki /Vigenère_cipher)中

答案 1 :(得分:0)

我认为你过于复杂了:

def charxor(s1, s2):
    return chr(ord(s1) ^ ord(s2))

def wordxor(w1, w2):
    return ''.join(charxor(w1[i], w2[i]) for i in range(min(len(w1), len(w2))))

word = 'test'
key = 'what'
cyphered = wordxor(word, key)
uncyphered = wordxor(cyphered, key)

print(repr(cyphered))
print(uncyphered)

你得到了

'\x03\r\x12\x00'
test

How do you get the logical xor of two variables in Python?

中对Python的位算术有一个相当好的解释

答案 2 :(得分:0)

在使用输入数据和密钥进行测试时,我发现函数的结果没有任何问题。为了演示,您可以尝试这个不应该失败的测试代码:

import random

def random_string(n):
    return ''.join(chr(random.getrandbits(8)) for _ in range(n))

for i in range(1000):
    plaintext = random_string(500)
    key = random_string(random.randrange(1,100))
    ciphertext = cypherString(plaintext, key)
    assert cypherString(ciphertext, key) == plaintext

如果您能提供失败的纯文本,密钥和密文的明确样本,我可以进一步了解。