How to detect an invalid pass phrase?

I used the sample code from Java Developers Almanac to encrypt a file (http://javaalmanac.com/egs/javax.crypto/DesFile.html). I changed a bit of the code so that user can enter a pass phrase.

When it comes to decrypting the file, I found that the file gets "decrypted" and becomes corrupt even when a wrong pass phrase is supplied.

How can I detect if the pass phrase is correct before the program goes on to decrypt the file?

My code (for the constructor) is as below:

public EncryptDecrypt(String passphrase){

byte[] iv =newbyte[]{(byte)0x8E, 0x12, 0x39, (byte)0x9C, 0x07, 0x72, 0x6F, 0x5A};

AlgorithmParameterSpec paramSpec =new IvParameterSpec(iv);

try{

KeySpec keyspec =new DESKeySpec(passphrase.getBytes());

SecretKey key = SecretKeyFactory.getInstance("DES").generateSecret(keyspec);

ecipher = Cipher.getInstance("DES/CBC/PKCS5Padding");

dcipher = Cipher.getInstance("DES/CBC/PKCS5Padding");

ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);

dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);

}catch(java.security.InvalidAlgorithmParameterException e){

}catch(javax.crypto.NoSuchPaddingException e){

}catch(java.security.NoSuchAlgorithmException e){

}catch(java.security.InvalidKeyException e){

}catch(java.security.spec.InvalidKeySpecException e){

}

}// constructor

[2417 byte] By [correroa] at [2007-10-2 9:29:49]
# 1

Use one of the PBE encryption algorithms to encrypt data based on a password. It is simpler and more secure than your example. You can append a PBE-based MAC to the encrypted message to verify the correctness of your decryption. See http://java.sun.com/j2se/1.5.0/docs/guide/security/jce/JCERefGuide.html for more details.

ghstarka at 2007-7-16 23:36:19 > top of Java-index,Security,Cryptography...