BadPaddingException when decrypting JSON data with encrypted values

226 views Asked by At

I have a third party API where I have to send data in JSON in encrypted form. The data in JSON looks like this:

{
    "encryptedKey": "rltP+oNBMx26wSpmvKZ91iL=",
    "encryptedData": "u5o+ON08CNGLwvt8OUmHXFPAzfk3uPILANA="
}

Note: The data in json values is trimmed to just show example.

I am using Java11HttpClient to send this request to the given endpoint. The request with all encrypted values get processed well and I get a desired result that looks like same as request(Response is again in key value paired JSON and values are encrypted).

{
    "encryptedKey": "rltP+oNmvKZ91iL=",
    "encryptedData": "u5ot8OUmHXFPAzfk3uPILANA="
}

I have to decrypt this JSON "encryptedKey" again to get actual content. The decryption is done using "RSA/ECB/PKCS1Padding". So when I pass this String of encryptedKey to decrypt code it gives me BadPaddingException.

javax.crypto.BadPaddingException: Decryption error
        at java.base/sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:378)
        at java.base/sun.security.rsa.RSAPadding.unpad(RSAPadding.java:290)
        at java.base/com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:366)
        at java.base/com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:392)
        at java.base/javax.crypto.Cipher.doFinal(Cipher.java:2202)

I am using this code:

HttpRequest request = HttpRequest.newBuilder().POST(BodyPublishers.ofString(requestPayload))
                .uri(URI.create(url))
                .header("Content-Type", "application/json")
                .header("Accept", "application/json")
                .headers(buildHeaders(headers).toArray(String[]::new)).build();

HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));

This above code works well for request and give me a response in structure same as expected. But the problem seems to be lying in the process of deserialization of response in String.

Option 2: When I pick the encrypted request generated from code, same request if added as a payload in Postman, I get similar response. Now if I decrypt that encrypted key from Postman response, using same codebase it gives me a valid data without padding Exception.

Need suggestion on the ways to send such request and process the response data with some library in Spring or Java11 etc.

I have tried Unirest, Java11HttpClient and OkHttp so far but same results.

Thanks in advance.

0

There are 0 answers