Cannot Serialize my class object

I am using 2 classes RSAKeyPack.java and SerialVersionUIDTest.java

My problem is that I cannot serialize the object of RSAKeyPack.

StackTrace:

java.io.NotSerializableException: java.security.KeyPairGenerator$Delegate
 at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
 at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
 at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
 at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
 at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
 at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
 at FADE.SerialVersionUIDTest.main(SerialVersionUIDTest.java:43)
public class RSAKeyPack implements Serializable { //Object to be serialized

    private static final long serialVersionUID = 2L;
    PublicKey publicKey;
    PrivateKey privateKey;
    KeyPairGenerator keyPairGenerator;
    public RSAKeyPack()
    {
        try 
        {
            keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(2048); //1024 used for normal securities
            KeyPair keyPair = keyPairGenerator.generateKeyPair();  
            publicKey = keyPair.getPublic();  
            privateKey = keyPair.getPrivate();          
        } 
        catch (NoSuchAlgorithmException e) 
        {
            e.printStackTrace();
        }
    }
}

Is KeyPairGenerator is the problem? Is it an abstract class?

Answer

keyPairGenerator is not serializable, probably.

Make that field transient, and then just add a lazy-initializer getter for it.

Or remove it entirely and just use KeyPairGenerator.getInstance("RSA") directly whenever you need it.

transient KeyPairGenerator keyPairGenerator;

private KeyPairGenerator getGenerator() {
   if (keyPairGenerator == null) {
       keyPairGenerator = KeyPairGenerator.getInstance("RSA");
       keyPairGenerator.initialize(2048); //1024 used for normal securities
       ...
   }
   return keyPairGenerator;
}

Leave a Reply

Your email address will not be published. Required fields are marked *