2
votes

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?

1
What do you mean by 'everything fell apart'? - xiaofeng.li
You'd better split the file content into chunks and encrypt them separately. - xiaofeng.li
I would get empty encrypted files and of course subsequently, incorrect decrypted files. Any suggestions on how to split the file? - bennyboy
You should encrypt files using a combination of RSA and a symmetric cipher, e.g. AES in CBC mode. For RSA you should be using using OAEP mode padding if possible, although PKCS#1 padding is easier for learning purposes. Both have been described in the publicly available (and pretty readable) PKCS#1 standards from RSA labs. Encrypting a file using just modular exponentiation is learning how not to perform encryption. RSA without padding over large data is bunk. - Maarten Bodewes
Are you just trying to learn, or do you have a real application in mind? - President James K. Polk

1 Answers

2
votes

To solve this , you need to divide the file into chunk, which means for example take every 256 bit as a part and encrypt it ., and so on.