RSA decryption error - IllegalBlockSizeException: Data must not be longer than 128 bytes

Your signature string contains 256 characters, however this is hexadecimal and really represents 128 bytes.

Before you verify the signature, you must convert it back to a byte array. This is not achieved through someString.getBytes() but rather via DatatypeConverter.parseHexBinary(someString) (or any other method you prefer from Google).

Also, I would strongly recommend you use the Signature class rather than the Cipher class when signing messages. Currently your code can only handle messages that are smaller than 128 bytes in length (smaller, in fact, due to padding). Instead, you should be hashing the message prior to signing (e.g. using the SHA256withRSA mechanism).


first convert text to Hex and then encrypt it, after encrypt you can convert from hex to string.

public static String toHex(String text)
{
    return String.format("%040x", new BigInteger(1, text.getBytes()));
}

public static byte[] hexToBytes(String hex)
{
    int l = hex.length();
    byte[] data = new byte[l/2];

    for (int i = 0; i < l; i += 2)
    {
        data[i/2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4) + Character.digit(hex.charAt(i+1), 16));
    }

    return data;
}

public static String hexToStringA(String hex)
{
    return new String(hexToBytes(hex));
}

Tags:

Java

Key

Rsa

Jce