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.
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 secondi++will cause anIndexOutOfBoundsException. You are better off incrementingiby 2 in theforloop and using[i]and[i+1]when accessing the data: