Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: Java Encryption Decryption , +
Hello!
I doing a project in which data transfer should be secured. I am using password based encryption with MD5 and DES for encrypting the file.
The class for encrypting the file:
public class FileEncryptor {	
	private static String filename;
	private static String password;
	private static FileInputStream inFile;
	private static FileOutputStream outFile;
	public static String tempFilename;
	public static File tempFile;
	
	public static File encryptFile(File f, String passkey) throws Exception {
		if(f.isDirectory()) {
			JOptionPane.showMessageDialog(null, "file object is a directory");
			return null;
		}
		filename = f.getPath();
		password = passkey;		
		//Need to create a temporary file which is filled with the encrypted data.
		tempFilename = filename + ".des";
		tempFile = new File(tempFilename);		
		inFile = new FileInputStream(f);
		outFile = new FileOutputStream(tempFile);		
		// Use PBEKeySpec to create a key based on a password.
		// The password is passed as a character array.
		PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
		SecretKeyFactory sKeyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
		SecretKey sKey = sKeyFac.generateSecret(keySpec);		
		byte[] salt = new byte[8];
		Random rnd = new Random();
		rnd.nextBytes(salt);
		int iterations = 100;		
		 //Create the parameter spec for this salt and iteration count
		PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, iterations);
		//Create the cipher and initiate it for encryption
		Cipher c = Cipher.getInstance("PBEWithMD5AndDES");
		c.init(Cipher.ENCRYPT_MODE, sKey, parameterSpec);
		
		//Need to write the salt into the file. It is required for decryption
		outFile.write(salt);
		
		//Read the file and encrypt its bytes
		byte[] input = new byte[64];
		int bytesRead;
		while((bytesRead = inFile.read(input)) != -1) {
			byte[] output = c.update(input, 0, bytesRead);
			if(output != null) { outFile.write(output); }			
		}
		
		byte[] output = c.doFinal();
		if(output != null) { outFile.write(output); }
		
		//Closing the streams before exiting.
		inFile.close();
		outFile.flush();
		outFile.close();
	
		return tempFile;
	}
	
}

 
The class for decrypting the file:
public class FileDecryptor {
 
	private static String filename;
	private static String password;
	private static FileInputStream inFile;
	private static FileOutputStream outFile;
	
	public static File decryptFile(File encryptedFile, String passkey) throws NoSuchAlgorithmException, 
															InvalidKeySpecException, IOException, NoSuchPaddingException,
															InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
		
		String encryptedfilename = encryptedFile.getPath();
		password = passkey;
		
		inFile = new FileInputStream(encryptedFile);
		StringBuffer sb = new StringBuffer(encryptedfilename);
		sb.reverse();
		sb.delete(0, 3);
		sb.reverse();			//removing the ".des" extension of the encrypted file
		filename = new String(sb) + ".dec";
		
		File decrypFile = new File(filename);
		outFile = new FileOutputStream(decrypFile);
		
		PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
		SecretKeyFactory sKeyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
		SecretKey sKey = sKeyFac.generateSecret(keySpec);
		
		// Read in the previously stored salt and set the iteration count.
		byte[] salt = new byte[8];
		inFile.read(salt);
		int iterations = 100;
		
		PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, iterations);
		
		//Create the cipher and initialize it for decryption.
		Cipher c = Cipher.getInstance("PBEWithMD5AndDES");
		c.init(Cipher.DECRYPT_MODE, sKey, parameterSpec);
		
		byte[] input = new byte[64];
		int bytesRead;
		while((bytesRead = inFile.read(input)) != -1) {
			byte[] output = c.update(input, 0, bytesRead);
			if(output != null) {
				outFile.write(output);
			}
		}
		
		byte[] output = c.doFinal();
		System.out.println("Decrypted the data....");
		System.out.println("Wrting the data into file!!");
		if(output != null) {
			outFile.write(output);
		}
		System.out.println("Closing the streams");
		inFile.close();
		outFile.flush();
		outFile.close();
		
		return decrypFile;		
	}
}
 
Sending logic:
 public static void main(String[] args) {
		// TODO Auto-generated method stub
		Socket cs;
		OutputStream os;
		FileInputStream fis;
		byte[] b = new byte[6022386];
		File f = new File("D:\\abc.txt");
		File tempFile;
				
		try {
			tempFile = FileEncryptor.encryptFile(f, "impetus");
			fis = new FileInputStream(tempFile);
			ServerSocket ss = new ServerSocket(7007);
			System.out.println("Created and listening...");
			while(true) {
				System.out.println("Incoming connection!!!!!!!!");
				cs  = ss.accept();
				System.out.println("Client connected");
				os = cs.getOutputStream();
				fis.read(b);
				System.out.println("Sending the encrypted data");
				os.write(b);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
	} 
 
Receiving logic:
 public static void main(String[] args) {
		// TODO Auto-generated method stub
		File f = new File("D:\\P2PFolder\\ToDec.txt.des");
		FileOutputStream fos;
		InputStream is;
		Socket s;
		int bytesRead = 0;
		int current = 0;
		byte[] rb = new byte[6022386];
		try {
			fos = new FileOutputStream(f);
			System.out.println("Connecting.....");
			 s = new Socket(InetAddress.getLocalHost(), 7007);
			 System.out.println("Connected!!!");
			 is = s.getInputStream();
			 do {
				 System.out.println("Reading encrypted data from socket");
				 bytesRead = is.read(rb, current, (rb.length - current));
				 System.out.println(new String(rb) + bytesRead);
				 if(bytesRead > 0) {
					 current += bytesRead;
				 }
			 } while(bytesRead > -1);
			fos.write(rb);
			is.close();
			fos.flush();
			fos.close();
			System.out.println("Decrypting the file");
			FileDecryptor.decryptFile(f, "impetus");
		} catch (Exception e) {
			e.printStackTrace();
		}
	} 
 
No exceptions are being thrown but no data is being transferred also. The encryption part is done successfully. But the transferring and decryption are not happening. I checked the code for transferring the file without encryption, it is working. The encryption and decryption classes are also working when used separately without file transfer. Can someone please point out where am I going wrong here. I am sorry if the code is too long but had to present what I tried.
Posted 3-Apr-13 4:50am

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 OriginalGriff 325
1 DamithSL 300
2 Sergey Alexandrovich Kryukov 289
3 CPallini 235
4 Maciej Los 215
0 OriginalGriff 5,455
1 DamithSL 4,422
2 Maciej Los 3,860
3 Kornfeld Eliyahu Peter 3,480
4 Sergey Alexandrovich Kryukov 3,010


Advertise | Privacy | Mobile
Web01 | 2.8.141216.1 | Last Updated 3 Apr 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100