ArrayIndexOutOfBoundsException: too much data for RSA block

I have some problems with my android app. I am trying to use an RSA encryption / decryption application. That's my problem:

I can clearly encrypt short sentences, but when I try to decrypt this message to the source text, I give an error ("too much data for the RSA block"). And also, if I want to encrypt long sentences, I have the same error. I had a search for this problem, and I found some solution on these sites:

Site 1

Site 2

Site 3

But I don’t understand anything, these decisions are so complicated. How can I fix this problem, can someone give me a simpler solution? Thanks.

EDIT: These are the code blocks that I use for this project.

public String RSAEncrypt(String plain) throws NoSuchAlgorithmException, NoSuchPaddingException,InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidKeySpecException, UnsupportedEncodingException { publicKey = getPublicKey(); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] cipherData = cipher.doFinal(plain.getBytes()); return Base64.encodeToString(cipherData, Base64.DEFAULT); } public String RSADecrypt(byte[] encryptedBytes) throws NoSuchAlgorithmException, NoSuchPaddingException,InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidKeySpecException, UnsupportedEncodingException { privateKey = getPrivateKey(); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] cipherData = cipher.doFinal(encryptedBytes); return Base64.encodeToString(cipherData, Base64.DEFAULT); } 
+4
source share
1 answer

RSA can only encrypt messages that are several bytes shorter than the key pair module. Additional bytes to fill, and the exact number depends on the filling scheme used.

RSA is designed to transmit keys, not encrypt data. If you have a long message, encrypt it using AES using a random key. Then encrypt the AES key using RSA using the public key of the message recipient. You should use the Cipher class wrap() and unwrap() methods.

This is how PGP, S / MIME, TLS (approximately) and any other properly designed RSA encryption scheme work.

+15
source

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


All Articles