Convert Hex string to Byte Array for RSA Decryption
-
09-02-2021 - |
Question
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.
Solution
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));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow