等效字符串在Python中不提供等效位字符串

时间:2019-02-25 01:15:56

标签: python security encryption binary one-time-pad

我目前正在为分配工作编写加密程序,但是我无法解密。原因是密钥是由随机生成的位串组成的字符串,但是当将密钥转换回位串时,会得到不同的位串。在检查并发现将密钥重新转换为二进制后的位串比用于制作密钥的位串短时,我才意识到这一点。

##imports##################################################
from socket import *
import random

##functions################################################
def CCipher(message, k):
    output = ""
    for x in message:
        i = ord(x)
        i = (i+k)%128
        output += chr(i)
    return output

def toBinary(message):
    output = ""
    for x in message:
        i = bin(ord(x))[2:]
        output += i
    return output

def XOR(bitstring1, bitstring2):
    output = ""
    if(len(bitstring1) != len(bitstring2)):
        print("Use bitstrings of the same length")
        return None
    for x in range(len(bitstring1)):
        if(bitstring1[x] == "1" and bitstring2[x] == "0"):
            output += "1"
        elif(bitstring1[x] == "0" and bitstring2[x] == "1"):
            output += "1"
        else:
            output += "0"
    return output

def randomBinary(k):
    output = ""
    for x in range(k):
        i = random.randint(0,1)
        output = output + str(i)
    return output

def toString(message):
    output = ""
    i = ""
    n = 0
    for x in message:
        n += 1
        i += x
        if(n == 7):
            output += chr(int(i,2))
            n = 0
            i = ""
    return output

##server stuff#########################################
serverName = "OmariPC"
serverPort = 12347
clientSocket = socket(AF_INET,SOCK_STREAM)
clientSocket.connect((serverName,serverPort))

##files################################################
nowar = open("NoWar.dat",'r')
trump = open("Trump.dat","w")

##encryption###########################################
message = nowar.read()
mesBin = toBinary(message)
bkey = randomBinary(len(mesBin))
encrypted = XOR(mesBin, bkey)
encrypted = toString(encrypted)
key = toString(bkey)
trump.write(encrypted)
trump.close()
enKey = CCipher(key, 4)

##sending###############################################
clientSocket.send(enKey.encode())
print(len(enKey))
clientSocket.send(encrypted.encode())
print(len(encrypted))

##testing###############################################
if key == toString(bkey):
    print(True)
else:
    print(False)
if len(toBinary(key)) == len(bkey):
    print(True)
else:
    print(False)

输出: 168 168 真正 错误

1 个答案:

答案 0 :(得分:1)

def toBinary(message):
    output = ""
    for x in message:
        i = bin(ord(x))[2:]
        output += i
    return output

bin(ord(x))生成可变长度的字符串。例如:

>>> bin(ord(' '))
0b100000
>>> bin(ord('a'))
0b1100001

您将bin()的所有结果连接在一起,因此以后没有办法将它们分开。同时,您的toString()函数一次只读取7个“位”。

您可以使bin()附加固定大小的块:

# Pad the left with 0s to always generate a string of length 7.
# (Assumes that all input characters are ASCII.)
assert(ord(x) < 128)
bin(ord(x))[2:].rjust(7, '0')