Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encoding strings to and from base-64

Tags:

string

c#

base64

I'm trying to encode some strings back and forth from base-64 string and I'm having truble to get the right result.

string text = base64string.... //Here I have a base-64 string.
byte[] encodedByte = System.Text.ASCIIEncoding.ASCII.GetBytes(text);
string base64Encoded = Convert.ToBase64String(encodedByte);

if (text == base64Encoded) //If the new encoded string is equal to its original value
    return base64Encoded;

I have tried my ways to do this and I don't seem to get the right result. I have tried both with System.Text.Encoding.Unicode and System.Text.Encoding.UTF8

What could be the problem? Does anyone have a proper solution?

like image 938
Erik Larsson Avatar asked Mar 26 '12 19:03

Erik Larsson


1 Answers

string text = base64string.... //Here I have a base-64 string.
byte[] encodedByte = System.Text.ASCIIEncoding.ASCII.GetBytes(text);
string base64Encoded = Convert.ToBase64String(encodedByte);

You are double encoding the string. You begin with a base64 string, get the bytes, and then encode it again. If you want to compare you will need to begin with the original string.

like image 108
Ed S. Avatar answered Sep 28 '22 07:09

Ed S.