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.

Tewr
  • 3,713
  • 1
  • 29
  • 43
King_Fisher
  • 1,171
  • 8
  • 21
  • 51
  • 11
    Just to be clear: base64 encoding/decoding is not encryption - there is no key involved, so anyone can "decrypt" this data. – vcsjones May 25 '17 at 16:18
  • Possible duplicate of [Using Javascript's atob to decode base64 doesn't properly decode utf-8 strings](https://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings) – Samvel Petrosov May 25 '17 at 16:20
  • 1
    It is because you encoded a Unicode string. Try encoding it as an ASCII string instead (or UTF-8). – Robert McKee May 25 '17 at 16:22

2 Answers2

3

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

Convert.ToBase64String(Encoding.UTF8.GetBytes("Sample text"))
Misaz
  • 3,694
  • 2
  • 26
  • 42
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

Asim Mittal
  • 101
  • 4