1

I have a hex string after RSA encryption. When I convert it to a byte[], the RSA decryption gives javax.crypto.BadPaddingException: Blocktype mismatch: 0

I am using this method for conversion (got it on Stack overflow itself)

public static byte[] hexStringToByteArray(String data) {
    int k = 0;
    byte[] results = new byte[data.length() / 2];
    for (int i = 0; i < data.length();) {
        results[k] = (byte) (Character.digit(data.charAt(i++), 16) << 4);
        results[k] += (byte) (Character.digit(data.charAt(i++), 16));
        k++;
    }
    return results;
}

Any suggestions please.

2
  • 1
    Your conversion looks good. I suppose your mistake is somewhere else. (By the way, instead of "got it on Stack Overflow itself", the proper way would be to link to the relevant question/answer.) Commented Oct 14, 2011 at 12:41
  • Can you post the relevant decryption section of the code? Perhaps you're using String.getBytes() somewhere instead of this routine? Commented Oct 14, 2011 at 13:58

1 Answer 1

1

The encryption method requires the input to be a fixed-length; you're going to have to add padding to the required length in order to avoid this exception. This size will depend on the key size.

EDIT: There is also a potential bug in your iteration of data: If its length is not divisible by two then the second i++ will cause an IndexOutOfBoundsException. You are better off incrementing i by 2 in the for loop and using [i] and [i+1] when accessing the data:

for (int i = 0; i + 1 < data.length(); i += 2, k++)
{
    results[k] = (byte) (Character.digit(data.charAt(i), 16) << 4);
    results[k] += (byte) (Character.digit(data.charAt(i + 1), 16));
}
Sign up to request clarification or add additional context in comments.

2 Comments

This is true; however, typically when you instantiate the cipher it chooses a padded transform by default, so there's no need to play with madding manually. But it depends entirely on OPs code...
Your version of the code will give exactly the same IndexOutOfBoundsException. (It is more clear, though.)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.