Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayIndexOutOfBoundsException : too much data for RSA block

Tags:

java

android

rsa

I have some problem with my android application. I am trying to an app related with RSA encryption/decryption.this is my problem:

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

Site 1

Site 2

Site 3

But i dont understand anything, these solutions are so complicated.How can i fixed this problem, Can anyone give me a more simple solution? Thank you.

EDİT: 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);
}
like image 558
Bahadır Yılmaz Avatar asked Jul 23 '13 13:07

Bahadır Yılmaz


1 Answers

RSA can only encrypt messages that are several bytes shorter than the modulus of the key pair. The extra bytes are for padding, and the exact number depends on the padding scheme you are using.

RSA is for key transport, not data encryption. If you have a long message, encrypt it with AES, using a random key. Then encrypt the AES key with RSA, using the public key of the message recipient. You should be using the Cipher class's wrap() and unwrap() methods.

This is how PGP, S/MIME, TLS (roughly), and any other correctly designed RSA encryption schemes work.

like image 139
erickson Avatar answered Nov 15 '22 21:11

erickson