This question already has an answer here:
A have an error in my Android project (RSA encryption/decryption). The encryption passes OK, but when I trying to decrypt encrypted text, yhere are an error: "too much data for 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;
}
Your issue is that you need to encode/decode the ciphertext (just
text
in your code) if you want to transport it using a textual representation (String
in your case).Try and look up base 64 encoding on this site, there should be a lot of information about it. Encode after encryption and decode before decryption. You should also specify a specific character encoding for your plaintext.
Finally, you should probably encrypt with a symmetric cipher, and encrypt the symmetric key using RSA. Otherwise you may run out of space within the RSA calculation, because a public key cannot encrypt data larger than its modulus (key size).