Let say in a simple Java program, Considering all the facts, like security and performance, Which is the best way to follow. I tried searching for a answer but proper answer is not out there.

Which is better: “serialize and then encrypt” or “encrypt and then serialize”?

  • 3
    $\begingroup$ How would you encrypt the data before serialization? $\endgroup$ – otus Nov 21 '15 at 5:40
  • $\begingroup$ by using sealedObject in javax.crypto . we can pass an already sealedObject to a byte array stream and then Serialize it. $\endgroup$ – Raveen Athapaththu Nov 21 '15 at 6:37
  • 3
    $\begingroup$ The SealedObject class serializes and then encrypts the object. What's your alternative? $\endgroup$ – otus Nov 21 '15 at 9:05
  • 2
    $\begingroup$ Note that you should keep in mind that SealedObject only claims confidentiality, and that there are several attacks on de-serialization of Java objects possible. I.e. if you use it, make sure that you aren't vulnerable against attackers being able to alter the encrypted objects before you try to unseal them. $\endgroup$ – Maarten Bodewes Nov 21 '15 at 14:38
  • $\begingroup$ Two remarks: if you use SealedObject you need to perform serialization of the SealedObject instance if you require a binary representation. This is of course a nicely standardized way of doing things, but it also adds overhead you may want to avoid. Oh, and you can use GCM to seal objects, but I'm not sure this is secure if you serialize / de-serialize the SealedObject itself (I sure hope this was considered, but SealedObject only claims confidentiality and the de-serialization of SealedObject happens before decryption). $\endgroup$ – Maarten Bodewes Nov 21 '15 at 15:13

If you serialize it, then you have one [likely binary] block of data that you would then need to encrypt.

If you encrypt the contents first (however you might achieve this) and then serialize it, it would presumably have to identify the things that are encrypted, and this could likely leak information about the object or its makeup. Also, this would theoretically open the individual parts up to tampering, or replacement, or other specific attack.

Therefore, I assume the best answer is to serialize and then encrypt.

|improve this answer|||||
  • $\begingroup$ Note that if you consider encrypting your serialized data for sending it to another party then you should consider transport security, which is of course a form of serialize-then-encrypt. TLS is probably the most prevalent contender for transport mode security. Just using single-key AES-encrypt would likely not be a secure solution. $\endgroup$ – Maarten Bodewes Mar 27 '19 at 12:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.