无法序列化我的类对象

时间:2015-04-06 15:39:23

标签: java serialization rsa

我正在使用2个类RSAKeyPack.java和SerialVersionUIDTest.java

我的问题是我无法序列化RSAKeyPack的对象。

堆栈跟踪:

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();
        }
    }
}

KeyPairGenerator是问题吗? 它是抽象类吗?

1 个答案:

答案 0 :(得分:2)

keyPairGenerator可能不是可序列化的。

创建该字段transient,然后为其添加一个惰性初始化器getter。

或者完全删除它,只需在需要时直接使用KeyPairGenerator.getInstance("RSA")

transient KeyPairGenerator keyPairGenerator;

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