2

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?

5
  • What do you mean by 'everything fell apart'? Commented Dec 4, 2012 at 5:20
  • 1
    You'd better split the file content into chunks and encrypt them separately. Commented Dec 4, 2012 at 5:21
  • I would get empty encrypted files and of course subsequently, incorrect decrypted files. Any suggestions on how to split the file? Commented Dec 4, 2012 at 6:44
  • 1
    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. Commented Dec 4, 2012 at 20:28
  • 1
    Are you just trying to learn, or do you have a real application in mind? Commented Dec 4, 2012 at 22:43

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.