你好,我有以下问题:java读取加密对象
我有一个类/对象访问至极序列化。
public class Access implements Serializable {
private static final long serialVersionUID = 1L;
private URL website;
private String username;
private String password;
// + some methods
}
现在,当他们写入文件我使用密码加密它们。看起来是这样的:
写作:
ObservableList<Access> userData;
userData = FXCollections.observableArrayList();
...
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key128);
File file = new File("./resources/saves" + username);
file.createNewFile();
CipherOutputStream cipherOut = new CipherOutputStream(
new BufferedOutputStream(new FileOutputStream(file, true)), cipher);
ObjectOutputStream out = new ObjectOutputStream(cipherOut);
userData.forEach((item) -> {
try {
out.writeObject(new SealedObject(item, cipher));
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
});
out.flush();
out.close();
阅读:
ObservableList<Access> access = FXCollections.observableArrayList();
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, key128);
CipherInputStream cipherIn = new CipherInputStream(
new BufferedInputStream(new FileInputStream("./resources/saves" + username)), cipher);
ObjectInputStream in = new ObjectInputStream(cipherIn);
SealedObject sealed;
while ((sealed = (SealedObject) in.readObject()) != null) {
access.add((Access) sealed.getObject(cipher));
}
如果我现在加载似乎已损坏的文件。我发现很难找到这个错误。我认为问题在加载函数中。我在这里错过了明显的东西吗?
错误:
java.io.StreamCorruptedException: invalid stream header: 3D23898C
感谢您的时间&帮助! :*
如果您注释掉您的方法中的(de)加密内容,会发生什么情况?你能写和读回一个未加密的对象吗? – 9000
我刚刚尝试过,现在在阅读时遇到EOF异常。我可能会搞砸了吗? **编辑**是循环的一些问题。它工作正常,没有加密。 –
@Emmanuel:不是我会尝试另一种方式:通过密码流写入和读回字符串,以确保这部分工作正常。 – 9000