Monday, 26 December 2011

Java program to encrypt/decrypt a file with password

Java can be very efficiently in encrypting files in DES mode. In order to encrypt any text or file , first it is necessary to generate a particular key that will be used for encryption.This key is generated based on password. The parameter used is "PBEWithMD5andDES". Then generally a 8 bit salt is created from it. This salt must be written to the file first as it will be required for decryption of the file later. Next we have to create a Cipher object with the particular mode of encryption as its parameter. Then the Cipher object is initialized with the key and either ENCRYPT_MODE or DECRYPT_MODE . After all this is done, we just need to read a stream of bytes from a particular file using FileInputStream and encrypt it and then write to another file using FileOutputStream.
NOTE : The same key must be used for encrypting and decrypting the same file.
Code Extracts :
PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
SecretKeyFactory keyFactory=SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey passwordKey = keyFactory.generateSecret(keySpec); //key from password
byte[] salt = new byte[8];
Random rnd = new Random();
rnd.nextBytes(salt); //getting salt
int iterations = 100;
PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, iterations);
Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES"); //cipher instance
cipher.init(Cipher.ENCRYPT_MODE, passwordKey, parameterSpec); //initializing instance

Click to DOWNLOAD the JAVA file of password based encrypter from
Click to DOWNLOAD the JAVA file of password based decrypter from

No comments:

Post a Comment