Ryan S
Ryan S

Reputation: 155

Strange character appearing after doing UTF-8 Base64 Encoding/Decoding Java

I ran some input text through this online converter UTF8

https://www.base64encode.org/

I threw the output into my API, which decodes it and does some further processing.

API Call

@RequestMapping(value = "/highlight", method = RequestMethod.POST)
@ResponseBody
public String highlightTester(@RequestBody String programInput) throws UnsupportedEncodingException {
    byte[] decoded = Base64.getMimeDecoder().decode(programInput);
    String result = new String(decoded, StandardCharsets.UTF_8);

As I log this information, I keep getting a weird character..

Input

{
    "code": "ICAgICAgICAvLyBTaW1wbGUgdXNlIFB5Z21lbnRzIGFzIHlvdSB3b3VsZCBpbiBQeXRob24NCiAgICAgICAgaW50ZXJwcmV0ZXIuZXhlYygiZnJvbSBweWdtZW50cyBpbXBvcnQgaGlnaGxpZ2h0XG4iDQogICAgICAgICAgICAgICAgKyAiZnJvbSBweWdtZW50cy5sZXhlcnMgaW1wb3J0IFB5dGhvbkxleGVyXG4iDQogICAgICAgICAgICAgICAgKyAiZnJvbSBweWdtZW50cy5mb3JtYXR0ZXJzIGltcG9ydCBIdG1sRm9ybWF0dGVyXG4iDQogICAgICAgICAgICAgICAgKyAiZm9ybWF0dGVyID0gSHRtbEZvcm1hdHRlcihzdHlsZT0nbW9ub2thaScsIg0KICAgICAgICAgICAgICAgICsgIiAgICAgICAgICAgICAgICAgICAgICAgICAgICBsaW5lbm9zPUZhbHNlLCINCiAgICAgICAgICAgICAgICArICIgICAgICAgICAgICAgICAgICAgICAgICAgICAgbm9jbGFzc2VzPVRydWUsIg0KICAgICAgICAgICAgICAgICsgIiAgICAgICAgICAgICAgICAgICAgICAgICAgICBjc3NjbGFzcz0nJywiDQogICAgICAgICAgICAgICAgKyAiICAgICAgICAgICAgICAgICAgICAgICAgICAgIHByZXN0eWxlcz0nbWFyZ2luOiAwJykiDQogICAgICAgICAgICAgICAgKyAiXG5yZXN1bHQgPSBoaWdobGlnaHQoY29kZSwgUHl0aG9uTGV4ZXIoKSwgZm9ybWF0dGVyKSIpOw0KDQogICAgICAgIC8vIEdldCB0aGUgcmVzdWx0IHRoYXQgaGFzIGJlZW4gc2V0IGluIGEgdmFyaWFibGUNCiAgICAgICAgbG9nLmluZm8oaW50ZXJwcmV0ZXIuZ2V0KCJyZXN1bHQiLCBTdHJpbmcuY2xhc3MpKTsNCiAgICAgICAgcmV0dXJuIGludGVycHJldGVyLmdldCgicmVzdWx0IiwgU3RyaW5nLmNsYXNzKTs="
}

Strange Output

....#1e0010">�</span><span style="color: #f92672">^</span>....

Now, this happens with literally every single type of input I pass in, even if I use a different encoder. Why is this happening?

More Ouput

r�^wefwefwef

I'm using Java Spring Boot to run my API, so wondering if me passing this through Postman is adding some additional flavor to my call.

Upvotes: 1

Views: 3823

Answers (1)

Robby Cornelissen
Robby Cornelissen

Reputation: 97271

You're passing the entire request body to the base64 decoder. Since the request body not only contains the base64-encoded string but also JSON markup, decoding will either fail or result in unexpected output.

To fix, either:

  • make sure that you only have base64 content in your request body; or
  • parse the JSON in your request body and extract the base64 string that you want to decode; or
  • create a bean corresponding to your JSON structure and let Spring map the request body to that bean automatically.

Upvotes: 1

Related Questions