Encrypting large byte array

GVillani82 :

I am using a Cipher for encryption/decryption. It has always been fine, but now I am having problem when dealing with large array bytes.

This is my implementation:

val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.ENCRYPT_MODE, getSecretKey())
val encryptedData = cipher.doFinal(textToEncrypt.toByteArray(StandardCharsets.UTF_8))

As said the problem happens only if the input text is too big. For example, if I pass as input of the doFinal a byte array of length 168036, it will give me back an array of byte, of length 65652.

Is this related with a limitation of the Cipher? If so, is there a way for increasing the input buffer?

enter image description here

Maarten Bodewes :

GVillani82 shows he's in posession of some serious Google-Fu; from the comments:

"Maybe related with this https://issuetracker.google.com/issues/123307358 ?"

Shows that this is likely a bug in runtime 27 and before. Presumably it is fixed in later versions, although the bug report doesn't say which version.


However, maybe it is better to fix the issue using incremental updates. In that case make sure that your buffer is strictly below 64KiB, say 32KiB.

Basically, in Java, there are two ways how you can perform incremental encryption. One is to simply use one of the many Cipher.update methods, and supply it text from a buffer (and note that Cipher.update returns part of the ciphertext, when it becomes available). Then you need to finalize the encryption using a doFinal() method.

The other is to use streaming. For encryption you'd generally use a CipherOutputStream and then copy the plaintext into it, either manually (again using a buffer as you are doing now) or by simply performing the InputStream.transferTo method if you want to write an entire stream. In that case, you might want to directly read bytes from the resource (keeping the original encoding). However, in this case you don't know the what buffer size it will use. If you need streaming then it is relatively easy to create your own using update / doFinal calls.

Using doFinal using an in and output buffer (ByteBuffer) seems to still trigger the error, so that won't work.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=183010&siteId=1