hello everyone,
Given below is my code for DES encryption using JCE. The process of
encryption works fine. But decryption gives me bad padding exception. I'm
very new to JCE and I dont know how to correct it. Someone please help me.
Thanks in advance,
Vijai Mohan
import java.io.*;
import java.security.spec.*;
import javax.crypto.*;
import javax.crypto.spec.*;
class myjce
{
public static void main(String[] a)
{
String mode = a[0];
System.out.println(mode);
String input = a[1];
String output = a[2];
try
{
SecretKey ky = getkey();
myCipher(mode, ky, input, output);
} catch (Exception e)
{
System.out.println("Exception: "+e);
return;
}
}
private static SecretKey getkey() throws Exception
{
KeyGenerator kg = KeyGenerator.getInstance("DES");
kg.init(56);
SecretKey key = kg.generateKey();
return key;
}
private static void myCipher(String mode,SecretKey ky, String input,
String output) throws Exception
{
Cipher c = Cipher.getInstance("DES");
if (mode.equalsIgnoreCase("encrypt"))
c.init(Cipher.ENCRYPT_MODE,ky);
else if (mode.equalsIgnoreCase("decrypt"))
c.init(Cipher.DECRYPT_MODE,ky);
FileInputStream fis = new FileInputStream(input);
FileOutputStream fos = new FileOutputStream(output);
int bufSize = fis.available();
byte[] buf = new byte[bufSize];
int n = fis.read(buf,0,bufSize);
int fisSize = 0;
int fosSize = 0;
while (n!=-1)
{
fisSize += n;
byte[] out = c.update(buf,0,n);
fosSize += out.length;
fos.write(out);
n = fis.read(buf,0,bufSize);
}
byte[] out = c.doFinal();
fosSize += out.length;
fos.write(out);
fis.close();
fos.close();
System.out.println();
System.out.println("Input Size = "+fisSize);
System.out.println("Output Size = "+fosSize);
}
}
Chris - 16 Mar 2005 07:35 GMT
[snip]
> private static SecretKey getkey() throws Exception
> {
[quoted text clipped - 14 lines]
> else if (mode.equalsIgnoreCase("decrypt"))
> c.init(Cipher.DECRYPT_MODE,ky);
[snip]
Hello,
The most basic problem here is that you're encrypting and decrypting
with different keys. When you store data encrypted, you must save the
encryption key somewhere and use the same key to decrypt later. The
KeyGenerator gives you a new key every time you run the program. I
would suggest starting off with a program which encrypts some data
then immediately decrypts it, using only one SecretKey object. Once
this works, you can try saving the key to a file so you can actually
save the encrypted data and decrypt later.
Chris