问题:
我目前正在为 Android API Level 19 编写一个应用程序(是的,我知道它已经很旧了)。我在序列化设置数据时遇到问题。部分问题在于某些数据是 secret 的,必须在写入磁盘之前进行加密。因此存在加密和未加密数据的混合。数据由int、Boolean、String、byte[]等类型组成。
如果有兴趣的话,当应用程序启动时,用户必须输入 PIN 码。 PIN 通过哈希算法运行几次。在运行过程中,会获取加密 key ,然后哈希循环运行直至完成。所以中间结果是关键,最终结果才是验证。验证被写入设置文件,而 key 用于加密或解密 secret 数据。还有其他保护措施,但这就是它的工作原理。
我发现的大多数实现都使用 HashMap 和 ObjectOutputStream,但由于加密问题而无法使用(根据我迄今为止看到的示例)。我确实在 Android 开发者文档中遇到过 Data 类,但 Android Studio 说它需要 API 29 才能使用。
研究:
我在不同的地方找到了很多答案,例如:
Reliably convert any object to String and then back again
https://developer.android.com/reference/androidx/work/Data
https://beginnersbook.com/2013/12/how-to-serialize-hashmap-in-java/
https://developer.android.com/guide/topics/security/cryptography#java
...还有很多其他的,但由于我想做的事情,我无法真正使用它们。
最佳答案
您具体提出的问题的答案是:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOuputStream oos = new ObjectOuputStream(baos);
oos.writeObject(someObject);
oos.close();
byte[] serialized = baos.toByteArray();
这会序列化为字节数组。没有使用任何文件。然后,您可以在编写序列化之前对其进行加密...使用您选择的任何加密方案。
但是,更好的想法是将加密放入输出管道中;例如
FileOutputStream fos = new FileOutputStream(path);
Cipher c = ...
CipherOutputStream cos = new CipherOutputStream(fos, c);
ObjectOuputStream oos = new ObjectOuputStream(baos);
oos.writeObject(someObject);
oos.close();
在写入文件系统之前序列化将被加密。
关于java - 如何在不使用文件的情况下序列化对象(例如 HashMap)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59717276/