序列化期间的构造函数调用

时间:2013-11-06 01:54:08

标签: java serialization encryption aes state

我的代码中有一个KeyChain类,它允许我存储到磁盘并检索加密的凭据列表。

KeyChain构建期间,我初始化AES密码。

要序列化对象,我首先将凭证列表序列化为缓冲区,然后加密该缓冲区并将其放入原始OutputObjectStream

要反序列化它,我尝试将ObjectInputStream读入缓冲区,解密并从中反序列化我的凭据,但为此,我需要首先构建密码。我不能这样做,因为反序列化不会调用我的构造函数。我怎么扭转这个?

钥匙串:

private void readObject(ObjectInputStream is) throws IOException {
    byte[] buffer = new byte[512000];

    int readBytes = is.read(buffer);

    byte[] encryptedBytes = new byte[readBytes];
    System.arraycopy(buffer, 0, encryptedBytes, 0, readBytes);

    // Here it crashes and burns because i can't decrypt yet, the ciphers haven't been setup
    byte[] decryptedBytes = decryptBytes(encryptedBytes);

    ByteInputStream stream = new ByteInputStream(decryptedBytes, readBytes);
    ObjectInputStream unsafeInputStream = new ObjectInputStream(stream);
    try {
        Keys = (List<Key>)unsafeInputStream.readObject();
    } catch (ClassNotFoundException ex) {
        // Fail miserably
    }
}

private void writeObject(ObjectOutputStream os) throws IOException {
    ByteOutputStream streamBytes = new ByteOutputStream();
    ObjectOutputStream unsafeOutputStream = new ObjectOutputStream(streamBytes);

    unsafeOutputStream.writeObject(Keys);
    unsafeOutputStream.flush();

    byte[] decryptedBytes = streamBytes.getBytes();

    byte[] encryptedBytes = encryptBytes(decryptedBytes);

    os.write(encryptedBytes);
    os.flush();

    Arrays.fill(decryptedBytes, (byte)0);
    Arrays.fill(encryptedBytes, (byte)0);
}

gotcha:我不能只在readObject中调用initCryptograhy(char[] password),因为我只是没有可用的密码,我无法将其作为参数传递,这是问题的根源。

1 个答案:

答案 0 :(得分:2)

Java实际上有一个名为SealedObject的工具,用于加密序列化实例。也许这对你想要实现的目标更有效。我认为你在做什么和SealedObject做的关键区别在于它在第二阶段进行解密,而不是在最初的反序列化中进行解密。

相关问题