Removing BadPddingException
Hi all,
Please help me with this problem which is troubling me from last 3-4 days.
There are two files
1)Receiver.java
2)Sender.java
In Receiver.java,I am generating a public and private key using RSA and storing them in two separate files public.dat and private.dat.
Here is the code segment for this.....
import java.io.*;
import java.security.*;
import sun.misc.*;
import javax.crypto.*;
public class Receiver {
public static void main (String[] args) throws Exception {
// generate an RSA key
ObjectOutputStream f=new ObjectOutputStream(new FileOutputStream("public.dat"));
ObjectOutputStream f1=new ObjectOutputStream(new FileOutputStream("private.dat"));
System.out.println( "\nStart generating RSA key" );
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(1024);
KeyPair keypair = keyGen.generateKeyPair();
f.writeObject(keypair.getPublic());
f.close();
f1.writeObject(keypair.getPrivate());
f1.close();
System.out.println( "Finish generating RSA key" );
Now the public and private keys are in public.dat and private.dat respectively. Now im loading an encypted file called encrypt.txt which was encrypted using RSA public key in Sender.java.
While trying to decrypt it using private.dat, a BadPaddingException is coming.....
Here is the code
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
ObjectInputStream in1 = new ObjectInputStream(new FileInputStream("encrypt.txt"));
ObjectInputStream in2 = new ObjectInputStream(new FileInputStream("private.dat"));
Key key = (Key)in2.readObject();
cipher.init(Cipher.DECRYPT_MODE,key);
byte newMsg1[]=(byte[])in1.readObject();
byte[] newPlainText = cipher.doFinal(newMsg1);
System.out.println( "Finish decryption: " );
System.out.println(new String(newPlainText,"UTF8"));
in1.close();
in2.close();
Also look at Sender.java
import java.util.Scanner;
import java.security.*;
import java.io.*;
import javax.crypto.*;
import sun.misc.*;
public class Sender {
public static void main(String[] args)throws Exception {
Scanner scan=new Scanner(System.in);
System.out.println("Enter any message");
String msg=scan.next();
OutputStream f=new FileOutputStream("plainText.txt");
byte b[]=msg.getBytes();
f.write(b);
f.close();
// encrypt the plaintext using the public key from the file "public.dat"
ObjectInputStream in=new ObjectInputStream(new FileInputStream("public.dat"));
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
Key key=(Key)in.readObject();
System.out.println( "\nStart encryption" );
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] cipherText = cipher.doFinal(b);
ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream("encrypt.txt"));
//produce the encypted msg.....
out.writeObject(cipherText);
in.close();
out.close();
System.out.println( "\nFinish encryption: \n"+new String(cipherText,"UTF8") );
}
}
What is the possible solution for this problem?

