java - 如何正确加密用jackson编写的JSON文件
问题描述
我目前正在开发一个小型 Java/Kotlin 程序,它将设置和一些数据写入 JSON 文件。我想实现一个用 AES 加密这个文件的功能。使用 AES 加密文件完全没有问题。
到目前为止,我是这样做的(文件名是“保存文件对话框”中所需保存文件的文件路径,“它”来自 fileOutputStream.use,文件名是目标,superCategory 是要写入的 JSONNode):
//in the end write the stuff to the file
objectMapper.writerWithDefaultPrettyPrinter().writeValue(it, superCategory)
//TODO encrypt? best case: encrypt before ever writing to a file
if(encrypt) {
//up to now I don't know how to get a stream from objectMapper instead of doint it this way
val infile = File(filename)
val outfile = File(filename+"_enc")
AESfileCrypto.doEncryption(password = password, inputFile = infile, outputFile = outfile)
infile.delete()
}
AESfileCrypto 是一个自写的类,它将输入文件加密为输出文件,而输入文件保持不变。正如您从我的评论中看到的那样,我根本不喜欢这样做。仅加密文件并随后删除未加密的文件似乎很容易受到攻击。
我很想在写任何东西之前加密这些东西。有没有办法从 objectMapper 获取 FileInputStream 而不是直接写入文件?或者是否有不同的方式来编写加密的 JSON 文件?
解决方案
将 Jackson 输出写入ByteArrayOutputStream
. 然后根据需要对这些字节进行加密,并将它们写入用户选择的文件中。
推荐阅读
- spring-boot - 如何在 Spring OAuth 中进行相对重定向到授权端点?
- kubernetes - 失败的 K8s rabbitmq-peer-discovery-k8s 集群
- python - 如何在循环内将随机浮点值附加到数组中
- mysql - 如何处理 csv 导入时的“列数据被截断”警告?
- c++ - 我可以在这个例子中使用折叠表达式吗
- c++ - 定义显式转换 - 可能的 GCC 错误
- python - 如何将两个字典写入 CSV?
- c# - 如何使用 Autofac 在同一接口的多个实现之间进行选择?
- c++ - 基本/默认构造函数与构造函数初始化列表
- google-tag-manager - 有没有办法让内容安全策略 2 与 Google 跟踪代码管理器一起使用?