首页 > 解决方案 > 如何正确加密用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 文件?

标签: javajsonencryptionkotlin

解决方案


将 Jackson 输出写入ByteArrayOutputStream. 然后根据需要对这些字节进行加密,并将它们写入用户选择的文件中。


推荐阅读