如何用Java加密/解密文件? [英] How to encrypt/decrypt a file in Java?

查看:157
本文介绍了如何用Java加密/解密文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我只是加密领域的初学者所以我想在开头写一个非常简单的应用程序。



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



<那么我可能会使用一些非常简单的密码,例如将每个字节向上移位1 然后我会得到加密字节 byte encryptedBytes [] 让我们说我也会为它设置一个密码,例如123456789。



接下来,当有人想要解密时那个文件,他必须首先输入密码(123456789)然后才能解密文件(因此每个字节按1 向下移动),然后保存到输出文件中 java.io.FileOutputStream中





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



将密码(例如密码字母的ASCII序号)添加到文件的开头可能是愚蠢的(在加密数据之前。)





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

解决方案

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


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.

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.

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".

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?

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).


So my main question is how to store the password information to the encrypted file?

解决方案

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.

这篇关于如何用Java加密/解密文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆