Encrypting but not decrypting!
843810Feb 14 2004 — edited Feb 18 2004Hi,
I have been working on the following DES program. I am using my own secret-key, instead of using the generateKey(). Its encrypting well, but its not decrypting. Its giving nullpointer exception, not going into doFinal() in decrypt mode. I am new to this topic. I am pasting the code below. Can u help??
public static String encrypt( String source ){
try{
// Get our secret key
Key key = getKey();
// Initialize the cipher for encryption
desCipher.init(Cipher.ENCRYPT_MODE, key);
// Encode the string into bytes using utf-8
byte[] utf8 = source.getBytes("UTF8");
// Encrypt
byte[] enc = desCipher.doFinal(utf8);
// Encode bytes to base64 to get a string
return new sun.misc.BASE64Encoder().encode(enc);
}
catch (javax.crypto.BadPaddingException e) {
}
catch (IllegalBlockSizeException e) {
}// catch (UnsupportedEncodingException e) {
catch (java.io.IOException e) {
}
catch (Exception e){
}
return null;
}
public static String decrypt( String source ){
try{
// Get our secret key
Key key = getKey();
System.out.println ("a");
// Create the cipher
//desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
System.out.println ("b");
// Initialize the same cipher for decryption
desCipher.init(Cipher.DECRYPT_MODE,key);
// Decode base64 to get
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(source);
// Decrypt
byte[] utf8 = desCipher.doFinal(dec);
// Decode using utf-8
return new String(utf8, "UTF8")
} catch (javax.crypto.BadPaddingException e) {
e.getMessage(
} catch (IllegalBlockSizeException e) {
e.getMessage();
}
catch (IOException e) {
e.getMessage();
}
catch (Exception e) {
e.getMessage();
}
return null;
}
private static Key getKey(){
try{
byte[] bytes = getBytes( secret_key );
//byte[] bytes = getBytes(generateKey());
DESKeySpec pass = new DESKeySpec( bytes );
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
SecretKey s = skf.generateSecret(pass);
return s;
}
I am reading the secretkey from a textfile. Then calling encrypt method, saving the ciphertext in a file, reading that cipherfile n calling the decrypt method and saving the plaintext. But plaintext is not getting generated cuz of the failure of decryption. I tried a lot to solve, but finally have no idea as to why its giving nullpointer exception and not going thru doFinal() in decrypt. Please help!!