2

I have encoded some text in C# like below:

var encodedCredential = Convert.ToBase64String(Encoding.Unicode.GetBytes(JsonConvert.SerializeObject("Sample text")));

The encoded String is :IgBTAGEAbQBwAGwAZQAgAHQAZQB4AHQAIgA=

I want to decode the encoded String in java script.

I have tried the below

decodeURIComponent(atob("IgBTAGEAbQBwAGwAZQAgAHQAZQB4AHQAIgA="))
decodeURIComponent(atob("IgBTAGEAbQBwAGwAZQAgAHQAZQB4AHQAIgA=").replace(' ',''))

enter image description here

The result is something different, There are some spaces in each letter. I cant even replace the spaces.

3
  • 11
    Just to be clear: base64 encoding/decoding is not encryption - there is no key involved, so anyone can "decrypt" this data. Commented May 25, 2017 at 16:18
  • Possible duplicate of Using Javascript's atob to decode base64 doesn't properly decode utf-8 strings Commented May 25, 2017 at 16:20
  • 1
    It is because you encoded a Unicode string. Try encoding it as an ASCII string instead (or UTF-8). Commented May 25, 2017 at 16:22

2 Answers 2

4

You need to use UTF-8 encoding in C#. Export base64 by this command

Convert.ToBase64String(Encoding.UTF8.GetBytes("Sample text"))
Sign up to request clarification or add additional context in comments.

Comments

0

@King_Fisher, you shouldn't be getting additional spaces, also the replace method will replace a single occurrence.

Here's what I did with your code (see attached screenshot)enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.