使用Gson反序列化RSAPublicKey

时间:2012-07-05 22:49:03

标签: java serialization encryption gson

我正在尝试用Gson反序列化RSAPublicKey,但它不能按照我的意愿工作。 Gson首先抱怨,因为它说RSAPublicKey没有no-arg构造函数,所以我创建了一个InstanceCreator

public static class PublicKeyInstanceCreator implements InstanceCreator<RSAPublicKey> {
    public RSAPublicKey createInstance(final Type type) {
        try {
            final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
            keyGen.initialize(2048);
            final KeyPair key = keyGen.generateKeyPair();
            return (RSAPublicKey) key.getPublic();
        } catch (final NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }
}

并在创建Gson对象时注册它

Gson gson = new GsonBuilder().registerTypeAdapter(RSAPublicKey.class, new PublicKeyInstanceCreator()).create();

现在Gson似乎运行正常,但是从解析Json文件创建的RSAPublicKey对象是从RSAPublicKey返回的任何PublicKeyInstanceCreator对象,即字段永远不会更改反序列化过程。如何让Gson正确返回我想要的对象?

0 个答案:

没有答案