hello everyone,i need to make an encryption/decryption program
and I'm almost finished, the problem is when i tried to add some gui an error about throwing exception keeps showing..

this is the code without the gui and it works just fine because the throws Exception is in the main..

import java.io.*;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.util.*;
 
public class FileEncryptor
{
	private static String filename;
	private static String password;
	private static FileInputStream inFile;
	private static FileOutputStream outFile;
 
	public static void main(String[] args) throws Exception
	{
 
	   // File to encrypt.  It does not have to be a text file!
 
	   filename = "myFile.txt";
 
	   // Password must be at least 8 characters (bytes) long
 
	   String password = "super_secret";
 
	   inFile = new FileInputStream(filename);
	   outFile = new FileOutputStream(filename + ".des");
 
	   // 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 keyFactory =
	       SecretKeyFactory.getInstance("PBEWithMD5AndDES");
	   SecretKey passwordKey = keyFactory.generateSecret(keySpec);
 
	   // PBE = hashing + symmetric encryption.  A 64 bit random
	   // number (the salt) is added to the password and hashed
	   // using a Message Digest Algorithm (MD5 in this example.).
	   // The number of times the password is hashed is determined
	   // by the interation count.  Adding a random number and
	   // hashing multiple times enlarges the key space.
 
	   byte[] salt = new byte[8];
	   Random rnd = new Random();
	   rnd.nextBytes(salt);
	   int iterations = 100;
 
	   //Create the parameter spec for this salt and interation count
 
	   PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, iterations);
 
	   // Create the cipher and initialize it for encryption.
 
	   Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
	   cipher.init(Cipher.ENCRYPT_MODE, passwordKey, parameterSpec);
 
	   // Need to write the salt to the (encrypted) file.  The
	   // salt is needed when reconstructing the key 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 = cipher.update(input, 0, bytesRead);
	      if (output != null) outFile.write(output);
	   }
 
	   byte[] output = cipher.doFinal();
	   if (output != null) outFile.write(output);
 
	   inFile.close();
	   outFile.flush();
	   outFile.close();
 
	}
}

and this is my version with the added gui...

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
 
import java.awt.Toolkit;
import java.io.*;
 
import java.io.FileWriter;
import java.io.IOException;
 
//import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
 
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.util.*;
 
 
 
public class Encrypt extends JPanel {
    private Button btn_load;
    private Button btn_save;
    private TextField txt_name;
    private Label lbl_name;
    private TextField txt_pass;
    private Label lbl_pass;
    private Label lbl_info;
	private	File file;
 
	private static String filename;
	private static String password;
	private static FileInputStream inFile;
	private static FileOutputStream outFile;
 
 
    public Encrypt(){
        //construct components
        btn_load = new Button ("Load File");
        btn_save = new Button ("Save Encrypted File");
        txt_name = new TextField (100);
        lbl_name = new Label ("File Name:");
        txt_pass = new TextField (100);
        lbl_pass = new Label ("Pass Key:");
        lbl_info = new Label ("Password must be at least 8 characters (bytes) long");
 
        //adjust size and set layout
        setPreferredSize (new Dimension (420, 126));
        setLayout (null);
 
        //add components
        add (btn_load);
        add (btn_save);
        add (txt_name);
        add (lbl_name);
        add (txt_pass);
        add (lbl_pass);
        add (lbl_info);
 
        //set component bounds (only needed by Absolute Positioning)
        btn_load.setBounds (315, 5, 100, 25);
        btn_save.setBounds (110, 95, 305, 25);
        txt_name.setBounds (110, 5, 200, 25);
        lbl_name.setBounds (5, 5, 100, 25);
        txt_pass.setBounds (110, 35, 305, 25);
        lbl_pass.setBounds (5, 35, 100, 25);
        lbl_info.setBounds (110, 65, 305, 25);
 
 
        //set actions
	    btn_load.addActionListener(new ActionListener() {
 
			public void actionPerformed(ActionEvent ae) {
 
			JFileChooser fileopen = new JFileChooser();
			FileFilter filter = new FileNameExtensionFilter("Text Documents (*.txt)", "txt");
 
			fileopen.addChoosableFileFilter(filter);
 
			int ret = fileopen.showDialog(null, "Open file");
 
			switch (ret) {
				case JFileChooser.APPROVE_OPTION:
					file = fileopen.getSelectedFile();
					txt_name.setText(file.getName());
					break;
				case JFileChooser.CANCEL_OPTION:
					file = null;
					txt_name.setText("");
					break;
				case JFileChooser.ERROR_OPTION:
					file = null;
					txt_name.setText("");
					break;
			}	
 
			}
	    });
 
 
		btn_save.addActionListener(new ActionListener() {
 
			public void actionPerformed(ActionEvent ae){
 
	      		String saveLoc = null;
 
				JFileChooser chooser = new JFileChooser();
				chooser.setCurrentDirectory(new java.io.File("."));
				chooser.setDialogTitle("choosertitle");
				chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
				chooser.setAcceptAllFileFilterUsed(false);
 
 
				switch (chooser.showSaveDialog(null)) {
					case JFileChooser.APPROVE_OPTION:
						//System.out.println("getCurrentDirectory(): " + chooser.getCurrentDirectory());
						//System.out.println("getSelectedFile() : " + chooser.getSelectedFile());
						saveLoc = chooser.getSelectedFile().toString();
						break;
					case JFileChooser.CANCEL_OPTION:
						//System.out.println("No Selection ");
						saveLoc = null;
						break;
					case JFileChooser.ERROR_OPTION:
						//System.out.println("No Selection ");
						saveLoc = null;
						break;
				}
 
				if (saveLoc != null) {
 
					// File to encrypt.  It does not have to be a text file!
 
					//filename = file;
 
					// Password must be at least 8 characters (bytes) long
 
					password = txt_pass.getText();
 
					inFile = new FileInputStream(file);
					outFile = new FileOutputStream(saveLoc + "\\" + file.getName() + ".des");
 
					// 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 keyFactory =
					   SecretKeyFactory.getInstance("PBEWithMD5AndDES");
					SecretKey passwordKey = keyFactory.generateSecret(keySpec);
 
					// PBE = hashing + symmetric encryption.  A 64 bit random
					// number (the salt) is added to the password and hashed
					// using a Message Digest Algorithm (MD5 in this example.).
					// The number of times the password is hashed is determined
					// by the interation count.  Adding a random number and
					// hashing multiple times enlarges the key space.
 
					byte[] salt = new byte[8];
					Random rnd = new Random();
					rnd.nextBytes(salt);
					int iterations = 100;
 
					//Create the parameter spec for this salt and interation count
 
					PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, iterations);
 
					// Create the cipher and initialize it for encryption.
 
					Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
					cipher.init(Cipher.ENCRYPT_MODE, passwordKey, parameterSpec);
 
					// Need to write the salt to the (encrypted) file.  The
					// salt is needed when reconstructing the key 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 = cipher.update(input, 0, bytesRead);
					  if (output != null) outFile.write(output);
					}
 
					byte[] output = cipher.doFinal();
					if (output != null) outFile.write(output);
 
					inFile.close();
					outFile.flush();
					outFile.close();	
 
 
				}
 
			}
		});
 
 
 
    }
 
 
    public static void main (String[] args){
 
	    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
 
		int x = (dim.width-300)/2;
		int y = (dim.height-280)/2;
 
        JFrame frame = new JFrame ("Encryptor");
        frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add (new Encrypt());
        frame.setLocation (x,y);
        frame.setResizable(false);
        frame.pack();
        frame.setVisible (true);
 
    }
}

i dont know what to do next and where to put the throw exception to make this work..im just a new to java and i think this isn't that big of a problem to you guys..hope you can help me..thanks :icon_smile:


BTW this is the decryption for the working code..

import java.io.*;
 import java.security.*;
 import javax.crypto.*;
 import javax.crypto.spec.*;
 import java.util.*;
 
 public class FileDecryptor
 {
    private static String filename;
    private static String password;
    private static FileInputStream inFile;
    private static FileOutputStream outFile;
 
    /**
     * Note: All kinds of exceptions can be thrown in main.
     * See the API documentation for each method used.
     */
 
    public static void main(String[] args) throws Exception
    {
 
       // File to decrypt.
 
       filename = "myFile.txt.des";
 
       String password = "super_secret";
 
       inFile = new FileInputStream(filename);
       outFile = new FileOutputStream(filename + ".dcr");
 
       PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
       SecretKeyFactory keyFactory =
           SecretKeyFactory.getInstance("PBEWithMD5AndDES");
       SecretKey passwordKey = keyFactory.generateSecret(keySpec);
 
       // Read in the previouly 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 cipher = Cipher.getInstance("PBEWithMD5AndDES");
       cipher.init(Cipher.DECRYPT_MODE, passwordKey, parameterSpec);
 
 
       byte[] input = new byte[64];
       int bytesRead;
       while ((bytesRead = inFile.read(input)) != -1)
       {
          byte[] output = cipher.update(input, 0, bytesRead);
          if (output != null)
             outFile.write(output);
       }
 
       byte[] output = cipher.doFinal();
       if (output != null)
          outFile.write(output);
 
       inFile.close();
       outFile.flush();
       outFile.close();
   }
 }

Recommended Answers

All 3 Replies

Write a proper class, not a bad hack at a serial program. IOW don't just put everything in main, and catch and handle (when possible) exceptions, don't just declare "throws Exception". The very least you should do is give out a proper error message rather than just dropping out.

masijade is right, since you are new to Java this is just a general structure that I use for Exceptions and Errors,

public static void main(String[] args)
{
  try
  {
    //whatever class call may cause a Throwable Error/Exception
    //In this case: an instance of the Example class
  }
  catch(APossibleException)
  {
    //Tell the user what the error/exception means(i.e. System.out.println("Error Message...."))
  }
}//end main

public class Example throws APossibleException
{
   //your code
}

Look at some try/catch tutorials to get a better idea of what you need for your project.
-Take a look at the Throwable class in the java api, and its subclasses.
The point of java is that it is Object Oriented, looking at your code it looks more like a procedural solution.

its working now!!Thanks masijade and Mattox!!:icon_cheesygrin:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.