How to encrypt/decrypt a file in Java?

◇◆丶佛笑我妖孽 提交于 2019-12-01 12:58:21

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.

Maybe this open source library can help you:

http://www.jasypt.org/

Use the password to encrypt your data. You could for example repeat the password so that it matches the byte array's length and then do something like

data[i] = data[i] >> password[i];

Edit: if you wanted to store the password, you would have to encrypt it. Which - at least when using symmetrical cryptosystems - will be inherently insecure.

Don't store it there! Any good encryption is based on mathematical algorithms (like AES). You may want to have a look at BouncyCastle http://www.bouncycastle.org/ - but encryption is not a simple topic, so you should get a good book to learn about its basics first!

try the sample given below. u could convert the bytes to string and then encrypt and then write it to file. reverse it while decrypting.

http://www.exampledepot.com/egs/javax.crypto/desstring.html

below u can find a sample DES enc&dec for files..

http://www.exampledepot.com/egs/javax.crypto/DesFile.html

A really simple way to use a password to encrypt is to use XOR, here is some pseudo code

for(byte in file)
{
    Byte newByte = byte ^ (byte) password[i];
    outputFile.write(newByte);
    i = (i + 1) password.length();
}

This is based on the identity that (x XOR y) XOR y = x, all you need to do is encrypt/decrypt with the same password.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!