I'm trying to implement RSA encryption and decryption of files in Java using BigInteger.
I have my parameters p, q, e, n, d
I read a file into a byte[]
System.out.println("Opening file: " + infile);
File file = new File(infile);
FileInputStream fis = new FileInputStream(file);
int filelength = (int)file.length();
byte[] filecontent = new byte[filelength];
fis.read(filecontent);
fis.close();
And then make a BigInteger from that byte[]
BigInteger plaintext = new BigInteger(filecontent);
Then encryption is simply
BigInteger ciphertext = plaintext.modPow(e, n);
And I write the ciphertext to a new encrypted file
FileOutputStream fos = new FileOutputStream(outfile);
fos.write(ciphertext.toByteArray());
fos.close();
Decryption is pretty much the same
BigInteger plaintext = ciphertext.modPow(d, n);
This worked perfectly fine when I first tested it with a small text file. It encrypted and decrypted just fine. However as I started to test with some other files like a jpg or zip, everything fell apart. I can't pinpoint the problem debugging but I do notice sometimes the conversion from the file byte[] to BigInteger results in an empty BigInteger object.
Is there something I have to do to the byte[] before encryption?