Problem Decrypting Files

I am attempting to create a program that will encrypt and decrypt file using password based encryption. However I have been having trouble decrypting. If I try to open up a decrypted .doc Word file it doesn't work or any other files for that matter. Here is the decryption coed I am using. Any suggestions would be extremely appreciated.

publicvoid Decrypt(SecretKey key, File inFile, JTextField outputFile){

try{

FileInputStream fis =new FileInputStream(inFile);

FileOutputStream fos =new FileOutputStream(outputFile.getText());

Cipher cipher = Cipher.getInstance("PBEWithMD5AndTripleDES");

cipher.init(Cipher.DECRYPT_MODE, key);

byte[] buffer =newbyte[(int)inFile.length()];

fis.read(buffer);

fis.close();

byte[] decrypt = cipher.doFinal(buffer);

fos.write(decrypt);

}catch(IOException ioe){

ioe.printStackTrace();

}catch(IllegalBlockSizeException ibse){

ibse.printStackTrace();

}catch(BadPaddingException bpe){

bpe.printStackTrace();

}catch(InvalidKeyException ike){

ike.printStackTrace();

}catch(NoSuchAlgorithmException nsae){

nsae.printStackTrace();

}catch(NoSuchPaddingException nspe){

nspe.printStackTrace();

}

}

[2265 byte] By [j-roda] at [2007-11-15]
# 1

1) What does "doesn't work" mean?

2) Just because it does not decrypt it does not mean that the problem is in your decryption - it could be a problem with your encryption but of course we can't see that since you have not posted it.

3) You should close your output streams

4) Get rid of that dreadful exception handling - it does nothing useful.

5) Change the method so that it does not depend on Swing. To test this code you have to put it in a Swing framework just to get the name of a file. All you need it a File object as argument.

I bet your problem is #3 .

sabre150a at 2007-7-12 > top of java,Security,Cryptography...
# 2

The problem is not closing the OutPutStream. I thought the same thing and put it im my code last night. After doing some debugging I now think that the problem is not in encrypting or decrypting it is with the write method. After a file is encrypted the encrypted file can be viewed in notepad as a longe list of ebcrypted bytes(their String representations at least --I think). However, say Itry to decrytp the file and it was originally a word document. After decryption word won't recognize the file.

Here is the entire code so that you can run it and understand.

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import java.lang.reflect.Array;

import java.io.IOException;

import java.io.FileNotFoundException;

import java.security.InvalidKeyException;

import java.security.NoSuchAlgorithmException;

import java.security.spec.InvalidKeySpecException;

import javax.crypto.BadPaddingException;

import javax.crypto.Cipher;

import javax.crypto.IllegalBlockSizeException;

import javax.crypto.NoSuchPaddingException;

import javax.crypto.SecretKey;

import javax.crypto.SecretKeyFactory;

import javax.crypto.spec.PBEKeySpec;

import javax.swing.ButtonGroup;

import java.util.Arrays;

import javax.swing.JFileChooser;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.awt.TextArea;

import javax.swing.filechooser.FileFilter;

import java.io.FileDescriptor;

class JCE extends JFrame implements ActionListener {

JRadioButton encryptButton;

JRadioButton decryptButton;

JLabel textLabel1;

JTextField inputFile;

JLabel textLabel2;

JTextField outputFile;

JButton chooser2;

JLabel passLabel1;

JPasswordField passwordField1;

JLabel passLabel2;

JPasswordField passwordField2;

JRadioButton delFileButton;

JButton startButton;

JFileChooser fc;

JFrame chooserFrame;

int approve;

File inFile;

String inFileName;

File outFile;

char[] nameChar;

int nameSize;

String outFileName;

char[] password1 = new char[128];

char[] password2 = new char[128];

int size = 0;

String error = "";

int errorCount = 0;

JFrame errorFrame;

SecretKey key;

byte[] salt = new byte[] { (byte) 0x3a, (byte)0x44, (byte)0x7f, (byte)0xf1, (byte)0xa2, (byte)0xe5, (byte)0x87, (byte)0x31 };

int iterations = 1000;

public JCE() {

//creat and display GUI

encryptButton = new JRadioButton("Encrypt ", true);

decryptButton = new JRadioButton("Decrypt");

ButtonGroup cryptGroup = new ButtonGroup();

cryptGroup.add(encryptButton);

cryptGroup.add(decryptButton);

JPanel selectPanel = new JPanel(new FlowLayout());

selectPanel.add(encryptButton);

selectPanel.add(decryptButton);

textLabel1 = new JLabel("Input File");

inputFile = new JTextField(40);

inputFile.setEditable(false);

inputFile.setText(" ");

JButton chooser1 = new JButton("...");

//add actionlisteners

chooser1.addActionListener(this);

chooser1.setActionCommand("chooser1");

JPanel inputPanel = new JPanel(new FlowLayout());

inputPanel.add(textLabel1);

inputPanel.add(inputFile);

inputPanel.add(chooser1);

textLabel2 = new JLabel("Output File");

outputFile = new JTextField(40);

outputFile.setEditable(false);

outputFile.setText(" ");

chooser2 = new JButton("...");

//add actionlisteners

chooser2.addActionListener(this);

chooser2.setActionCommand("chooser2");

JPanel outputPanel = new JPanel(new FlowLayout());

outputPanel.add(textLabel2);

outputPanel.add(outputFile);

outputPanel.add(chooser2);

passLabel1 = new JLabel("Enter password: ");

passwordField1 = new JPasswordField(10);

passwordField1.setEchoChar('*');

passwordField1.setText("");

passLabel2 = new JLabel(" Renter password: ");

passwordField2 = new JPasswordField(10);

passwordField2.setEchoChar('*');

passwordField1.setText("");

JPanel passwordPanel = new JPanel(new FlowLayout());

passwordPanel.add(passLabel1);

passwordPanel.add(passwordField1);

passwordPanel.add(passLabel2);

passwordPanel.add(passwordField2);

delFileButton = new JRadioButton("Delete Input File");

startButton = new JButton("Start Process");

//add actionlisteners

startButton.addActionListener(this);

startButton.setActionCommand("startButton");

JPanel processPanel = new JPanel(new FlowLayout());

processPanel.add(delFileButton);

processPanel.add(startButton);

getContentPane().setLayout(new GridLayout(5,1));

getContentPane().add(selectPanel);

getContentPane().add(inputPanel);

getContentPane().add(outputPanel);

getContentPane().add(passwordPanel);

getContentPane().add(processPanel);

}

public void actionPerformed(ActionEvent ae) {

if(ae.getActionCommand() == "chooser1") {

//create file chooser for selecting input file

fc = new JFileChooser(inFile);

fc.setDialogTitle("Input File");

fc.setFileSelectionMode(fc.FILES_ONLY);

//this filter only allows the display of encrypted files

if(decryptButton.isSelected()) {

fc.addChoosableFileFilter(new DecryptFilter());

approve = fc.showOpenDialog(chooserFrame);

} else {

fc.showOpenDialog(chooserFrame);

}

//display path of file

if (approve == JFileChooser.APPROVE_OPTION) {

inFile = fc.getSelectedFile();

inFileName = fc.getSelectedFile().getName();

inputFile.setText(fc.getCurrentDirectory().getAbsolutePath() + "\\" + inFileName);

}

}

if(ae.getActionCommand() == "chooser2") {

//create an other file chooser for selecting output path

fc = new JFileChooser(outFile);

fc.setDialogTitle("Output File");

//no file filter necessary because only a path is required

//only lets user select folders

fc.setFileSelectionMode(fc.DIRECTORIES_ONLY);

fc.showOpenDialog(chooserFrame);

outFile = fc.getSelectedFile();

//modifies name of the input file to chop off the .encrypt extension if user is

//decrypting a file

if(decryptButton.isSelected()) {

nameChar = inFileName.toCharArray();

nameSize = inFileName.length();

outFileName = "";

for(int a = 0; a < nameSize - 8; a++) {

outFileName = outFileName + nameChar[a];

}

} else {

//adds .encrypt extension if usre is encrypting a file

outFileName = inFileName + ".encrypt";

}

//displays output file path

try {

outputFile.setText(outFile.getCanonicalPath() + "\\" + outFileName);

} catch(IOException ioe) {

ioe.printStackTrace();

}

}

if(ae.getActionCommand() == "startButton") {

//this is all some user error handeling

//chech input file selected

if(inputFile.getText().equals(" ")) {

error = error + " You must select an input file";

errorCount++;

}

//chech output file selected

if(outputFile.getText().equals(" ")) {

if(errorCount >= 1) {

error = error + "\n You must select an output file";

errorCount++;

} else {

error = error + " You must select an output file";

errorCount++;

}

}

//check that password has been enterd, password length, and if they match

password1 = passwordField1.getPassword();

password2 = passwordField2.getPassword();

try {

size = Array.getLength(password1);

} catch(IllegalArgumentException iae) {

iae.printStackTrace();

}

if(size == 0) {

if(errorCount >= 1) {

error = error + "\n You must enter in a password";

errorCount++;

} else {

error = error + " You must enter in a password";

errorCount++;

}

}

if(size > 20) {

if(errorCount >= 1) {

error = error + "\n The password must be 20 characters or less";

errorCount++;

} else {

error = error + " The password must be 20 characters or less";

errorCount++;

}

}

if(!Arrays.equals(password1, password2)) {

if(errorCount >= 1) {

error = error + "\n Enter the same password in both fields";

errorCount++;

} else {

error = error + "Enter the same password in both fields";

errorCount++;

}

}

//start encryption or decryption

if(errorCount == 0) {

//generate key

KeyGenerator(password1, salt, iterations);

//encrypt or decrypt

if(encryptButton.isSelected()){

Encrypt(key, inFile, outputFile, password1, password2, inputFile, passwordField1, passwordField2);

} else {

Decrypt(key, inFile, outputFile, password1, password2, inputFile, passwordField1, passwordField2, encryptButton);

}

} else {

//output and error report

Toolkit.getDefaultToolkit().beep();

JOptionPane.showMessageDialog(errorFrame, error, "ERROR", JOptionPane.ERROR_MESSAGE);

passwordField1.setText("");

passwordField2.setText("");

error = "";

errorCount = 0;

}

}

}

public void KeyGenerator(char[] password1, byte[] salt, int iterations) {

//generate a SecretKey

PBEKeySpec pbeKeySpec;

SecretKeyFactory factory;

try {

pbeKeySpec = new PBEKeySpec(password1, salt, iterations);

factory = SecretKeyFactory.getInstance("PBEWithMD5AndTripleDES");

key = factory.generateSecret(pbeKeySpec);

} catch(NoSuchAlgorithmException nsae) {

nsae.printStackTrace();

} catch(InvalidKeySpecException ikse) {

ikse.printStackTrace();

} catch(IllegalStateException ise) {

ise.printStackTrace();

} catch(ArrayIndexOutOfBoundsException aioobe) {

aioobe.printStackTrace();

} catch(NullPointerException npe) {

npe.printStackTrace();

}

}

public void Encrypt(SecretKey key, File inFile, JTextField outputFile, char[] password1, char[] password2, JTextField inputFile, JPasswordField passwordField1, JPasswordField passwordField2) {

//encrypt file

try{

FileInputStream fis = new FileInputStream(inFile);

FileOutputStream fos = new FileOutputStream(outputFile.getText());

Cipher cipher = Cipher.getInstance("PBEWithMD5AndTripleDES");

//here is where I believe the proble lies something with how I read and then write the byte data

//of a file

cipher.init(Cipher.ENCRYPT_MODE, key);

byte[] buffer = new byte[(int)inFile.length()];

fis.read(buffer);

fis.close();

byte[] encrypt = cipher.doFinal(buffer);

fos.write(encrypt);

fos.close();

} catch(IOException ioe){

ioe.printStackTrace();

} catch(IllegalBlockSizeException ibse) {

ibse.printStackTrace();

} catch(BadPaddingException bpe) {

bpe.printStackTrace();

} catch(InvalidKeyException ike) {

ike.printStackTrace();

} catch(NoSuchAlgorithmException nsae) {

nsae.printStackTrace();

} catch(NoSuchPaddingException nspe) {

nspe.printStackTrace();

}

Toolkit.getDefaultToolkit().beep();

JOptionPane.showMessageDialog(errorFrame, "PROCESS FINISHED", " ", JOptionPane.INFORMATION_MESSAGE);

//reinitialize all important variables

key = null;

outputFile.setText("");

inputFile.setText("");

for(int a = 0; a < Array.getLength(password1); a++) {

password1[a] = 0;

}

for(int a = 0; a < Array.getLength(password2); a++) {

password2[a] = 0;

}

passwordField1.setText("");

passwordField2.setText("");

}

public void Decrypt(SecretKey key, File inFile, JTextField outputFile, char[] password1, char[] password2, JTextField inputFile, JPasswordField passwordField1, JPasswordField passwordField2, JRadioButton encryptButton) {

//decrypt file

try{

FileInputStream fis = new FileInputStream(inFile);

FileOutputStream fos = new FileOutputStream(outputFile.getText());

Cipher cipher = Cipher.getInstance("PBEWithMD5AndTripleDES");

cipher.init(Cipher.DECRYPT_MODE, key);

//here is where I believe the proble lies something with how I read and then write the byte data

//of a file

byte[] buffer = new byte[(int)inFile.length()];

fis.read(buffer);

fis.close();

byte[] decrypt = cipher.doFinal(buffer);

fos.write(decrypt);

fos.close();

} catch(IOException ioe){

ioe.printStackTrace();

} catch(IllegalBlockSizeException ibse) {

ibse.printStackTrace();

} catch(BadPaddingException bpe) {

bpe.printStackTrace();

} catch(InvalidKeyException ike) {

ike.printStackTrace();

} catch(NoSuchAlgorithmException nsae) {

nsae.printStackTrace();

} catch(NoSuchPaddingException nspe) {

nspe.printStackTrace();

}

Toolkit.getDefaultToolkit().beep();

JOptionPane.showMessageDialog(errorFrame, "PROCESS FINISHED", " ", JOptionPane.INFORMATION_MESSAGE);

//reinitialize all important variables

key = null;

outputFile.setText("");

inputFile.setText("");

for(int a = 0; a < Array.getLength(password1); a++) {

password1[a] = 0;

}

for(int a = 0; a < Array.getLength(password2); a++) {

password2[a] = 0;

}

passwordField1.setText("");

passwordField2.setText("");

encryptButton.setSelected(true);

}

public static void main(String[] args) {

//crerate JFrame

JFrame frame = new JCE();

frame.setSize(600,200);

frame.setTitle("Java Cryptography Extensions");

frame.setResizable(false);

frame.show();

frame.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent we) {

System.exit(0);

}

});

}

}

class DecryptFilter extends FileFilter {

//file filter for .encrypt extension

public boolean accept(File inFile) {

if (inFile.isDirectory()) {

return true;

}

String inFileName = inFile.getName();

int i = inFileName.lastIndexOf('.');

if (i > 0 && i < inFileName.length() - 1)

if (inFileName.substring(i + 1).toLowerCase().equals("encrypt"))

return true;

return false;

}

public String getDescription() {

return "Encrypted Files (.encrypt)";

}

}

j-roda at 2007-7-12 > top of java,Security,Cryptography...
# 3

Although it is probably not the source of your problem (unless your files are very large), this code is wrong.byte[] buffer = new byte[(int)inFile.length()];

fis.read(buffer);

fis.close();

because it assumes that fis.read() reads the whole of the file. If you look at the Javadoc you will see that it does not make this guarantee. You should wrap the InputStream in a DataInputStream and then use readFully().

I am not willing to spend time on all that code. You should separate out the encryption code so that it is testable without all the Swing baggage.

It is normal to use CipherInputStream and CipherOutputStream when encrypting files.

sabre150a at 2007-7-12 > top of java,Security,Cryptography...
# 4
Alright so I've done what you said with the DataInputStream. However, I'm not sure how to use the CipherInputStream and CipherOutputStream.Could you possibly go into a little more detail?
j-roda at 2007-7-12 > top of java,Security,Cryptography...
# 5
Read the API! It should be self explanatory.
sabre150a at 2007-7-12 > top of java,Security,Cryptography...
# 6

So far I am able to read the bytes of a file and then write them to a new .encrypt file. I am even able to then read the bytes of the .encrypt file and write them back to the original file type. However, when I try to initialize a new instance of a Cipher theprogram ceases to function. If I try to view the new .encrypt file in note pad nothing comes up. Even if I don't apply the cipher to the bytes of the file and just rewrite the original bytes nothing comes up. So, somewhere I am doing something wrong, I think its with my Cipher initialization. If you have some advice besides read the API's, because I have done that, I would gladly appreciate. If you don't know then just say so.

import javax.crypto.SecretKey;

import javax.crypto.SecretKeyFactory;

import javax.crypto.spec.PBEKeySpec;

import javax.crypto.Cipher;

import javax.crypto.CipherInputStream;

import javax.crypto.CipherOutputStream;

import javax.crypto.BadPaddingException;

import javax.crypto.IllegalBlockSizeException;

import javax.crypto.NoSuchPaddingException;

import javax.crypto.ShortBufferException;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.DataInputStream;

import java.io.DataOutputStream;

import java.io.FileDescriptor;

import java.io.IOException;

import java.io.FileNotFoundException;

import javax.swing.*;

import javax.swing.JFileChooser;

import javax.swing.ButtonGroup;

import javax.swing.filechooser.FileFilter;

import java.awt.*;

import java.awt.event.*;

import java.awt.TextArea;

import java.security.InvalidKeyException;

import java.security.NoSuchAlgorithmException;

import java.security.spec.InvalidKeySpecException;

import java.util.Arrays;

import java.lang.reflect.Array;

import java.nio.ByteBuffer;

class JCE extends JFrame implements ActionListener {

JRadioButton encryptButton;

JRadioButton decryptButton;

JLabel textLabel1;

JTextField inputFile;

JLabel textLabel2;

JTextField outputFile;

JButton chooser2;

JLabel passLabel1;

JPasswordField passwordField1;

JLabel passLabel2;

JPasswordField passwordField2;

JRadioButton delFileButton;

JButton startButton;

JFileChooser fc;

JFrame chooserFrame;

int approve;

File inFile;

String inFileName;

File outFile;

char[] nameChar;

int nameSize;

String outFileName;

char[] password1 = new char[128];

char[] password2 = new char[128];

int size = 0;

String error = "";

int errorCount = 0;

JFrame errorFrame;

SecretKey key;

byte[] salt = new byte[] { (byte) 0x3a, (byte)0x44, (byte)0x7f, (byte)0xf1, (byte)0xa2, (byte)0xe5, (byte)0x87, (byte)0x31 };

int iterations = 1000;

public JCE() {

encryptButton = new JRadioButton("Encrypt ", true);

decryptButton = new JRadioButton("Decrypt");

ButtonGroup cryptGroup = new ButtonGroup();

cryptGroup.add(encryptButton);

cryptGroup.add(decryptButton);

JPanel selectPanel = new JPanel(new FlowLayout());

selectPanel.add(encryptButton);

selectPanel.add(decryptButton);

textLabel1 = new JLabel("Input File");

inputFile = new JTextField(40);

inputFile.setEditable(false);

inputFile.setText(" ");

JButton chooser1 = new JButton("...");

chooser1.addActionListener(this);

chooser1.setActionCommand("chooser1");

JPanel inputPanel = new JPanel(new FlowLayout());

inputPanel.add(textLabel1);

inputPanel.add(inputFile);

inputPanel.add(chooser1);

textLabel2 = new JLabel("Output File");

outputFile = new JTextField(40);

outputFile.setEditable(false);

outputFile.setText(" ");

chooser2 = new JButton("...");

chooser2.addActionListener(this);

chooser2.setActionCommand("chooser2");

JPanel outputPanel = new JPanel(new FlowLayout());

outputPanel.add(textLabel2);

outputPanel.add(outputFile);

outputPanel.add(chooser2);

passLabel1 = new JLabel("Enter password: ");

passwordField1 = new JPasswordField(10);

passwordField1.setEchoChar('*');

passwordField1.setText("");

passLabel2 = new JLabel(" Renter password: ");

passwordField2 = new JPasswordField(10);

passwordField2.setEchoChar('*');

passwordField1.setText("");

JPanel passwordPanel = new JPanel(new FlowLayout());

passwordPanel.add(passLabel1);

passwordPanel.add(passwordField1);

passwordPanel.add(passLabel2);

passwordPanel.add(passwordField2);

delFileButton = new JRadioButton("Delete Input File");

startButton = new JButton("Start Process");

startButton.addActionListener(this);

startButton.setActionCommand("startButton");

JPanel processPanel = new JPanel(new FlowLayout());

processPanel.add(delFileButton);

processPanel.add(startButton);

getContentPane().setLayout(new GridLayout(5,1));

getContentPane().add(selectPanel);

getContentPane().add(inputPanel);

getContentPane().add(outputPanel);

getContentPane().add(passwordPanel);

getContentPane().add(processPanel);

}

public void actionPerformed(ActionEvent ae) {

if(ae.getActionCommand() == "chooser1") {

fc = new JFileChooser(inFile);

fc.setDialogTitle("Input File");

fc.setFileSelectionMode(fc.FILES_ONLY);

if(decryptButton.isSelected()) {

fc.addChoosableFileFilter(new DecryptFilter());

approve = fc.showOpenDialog(chooserFrame);

} else {

fc.showOpenDialog(chooserFrame);

}

if (approve == JFileChooser.APPROVE_OPTION) {

inFile = fc.getSelectedFile();

inFileName = fc.getSelectedFile().getName();

inputFile.setText(fc.getCurrentDirectory().getAbsolutePath() + "\\" + inFileName);

}

}

if(ae.getActionCommand() == "chooser2") {

fc = new JFileChooser(outFile);

fc.setDialogTitle("Output File");

fc.setFileSelectionMode(fc.DIRECTORIES_ONLY);

fc.showOpenDialog(chooserFrame);

outFile = fc.getSelectedFile();

if(decryptButton.isSelected()) {

nameChar = inFileName.toCharArray();

nameSize = inFileName.length();

outFileName = "";

for(int a = 0; a < nameSize - 8; a++) {

outFileName = outFileName + nameChar[a];

}

} else {

outFileName = inFileName + ".encrypt";

}

try {

outputFile.setText(outFile.getCanonicalPath() + "\\" + outFileName);

} catch(IOException ioe) {

ioe.printStackTrace();

}

}

if(ae.getActionCommand() == "startButton") {

if(inputFile.getText().equals(" ")) {

error = error + " You must select an input file";

errorCount++;

}

if(outputFile.getText().equals(" ")) {

if(errorCount >= 1) {

error = error + "\n You must select an output file";

errorCount++;

} else {

error = error + " You must select an output file";

errorCount++;

}

}

password1 = passwordField1.getPassword();

password2 = passwordField2.getPassword();

try {

size = Array.getLength(password1);

} catch(IllegalArgumentException iae) {

iae.printStackTrace();

}

if(size == 0) {

if(errorCount >= 1) {

error = error + "\n You must enter in a password";

errorCount++;

} else {

error = error + " You must enter in a password";

errorCount++;

}

}

if(size > 20) {

if(errorCount >= 1) {

error = error + "\n The password must be 20 characters or less";

errorCount++;

} else {

error = error + " The password must be 20 characters or less";

errorCount++;

}

}

if(!Arrays.equals(password1, password2)) {

if(errorCount >= 1) {

error = error + "\n Enter the same password in both fields";

errorCount++;

} else {

error = error + "Enter the same password in both fields";

errorCount++;

}

}

if(errorCount == 0) {

//generates a SecretKey based on the user inpu password

KeyGenerator(password1, salt, iterations);

//reads the bytes of the file to be en/decrypted

byte[] buffer = new byte[(int)inFile.length()];

buffer = GetBytes(inFile);

if(encryptButton.isSelected()){

//the encrypt calss is called to encrypt the files

Encrypt(inFile, outputFile, buffer, key);

} else {

//the decrypt calss is called to encrypt the files

Decrypt(inFile, outputFile, buffer, key);

}

} else {

Toolkit.getDefaultToolkit().beep();

JOptionPane.showMessageDialog(errorFrame, error, "ERROR", JOptionPane.ERROR_MESSAGE);

passwordField1.setText("");

passwordField2.setText("");

error = "";

errorCount = 0;

}

}

}

public void Encrypt(File inFile, JTextField outputFile, byte[] buffer, SecretKey key) {

//If you try commenting out all of the code dealing with encryption and all the

//code dealing with decryption in public void decrypt() you'll see that the program will

//read the bytes of the file, save them to a .encrypt file. Then when decrypt is selected

//it will read the bytes and write them back to the original file, and that file opens. As

//soon as the en-decryption code is then uncommented one cannot even open the

//.encrypt file in note pad and see anything.

try {

//a new file output sream is created atto the user pecified loaction

FileOutputStream fos = new FileOutputStream(outputFile.getText());

//a new cicher is created then initilaized to encrypt mode

Cipher encrypter = Cipher.getInstance("PBEWithMD5AndTripleDES");

encrypter.init(Cipher.ENCRYPT_MODE, key);

//the byte array created from the bytes the used defined file is converted to a

//ByteBuffer for processing

ByteBuffer buf = ByteBuffer.wrap(buffer);

//a new destination ByteBuffer is created and initialized to hold the encrypted bytes

ByteBuffer encrypt = null;

//the the bytes from buf are encrypted and passed to encrypt

encrypter.doFinal(buf, encrypt);

//set the location in the ByteBuffer back the the first position

encrypt.clear();

//writes the byte[] which backs the ByteBuffer the the file out put stream

fos.write(encrypt.array());

//fos.write(buffer);

fos.close();

} catch(IOException ioe){

ioe.printStackTrace();

} catch(NoSuchAlgorithmException nsae) {

nsae.printStackTrace();

} catch(NoSuchPaddingException nspe) {

nspe.printStackTrace();

} catch(InvalidKeyException ike) {

ike.printStackTrace();

} catch(IllegalBlockSizeException ibse) {

ibse.printStackTrace();

} catch(BadPaddingException bpe) {

bpe.printStackTrace();

} catch(ShortBufferException sbe) {

sbe.printStackTrace();

}

Toolkit.getDefaultToolkit().beep();

JOptionPane.showMessageDialog(errorFrame, "PROCESS FINISHED", " ", JOptionPane.INFORMATION_MESSAGE);

System.out.println("hello");

}

public void Decrypt(File inFile, JTextField outputFile, byte[] buffer, SecretKey key) {

try {

//a new file output sream is created atto the user pecified loaction

FileOutputStream fos = new FileOutputStream(outputFile.getText());

//a new cicher is created then initilaized to decrypt mode

Cipher decrypter = Cipher.getInstance("PBEWithMD5AndTripleDES");

decrypter.init(Cipher.DECRYPT_MODE, key);

//the byte array created from the bytes the used defined file is converted to a

//ByteBuffer for processing

ByteBuffer buf = ByteBuffer.wrap(buffer);

//a new destination ByteBuffer is created and initialized to hold the decrypted bytes

ByteBuffer decrypt = null;

//the the bytes from buf are decrypted and passed to decrypt

decrypter.doFinal(buf, decrypt);

//set the location in the ByteBuffer back the the first position

decrypt.clear();

//writes the byte[] which backs the ByteBuffer the the file out put stream

fos.write(decrypt.array());

//fos.write(buffer);

fos.close();

} catch(IOException ioe){

ioe.printStackTrace();

} catch(NoSuchAlgorithmException nsae) {

nsae.printStackTrace();

} catch(NoSuchPaddingException nspe) {

nspe.printStackTrace();

} catch(InvalidKeyException ike) {

ike.printStackTrace();

} catch(IllegalBlockSizeException ibse) {

ibse.printStackTrace();

} catch(BadPaddingException bpe) {

bpe.printStackTrace();

} catch(ShortBufferException sbe) {

sbe.printStackTrace();

}

Toolkit.getDefaultToolkit().beep();

JOptionPane.showMessageDialog(errorFrame, "PROCESS FINISHED", " ", JOptionPane.INFORMATION_MESSAGE);

}

public byte[] GetBytes(File inFile) {

byte[] temp = new byte[(int)inFile.length()];

try {

FileInputStream fis = new FileInputStream(inFile);

DataInputStream dis = new DataInputStream(fis);

dis.readFully(temp);

dis.close();

fis.close();

} catch(FileNotFoundException fnfe) {

fnfe.printStackTrace();

} catch(IOException ioe){

ioe.printStackTrace();

}

return temp;

}

public void KeyGenerator(char[] password1, byte[] salt, int iterations) {

PBEKeySpec pbeKeySpec;

SecretKeyFactory factory;

try {

pbeKeySpec = new PBEKeySpec(password1, salt, iterations);

factory = SecretKeyFactory.getInstance("PBEWithMD5AndTripleDES");

key = factory.generateSecret(pbeKeySpec);

} catch(NoSuchAlgorithmException nsae) {

nsae.printStackTrace();

} catch(InvalidKeySpecException ikse) {

ikse.printStackTrace();

} catch(IllegalStateException ise) {

ise.printStackTrace();

} catch(ArrayIndexOutOfBoundsException aioobe) {

aioobe.printStackTrace();

} catch(NullPointerException npe) {

npe.printStackTrace();

}

}

public static void main(String[] args) {

JFrame frame = new JCE();

frame.setSize(600,200);

frame.setTitle("Java Cryptography Extensions");

frame.setResizable(false);

frame.show();

frame.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent we) {

System.exit(0);

}

});

}

}

class DecryptFilter extends FileFilter {

public boolean accept(File inFile) {

if (inFile.isDirectory()) {

return true;

}

String inFileName = inFile.getName();

int i = inFileName.lastIndexOf('.');

if (i > 0 && i < inFileName.length() - 1)

if (inFileName.substring(i + 1).toLowerCase().equals("encrypt"))

return true;

return false;

}

public String getDescription() {

return "Encrypted Files (.encrypt)";

}

}

j-roda at 2007-7-12 > top of java,Security,Cryptography...
# 7
> If you have some advice besides> read the API's, because I have done that, I would> gladly appreciate. If you don't know then just say> so.> Ouch! That told me! Obviously you don't take advice so I won't give any!
sabre150a at 2007-7-12 > top of java,Security,Cryptography...