如何在 Java 中加密/解密文件?

2022-01-22 00:00:00 encryption passwords java

我正在编写一个 Java 应用程序,它可以加密"并因此解密"任何二进制文件.

I am writing a Java application which can "encrypt" and consequently "decrypt" whatever binary file.

我只是密码学"领域的初学者,所以我想写一个非常简单的应用程序作为开始.

I am just a beginner in the "cryptography" area so I would like to write a very simple application for the beginning.

为了读取原始文件,我可能会使用 java.io.FileInputStream 类来获取文件的字节数组"byte originalBytes[].

For reading the original file, I would probably use the java.io.FileInputStream class to get the "array of bytes" byte originalBytes[] of the file.

然后我可能会使用一些非常简单的密码,例如将每个字节上移 1",然后我会得到加密"字节 byte encryptedBytes[] 假设我还要为它设置一个密码",例如123456789".

Then I would probably use some very simple cipher, for example "shift up every byte by 1" and then I would get the "encrypted" bytes byte encryptedBytes[] and let's say that I would also set a "password" for it, for example "123456789".

接下来,当有人想解密"该文件时,他必须先输入密码(123456789"),然后才能解密文件(因此每个字节下移 1") 并因此通过 java.io.FileOutputStream 保存到输出文件.

Next, when somebody wants to "decrypt" that file, he has to enter the password ("123456789") first and after that the file could be decrypted (thus "shift down every byte by 1") and consequently saved to the output file via java.io.FileOutputStream.


我只是想知道如何将密码信息存储"到加密文件中,以便解密应用程序知道输入的密码和真实"密码是否相等?


I am just wondering how to "store" the password information to the encrypted file so that the decrypting application knows if the entered password and the "real" password equals?

将密码(例如密码字母的 ASCII 序数)添加到文件的开头(加密数据之前)可能会很愚蠢.

Probably it would be silly to add the password (for example the ASCII ordinal numbers of the password letters) to the beginning of the file (before the encrypted data).


所以我的主要问题是如何将密码信息存储到加密文件中?

推荐答案

不检查用户提供的密码与全局密码可能会更容易,而是确保只有一个密码(用户知道)解密将密文转换为正确的明文,任何其他密码都会返回乱码.这通常是密码学的工作原理,这意味着您不必在任何地方存储集中式密码.

It would probably be easier not to check the password give by the user against a global password, rather ensure that only that one password (known by the user) decrypts the ciphertext into the correct plaintext, any other password would return gibberish. This is usually how cryptography works and means you don't have to store a centralised password anywhere.

相关文章