Encrypt long string using RSA (Java)

I am having problems with an RSA application that I have to do in Java.

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

My RSA key is 1024 bits long.

The code part where the problem occurs is as follows:

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); 

If the variables are defined as follows:

  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 fact is that when I encrypt a string less than 117 bytes in size, it works fine (is encrypted and then decrypts well), but when the size is larger, the application throws this exception:

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

Abandoned:

 encodedContent = ciph.doFinal(); 

I do not know where the problem is and what I should do.

Can anyone help me? Thanks.

Sorry for my English.

+4
source share
1 answer

The problem is how you initialize the byte array you are reading. You set the size based on the size of the RSA key, not 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 must initialize the byte array as the maximum size of the data you need to read, which avoids the exception. For instance:

 byte[] bytesToBeEncoded = 1024; 

allows a maximum input line of 1024 characters.

+4
source

Source: https://habr.com/ru/post/1400844/


All Articles