Shuli
Shuli

Reputation: 51

Encrypt long String with RSA (Java)

I'm having problems with an RSA application I have to do in Java.

I have to read a string from a file, encrypt it, and then save the encrypted string in a new file.

My RSA key is 1024 bits long.

The code's part where the problem is, is the following:

            readBytes = in.read(bytesToBeEncoded, 0, bytesToBeEncoded.length);

            while(readBytes != -1){
                encodedContent = ciph.update(bytesToBeEncoded, 0, readBytes);
                out.write(encodedContent);
                bytesToBeEncoded= new byte[(KEY_SIZE/8)-11];
                readBytes = in.read(bytesToBeEncoded, 0, bytesToBeEncoded.length);                  
            }

            encodedContent = ciph.doFinal();
            out.write(encodedContent);

Where the variables are defined like this:

        byte[] bytesToBeEncoded = new byte[(KEY_SIZE/8)-11]; 

        FileInputStream in = new FileInputStream(new File(file1));
        FileOutputStream out = new FileOutputStream(new File(file2));
        int readBytes;

The point is that when I encrypt a less-than-117 bytes string, it works perfectly (encrypt and then decrypt well), but when the size is larger, the application throws this exception:

javax.crypto.IllegalBlockSizeException: Data must not be longer than 117 bytes

Thrown by:

encodedContent = ciph.doFinal();

I don't know where the problem is and what I have to do.

Could anyone help me? Thank you.

Sorry about my english.

Upvotes: 4

Views: 12160

Answers (1)

Steven Mastandrea
Steven Mastandrea

Reputation: 2772

The problem is with how you are initializing the byte array that you are reading your input. You are setting the size based on the size of the RSA key instead of by the expected size of your input stream.

byte[] bytesToBeEncoded = new byte[(KEY_SIZE/8)-11];

The key size is 1024 bits, so 1024/8 -11 = 128 - 11 = 117 bytes. This is the amount of data that you can read from the stream, and should not be related to the size of your RSA key.

You should initialize the byte array to be the maximum size of data that you'll need to read in, which will avoid the Exception. For example:

byte[] bytesToBeEncoded = 1024;

would allow a maximum input string of 1024 characters.

Upvotes: 4

Related Questions