此代码接受位串并将其转换为字符串。位串来自读取到客户端的 txt 文件,转换为位串然后发送到服务器。
def getChar(charstr):
char = []
for byte in charstr.split():
char.append(chr(int(''.join([str(bit) for bit in byte]), 2)))
return ''.join(char)
有问题的位串是:
10010011101101111000011001011100001110001111010001101101110010111011101110100100000110010110000110010110000100001
呼出这条线
char.append(chr(int(''.join([str(bit) for bit in byte]), 2)))
并给出错误:
OverflowError: Python int too large to convert to C long.
我将如何解决这个问题?
完整的服务器代码:
import socket
import random
import sys
def getCaesar(message, key):
enc = ""
for char in message:
if char == ' ':
enc = enc + char
elif char.isupper():
enc = enc + chr((ord(char)+key-65)%26+65)
elif char.islower():
enc = enc + chr((ord(char) + key - 97) % 26 + 97)
else:
enc = enc +chr((ord(char) + key - 33) % 32 + 33)
return enc
def getBinary(bitstr):
bit=' '.join(format(ord(char), 'b') for char in bitstr)
return bit
def getChar(charstr):
char = []
for byte in charstr.split():
char.append(chr(int(''.join([str(bit) for bit in byte]), 2)))
return ''.join(char)
def getBitstr(k):
result=""
for num in range(0,k):
result=''.join(str(random.randint(0,1))for num in range(k))
return result
def getXor(a,b):
a=a.replace(" ","")
b=b.replace(" ","")
result = int(a,2) ^ int(b,2)
return '{0:b}'.format(result)
def Decrypt(message, key):
enc = ""
for char in message:
if char == ' ':
enc = enc + char
elif char.isupper():
enc = enc + chr((ord(char)-key-65)%26+65)
elif char.islower():
enc = enc + chr((ord(char) - key - 97) % 26 + 97)
else:
enc = enc +chr((ord(char) - key - 33) % 32 + 33)
return enc
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host=socket.gethostname()
port=4000
s.bind((host,port))
s.listen(5)
print("Listening...")
while True:
c,addr=s.accept()
print("Got connection from ",addr)
print("Receiving...")
l = c.recv(4096).decode()
a=str(l)
cipherF=open("ciphertext.txt",mode='r')
caesar=cipherF.read()
key=Decrypt(caesar,4)
key=''.join(key)
b=str(key)
content=getXor(a,b)
dec=getChar(content)
if not l:
break
print("Decrypting...")
print(dec)
s.close()