views:

273

answers:

4

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.

A: 

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.

Bill K
same as @Randy Simon's answer, see the comments
Tom Brito
please, see my update
Tom Brito
A: 

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.

Randy Simon
The same security considerations that dictated that the class should not be Serializable should dictate that this method not be written.
EJP
please, see my update
Tom Brito
A: 

java.beans.XMLEncoder/Decoder.

EJP
absolutely not secure
Tom Brito
Of course. Nothing you can do about that. It exists whether you like it or not, so therefore the class in question is insecure if it is XMLEncodable.What I think you need is a method *in the class* that delivers a SealedObject and that uses private member data to construct it.
EJP
A: 

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.. :)

Tom Brito