Student
Student

Reputation: 28345

How to convert a non serializable object to byte array?

I'm trying to use javax.crypto.Cipher.doFinal(byte[]) method to encrypt an object. But, for security reasons, the object cannot be serializable. So, how to convert the object to byte array without serialization?

--update

is using serialization the only way to use this Cipher method? Because as I know important data should not be serializable.

Upvotes: 6

Views: 17804

Answers (5)

Makaku00
Makaku00

Reputation: 121

I used com.fasterxml.jackson.databind.ObjectMapper.

  private static byte[] serialize(Object obj) throws IOException {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.writeValue(os, obj);

    return os.toByteArray();
}

Upvotes: 4

Student
Student

Reputation: 28345

Solved, instead of use a getByteArray() to call Cipher.doFinal(), I'll use Cipher.doFinal() inside the class, with a getEncryptedByteArray() method; so I serialize the data inside the class without making the class itself serializable, and the return result will be encrypted. Any objection to this approach will be considered.. :)

Upvotes: 0

user207421
user207421

Reputation: 310883

java.beans.XMLEncoder/Decoder.

Upvotes: -1

Randy Simon
Randy Simon

Reputation: 3324

Here is a simple example of serializing a class to a byte array.

public Class Foo {

    private boolean isHappy;
    private short happyCount;
    private Bar bar;

    public byte[] serializeData () throws IOException
    {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        DataOutputStream out = new DataOutputStream( stream );

        out.writeBoolean(isHappy);
        out.writeShort( slope );

        // Serialize bar which will just append to this byte stream
        bar.doSerializeData(out);

        // Return the serialized object.
        byte[] data = stream.toByteArray();

        // Clean up.
        stream.close();

        return data;
    }
}

Of course, a lot of the details in your case depend on your class structure but hopefully this gets you pointed in the right direction.

To deserialize you just need to reverse the above.

Upvotes: -1

Bill K
Bill K

Reputation: 62769

You just serialize each of it's components. Recurse. Eventually you end up with native objects that you can serialize.

If you implement this by implementing java's serialization methods, java will ensure that you do not serialize any object twice and will take care of references for you.

In short, make the object serializable.

Upvotes: 0

Related Questions