Francesco Rizzi
Francesco Rizzi

Reputation: 631

Java Encrypted Object Serialization through sockets

I'm trying to implement a method which provides data encryption using Object Serialization through Sockets (ObjectInputStream && ObjectOutputStream are used).

The aim here is to reduce everything to an array of byte data, which will be used as input for an encryption algorithm.

Here is a very rude code which i wrote to simply test and see how things work:

List<Byte> bytes=new LinkedList<>();
    try (

        ByteArrayOutputStream bos=new ByteArrayOutputStream();
        ObjectOutputStream oos=new ObjectOutputStream(bos);
        InputStream finalInputStream=new InputStream() {

            int counter=0;
            @Override
            public int read() throws IOException {

                if (counter<bytes.size()) {

                    return bytes.get(counter++);
                }
                else return -1;
            }
        };

        OutputStream finalOutputStream=new OutputStream() {

            @Override
            public void write(int b) throws IOException {

                bytes.add((byte) b);
            }
        };
        BufferedOutputStream bfos=new BufferedOutputStream(finalOutputStream);
        BufferedInputStream bios=new BufferedInputStream(finalInputStream);
        ObjectInputStream ois=new ObjectInputStream(bios);
    ){

        oos.writeObject(new CryptoMain());
        oos.flush();
        bfos.write(bos.toByteArray());

        CryptoMain obj=(CryptoMain)ois.readObject();
        obj.printHello();
    }
    catch(Exception e) {

        e.printStackTrace();
    }

However i get EOFException at this statement:

ObjectInputStream ois=new ObjectInputStream(bios);

How can i obtain what i want? Is there an other way?

Thank you.

Upvotes: 0

Views: 222

Answers (1)

user207421
user207421

Reputation: 310893

You don't need most of this.

You don't need both the ByteArrayOutputStream and the List<Byte> and the local InputStream class. You're doing everything three times. You don't actually need any of them.

There are several simple solutions:

  1. javax.crypto.SealedObject
  2. javax.crypto.CipherInput/OutputStream.
  3. TLS.

Upvotes: 1

Related Questions