serializationkryonet

Kryonet - how to get the sender (Connection) during serialization?


I have a huge, huge problem. I'm using AES serialization for packets and here comes an issue.

Serializers in Kryo look like this:

public class AESSerializer extends Serializer {
    private final Serializer serializer;

    public AESSerializer (Serializer serializer) {
       this.serializer = serializer;
    }

    public void write (Kryo kryo, Output output, Object object) {
        // USE AES KEY TO ENCRYPT
        // WRITE OBJECT
    }

    public Object read (Kryo kryo, Input input, Class type) {
        // USE AES KEY TO DECRYPT
        // READ OBJECT
    }

}

The problem is here that each user has to have it's own SecretAESKey. I can't find any way to get to the connections lists from the serializer and as I read Kryonet's code - they don't pass it anywhere. I need to get the Connection that writes the object to get it's AES key.

Serializer constructor isn't an option cause serializer is one per application, not for each user.

Do you guys have any idea how to handle things like that?


Solution

  • Kryo has built in this code:

    public synchronized void write (Connection connection, ByteBuffer buffer, Object object) {
       output.setBuffer(buffer);
       kryo.getContext().put("connection", connection);
       kryo.writeClassAndObject(output, object);
       output.flush();
    }
    
    public synchronized Object read (Connection connection, ByteBuffer buffer) {
       input.setBuffer(buffer);
       kryo.getContext().put("connection", connection);
       return kryo.readClassAndObject(input);
    }
    

    In your serializer call:

    Connection connection = (Connection) kryo.getContext().get("connection");
    

    And you have your connection.