How to decode Base64 to original String?

Decode Base64 in C# (Either string Encrypted or not)

  • I want to decrypt the string in base64 format. I have some data in encrypt format and some in normal text. First I need to check the string is in encrypted or not. If its in encrypted format then decrypt the string. If its in normal text then show the text as it is. Here is my code:- public static string DecryptConnectionString(string connectionString) { string result = ""; bool app = false; app = IsBase64String(connectionString); if (app == true) { Byte[] b = Convert.FromBase64String(connectionString); string decryptedConnectionString = System.Text.ASCIIEncoding.ASCII.GetString(b); result = decryptedConnectionString; } else if (app == false) { result = connectionString; } return result; } public static bool IsBase64String(string s) { s = s.Trim(); return (s.Length % 4 == 0) && Regex.IsMatch(s, @"^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$", RegexOptions.None); } This code not working fine somtimes it works but somtimes not. If I write "test" then it shows like this "??". Can any one help??

  • Answer:

    The problem is the encoding. In the sample above you use ASCII. Normally when using .net Variables u have UTF-8 string. For this I recommend you to read http://www.joelonsoftware.com/articles/Unicode.html You have to always use the encoding with which the string was created. When you convert the byte data to a string and you don't have the correct encoding, chars which can't be mapped, will return unexpected Chars. (Like ?)

Shri at Stack Overflow Visit the source

Was this solution helpful to you?

Other answers

How about trying to Base64 decode and catch an exception if it cannot be decoded? string DecryptConnectionString(string connectionString) { string result; try { Byte[] b = Convert.FromBase64String(connectionString); result = decrypt(b); } catch (FormatException e) { result = connectionString; } return result; }

Francois

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.