King_Fisher
King_Fisher

Reputation: 1203

Encoding in C# and Decoding in Javascript

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.

Upvotes: 2

Views: 5235

Answers (2)

Asim Mittal
Asim Mittal

Reputation: 101

@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

Upvotes: 0

Misaz
Misaz

Reputation: 3985

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

Convert.ToBase64String(Encoding.UTF8.GetBytes("Sample text"))

Upvotes: 4

Related Questions