Android Java error "too much data for RSA block"

A has an error in my Android project (RSA encryption / decryption). Encryption goes fine, but when I try to decrypt the encrypted text, there is an error: "too much data for the RSA block".

How to solve this problem?

code:

public String Decrypt(String text) throws Exception { try{ Log.i("Crypto.java:Decrypt", text); RSAPrivateKey privateKey = (RSAPrivateKey)kp.getPrivate(); Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding"); cipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] cipherData = cipher.doFinal(text.getBytes());// <----ERROR: too much data for RSA block byte[] decryptedBytes = cipher.doFinal(cipherData); String decrypted = new String(decryptedBytes); Log.i("Decrypted", decrypted); return decrypted; }catch(Exception e){ System.out.println(e.getMessage()); } return null; } 
+1
source share
1 answer

Your problem is that you need to encode / decode encrypted text (just text in your code) if you want to wrap it using a text representation ( String in your case).

Try to find base 64 encoding on this site, there should be a lot of information about it. Encode after encryption and decoding before decryption. You must also specify a specific character encoding for your plaintext.

Finally, you probably should encrypt with a symmetric cipher and encrypt a symmetric key with RSA. Otherwise, there may be no space in the RSA calculation, because the public key cannot encrypt data that exceeds its module (key size).

+3
source

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


All Articles