0

I have a small problem to change the type from byte[] to String and then from String to byte[]. When I use my code, it returns the RSA error "Too much data for rsa block". But when I use the original byte[], it works fine.

This is how it works:

cipherData = cipher.doFinal(cipherData);

I tried to change the data type:

// Byte[] to String
String encrypted = new String(cipherData, "UTF-8");
// RSA Operation
cipherData = cipher.doFinal(encrypted.getBytes());
3
  • 3
    I don't understand. The line String encrypted = new String(cipherData, "UTF-8") is not going to have any effect on the line cipherData = cipher.doFinal(cipherData). Commented Apr 4, 2013 at 16:52
  • You are absolutely right. Changed it. But the error persists. I tried it also with StringBuffer. It does not work as well. Commented Apr 4, 2013 at 16:55
  • 1
    Have you tried specifying character set explicitly: encrypted.getBytes("UTF-8") ? Commented Apr 4, 2013 at 17:07

2 Answers 2

7

This is the problem:

String encrypted = new String(cipherData, "UTF-8");

Your cipherData isn't UTF-8-encoded text. It's arbitrary binary data. So don't try to interpret it as if it were UTF-8 text.

Instead, use either hex or base64 - where base64 is probably the simplest approach. I like the public domain iHarder base64 library:

String encrypted = Base64.encodeBytes(cipherData);
...

cipherData = Base64.decode(encrypted);

EDIT: If you're using Android of course, then use the built-in library :)

Sign up to request clarification or add additional context in comments.

4 Comments

Why would you use iHarder and not the built in support of the Convert class?
If I would like to use such a library, i have to take a look at Android Base64 libraries. Does the library also support decryption?
Thanks. I will check the API for Base64 on Android.
@MrMoDoJoJr: Are you thinking of System.Convert in .NET? This is Java.
0

I works perfect. Here is the Code for Android Base64 library:

String encrypted = Base64.encodeToString(cipherData, Base64.DEFAULT);
cipherData = cipher.doFinal(Base64.decode(encrypted, Base64.DEFAULT));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.