0

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

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

4

1 回答 1

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

bin(ord(x)) generates strings of variable length. For example:

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

You concatenate all of the results of bin() together, so there's no way to separate them later. Meanwhile, your toString() function reads exactly 7 "bits" at a time.

You could make bin() append chunks of a fixed-size instead:

# 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')
于 2019-02-25T02:02:43.713 回答