我的代码中有一个KeyChain
类,它允许我存储到磁盘并检索加密的凭据列表。
在KeyChain
's 的构建过程中,我初始化了 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:我不能只调用initCryptograhy(char[] password)
readObject ,因为那里没有可用的密码,我不能将它作为参数传递,这是问题的根源。