Hi Ranchers,
I am trying to use RSA encryption and decrpytion algorithem to encrypt and decrypt a Ms-word
doc file.
When i am providing a ms-word document as input for encryption and decryption, it is giving a "bad padding exception" at the 'doFinal' method in the decrypt method. If i am providing a text file as input to the same program i am getting corrrect text output with some extra spaces before the text content of the text file.
I am getting the RSA public and private keys from the D:\\RSA.pub and D:\\RSA.pri key files stored with a key length of 4096.
I am providing the encrypt and decrypt methid used by me below:
(after removing the try and catch blocks)
private void encrypt () throws Exception {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
String pubKeyFile = "D:\\RSA.pub";
FileInputStream pubKeyStream = new FileInputStream(pubKeyFile);
byte[] pubKeyBytes = new byte[4096];
pubKeyStream.read(pubKeyBytes);
pubKeyStream.close();
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pubKeyBytes);
PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
Cipher cf = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cf.init(Cipher.ENCRYPT_MODE,pubKey);
FileOutputStream fos= new FileOutputStream("C:\\Encrypt.txt");
FileInputStream fis= new FileInputStream("C:\\Input.txt");
int bufSize = 501;
int fisSize = 0;
int fosSize = 0;
byte[] buf = new byte[bufSize];
byte[] out= new byte[cf.getOutputSize(bufSize)];
int n = fis.read(buf,0,bufSize);
String str = buf.toString();
int total=n;
while (n==bufSize) {
fisSize += n;
int j=cf.update(buf,0,bufSize,out,0);
System.out.println("after update j lenght "+j);
fosSize += out.length;
fos.write(out);
n = fis.read(buf,0,bufSize);
System.out.println("n value"+n);
}
byte[] outb = cf.doFinal(buf,0,n);
fos.write(outb);
fis.close();
fos.close();
}
void decrypt()throws Exception
{
String algorithm = "RSA";
int bufSize = 501;
KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
String priKeyFile = "D:\\RSA.pri";
FileInputStream priKeyStream = new FileInputStream(priKeyFile);
byte[] priKeyBytes = new byte[4096];
priKeyStream.read(priKeyBytes);
priKeyStream.close();
PKCS8EncodedKeySpec priKeySpec
= new PKCS8EncodedKeySpec(priKeyBytes);
PrivateKey priKey = keyFactory.generatePrivate(priKeySpec);
FileOutputStream fos= new FileOutputStream("C:\\fpagfile\\Decrypt.txt");
FileInputStream fis= new FileInputStream("C:\\fpagfile\\Encrypt.txt");
Cipher cf = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cf.init(Cipher.DECRYPT_MODE,priKey);
byte[] buf = new byte[bufSize];
byte[] out = new byte[cf.getOutputSize(bufSize)];
int n = fis.read(buf,0,bufSize);
int fisSize = 0;
int fosSize = 0;
while (n==bufSize) {
fisSize += n;
int j=cf.update(buf,0,bufSize,out,0);
fosSize += out.length;
fos.write(out);
n = fis.read(buf,0,bufSize);
}
byte[] outb = new byte[cf.getOutputSize(n)];
outb = cf.doFinal(buf,0,n);
fos.write(outb);
fis.close();
fos.close();
}