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??
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 Joel about the basics of unicode
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 ?)