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

问题描述 投票:0回答:1

我正在为一项任务制作加密程序,但我无法解密。原因是键是由随机生成的位串组成的字符串,但是当将键转回到位串时,我得到一个不同的位串。我在检查并发现将密钥转回二进制后的位串短于用于生成密钥的位串时,我意识到了这一点。

##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真假

python security encryption binary one-time-pad
1个回答
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')
© www.soinside.com 2019 - 2024. All rights reserved.