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.
Maybe this open source library can help you:
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..
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.
来源:https://stackoverflow.com/questions/2442264/how-to-encrypt-decrypt-a-file-in-java