Search code examples
javaencryptioncryptographyclassnotfoundexceptionsealed-class

Encryption and decryption of sealed object in different java services throws classNotFoundException


I'm encrypting employee class below using AES and saving it as sealedObject as part of serviceA.

org.company.serviceA.model.employee;
class employee{
Integer ssn;
String name;
}

org.company.serviceB.model.employee;
class employee{
Integer ssn;
String name;
}

And In serviceB, when I try to decrypt the sealedObject back to employee class.

employee emp = (employee) sealedObject.getObject;

It throws ClassNotFoundException saying org.company.serviceA.model.employee not found.

Clearly it is trying to find the employee class of ServiceA by fully qualified name, even when I have created a similar class in serviceB.

When both encrypt and decrypt are done in the same service, it works fine. But when they are done in different service, decrypt throws ClassNotFoundException.

So is there a way to overcome ClassNotFoundException and decrypt the sealed object in serviceB ?


Solution

  • You either have to use the same classes / source code, or you will have to think about a different way to encode / decode the employee class. Java always works with full class names internally.

    If you would create a (stateless) library with the Person class in it then you can import that library in both services. Any differences in the Person class can be avoided by good class design.


    For instance, you could create your own serialization method.

    Alternatively you could simply encrypt / decrypt a byte array created around the person. It would make sense to somehow use the X500 / LDAP elements for the encoding / decoding - that's however more a research direction than a direct answer.

    In the end any thing that directly encodes / decodes to bytes in a canonical way would fit the bill, I suppose.