Python网络字节与java略有不同

2024-04-24 16:20:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近一直在做一个网络项目来恢复一个死了的mmo游戏以供个人学习,我有一个python实现,它使用blowfish(pypi/pycryptodome)来解码游戏数据,并希望将这个“服务器”转移到一个java项目中。你知道吗

最初在java中使用blowfish解密(BouncyCastle和Cipher——默认值),我在java和python之间得到了完全不同的结果。通过一些研究,我发现java(以及大多数东西)实际上使用了blowfish compat big endian。你知道吗

这个python库似乎是唯一一个正确解码数据的库。接下来,我决定使用python异步服务器作为中间中继,只用于加密和解密。网络流现在如下所示:

GameClient -> Java SocketServer -> Python server (decryption) -> Java SocketServer。你知道吗

最初的Python实现以十六进制格式生成这些字节:

32004a815f49367cc3691be26d7b668132506dc972d5a6bbad38299640c6e222c6e55096f50ff33711250675431633ca9ede

Java实现以十六进制格式(使用apachecommons)生成这些结果十六进制编码十六进制字符串())

32004a815f49367cc3691be26d7b668132506dc972d5a6bbad38299640c6e222c6e5c65830d65f9b4d60eb26730685f486d7

这两个十六进制表示都是Python中的预blowfish解密,它们只是从游戏客户端发送的原始字节。你知道吗

我的问题是,为什么这些字节的开头是一样的,而java却似乎落后了?python结果是正确的结果,它们经过测试并工作。我曾尝试将java中的字节包装到缓冲区中,然后调用flip(),但是这也没有产生正确的结果。你知道吗

我使用的代码分布在多个类和文件中,因为服务器需要多线程来实现作为中间人的python服务器,但是如果我需要发布代码以获得响应,我会很高兴地编辑和发布所需的内容。非常感谢您的帮助

编辑:代码栏

Python实现

#!/usr/bin/env python3

import asyncio
import binascii
import blowfish
import ipaddress
import os
import struct
import sys

AUTH_BLOWFISHKEY = b"[;'.]94-31==-%&@!^+]\000"
bf = blowfish.Cipher(AUTH_BLOWFISHKEY, byte_order="little")


class EncryptionRelay(asyncio.Protocol):
    def connection_made(self, transport):
        self.transport = transport
        self.client = (transport.get_extra_info('peername')[0] + ":"    # IP
        + str(transport.get_extra_info('peername')[1]))             # port
        print("Connection from: " + self.client)


    def connection_lost(self, exc):
        print("Connection closed: " + self.client)


    def data_received(self, data):
        print(data.hex()) #python output above
        pt = b''.join(bf.decrypt_ecb(data[2:]))
        self.transport.write(pt)

    def closeSocket(self, reason):
        print(reason)
        self.transport.close()


def main():
    loop = asyncio.get_event_loop()
    coroutine = loop.create_server(EncryptionRelay, host=None, port=54556)
    server = loop.run_until_complete(coroutine)

    for socket in server.sockets:
        print("Listening on: " + socket.getsockname()[0] + ":" +
        str(socket.getsockname()[1]))
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass

    server.close()
    loop.run_until_complete(server.wait_closed())
    loop.close()


if __name__ == "__main__":
    main()

Java实现

public AuthServer(int port) {
    serverGUI = new AuthServerGUI(port);

    try {
        serverSocket = new ServerSocket(port);
        relay = new PythonEncryptionRelay(this);
        new Thread(relay).start();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

@Override
public void run() {
    while(true) {
        try {
            Socket socket = serverSocket.accept();
            onConnection(socket); //sends an init packet to client -- irrelevant to question 

            byte[] incomingData = new byte[0];
            byte[] temp = new byte[1024];
            int k = -1;

            while((k = socket.getInputStream().read(temp, 0, temp.length)) > -1) {
                byte[] tbuff = new byte[incomingData.length + k];
                System.arraycopy(incomingData, 0, tbuff, 0, incomingData.length);
                System.arraycopy(temp, 0, tbuff, incomingData.length, k);
                incomingData = tbuff;

                receiveData(socket, incomingData);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public void receiveData(Socket socket, byte[] data) {
    int lenLo = (int) (data[0]);
    int lenHi = (int) (data[1]);
    int length = lenHi * 256 + lenLo;


    if(lenHi < 0) {
        System.out.println("Invalid Packet Length");
    }

    if(data.length != length) {
        System.out.println("Incomplete Packet Received");
    }

    serverGUI.serverDebug("DATA RECEIVED");
    serverGUI.serverDebug(Hex.encodeHexString(data)); //this is the java ouput above serverGUI is simply a jframe i built no data manipulation
    serverGUI.serverDebug("DATA_RECEIVED DONE");
    this.relay.sendData(data); //this function sends the data from socket server to the python asyncio server
}

public void receiveDataFromPythonRelay(Socket socket, byte[] data) {
    serverGUI.debugPythonRelay("DATA RECEIVED");
    serverGUI.debugPythonRelay(Hex.encodeHexString(data)); //this will be the output from the python script aka data decrypted. 
//The data byte[] is created in the exact same way the incomingData array is built in the AuthServer run function
    serverGUI.debugPythonRelay("DATA_RECEIVED DONE");
}

另外,我从套接字导入数据字节[]的方式是这样编程的,因为客户端不发送endl,因此readLine将无法从流中工作。你知道吗


Tags: theimportselfloopnewdataserversocket