我正在使用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问题吗?
它是抽象类吗?
最佳答案
keyPairGenerator可能无法序列化。
使该字段为transient
,然后为其添加一个惰性初始化获取器。
或将其完全删除,并在需要时直接使用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;
}