Search code examples
javac#encodingbase64tobase64string

Base64 Encode giving me different value for c# and java


I have been trying to get same encoding in my C# code which I am getting from my Java code.

In Java this is what I am doing:

    JSONObject claimSet = new JSONObject();
    claimSet.put("partnerUrl", "https://test.com/testapply/abc/signup");

    String claimSetJson = claimSet.toString();
    byte[] claimSetJsonBytes = claimSetJson.getBytes(StandardCharsets.UTF_8);
    
    String claimSetBase64 = 
    Base64.getEncoder().encodeToString(claimSetJsonBytes);

and the calimSetBase64 value is eyJwYXJ0bmVyVXJsIjoiaHR0cHM6XC9cL3Rlc3QuY29tXC90ZXN0YXBwbHlcL2FiY1wvc2lnbnVwIn0=

And the equivalent code I have written in c# is:

        var claimSets = new Dictionary<string, object>()
            {
                { "partnerUrl", "https://test.com/testapply/abc/signup" },
            };
        string claimSetsJson = JsonSerializer.Serialize(claimSets);
        byte[] claimSetsjsonBytes = Encoding.UTF8.GetBytes(claimSetsJson);
        var claimSetsBase64 = Convert.ToBase64String(claimSetsjsonBytes);

and now claimSetsBase64 values is eyJwYXJ0bmVyVXJsIjoiaHR0cHM6Ly90ZXN0LmNvbS90ZXN0YXBwbHkvYWJjL3NpZ251cCJ9

now if I decode though both of the encoded strings giving me exactly same value, I am expecting the encoded string also should be same, what I am missing here? I have seen similar question asked in Here but according to the accepted answer I am already using UTF8 on both Java and c#.


Solution

  • If you decode your Base64 strings, you will see different original strings.

    In Java code you try to encode string: {"partnerUrl":"https:\/\/test.com\/testapply\/abc\/signup"}.

    In C#: {"partnerUrl":"https://test.com/testapply/abc/signup"}

    So, string from Java code contains backslash \ as escape character.