i am using Encoding and decoding :
For Encoding:
private string EncodeServerName(string ServerName)
{
byte[] NameEncodein = new byte[ServerName.Length];
NameEncodein = System.Text.Encoding.UTF8.GetBytes(ServerName);
string EcodedName = Convert.ToBase64String(NameEncodein);
return EcodedName;
}
and Decoding:
public string DecoAndGetServerName(string Servername)
{
System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
System.Text.Decoder strDecoder = encoder.GetDecoder();
byte[] to_DecodeByte = Convert.FromBase64String(Servername);
int charCount = strDecoder.GetCharCount(to_DecodeByte, 0, to_DecodeByte.Length);
char[] decoded_char = new char[charCount];
strDecoder.GetChars(to_DecodeByte, 0, to_DecodeByte.Length, decoded_char,0);
string Name = new string(decoded_char);
return Name;
}
I am sending ServerName:DEV-SQL1\SQL2008
It is encoded:REVWLVNRTDFcU1FMMjAwOA==
Again i want to decode but getting Exception:in line:
byte[] to_DecodeByte = Convert.FromBase64String(Servername);
Exception IS:
`The input is not a valid Base-64 string as it contains a non-base 64 character,
more than two padding characters, or a non-white space character among the padding characters.`
How to solve this issue.
Please Help Me
Your code seems way too complex :-), here is one that works:
public static string EncodeServerName(string serverName)
{
return Convert.ToBase64String(Encoding.UTF8.GetBytes(serverName));
}
public static string DecodeServerName(string encodedServername)
{
return Encoding.UTF8.GetString(Convert.FromBase64String(encodedServername));
}
the same code works for me, which you written in DecoAndGetServerName().
the thing is, you need to pass ENCODED STRING to your DecoAndGetServerName() function,
which might be encoded like :
string Servername=Convert.ToBase64String(Encoding.UTF8.GetBytes("serverName"));
That's why you got that Error The input is not a valid Base-64 string as it contains a non-base 64 character,....
Related
Here is my problem, Im trying to Encode the response of my webservice with the following Code.
public static string ConvertToUTF8(string Cadena)
{
string mensajeex = Cadena;
Encoding utf8 = Encoding.UTF8;
Encoding unicode = Encoding.Unicode;
// Convert the string into a byte array.
byte[] unicodeBytes = unicode.GetBytes(mensajeex);
// Perform the conversion from one encoding to the other.
byte[] asciiBytes = Encoding.Convert(unicode, utf8, unicodeBytes);
// Convert the new byte[] into a char[] and then into a string.
char[] asciiChars = new char[utf8.GetCharCount(asciiBytes, 0, asciiBytes.Length)];
utf8.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0);
string Utf8string = new string(asciiChars);
// Display the strings created before and after the conversion.
Console.WriteLine("Original string: {0}", mensajeex);
Console.WriteLine("Ascii converted string: {0}", Utf8string);
return Utf8string;
}
And actually it works! But when I try to Encode a string and then pass through an exception as a Message property like this
throw new Exception(XMLHelper.ConvertToUTF8(Message));
It give me the response wrong like:
El valor 'R' no es válido segú
Any ideas? Thanks
I'm familiar with python and very new to C#.
I'm trying to convert a python code to C# code, which is not going well
Here is part of my python code:
def make_signature(uri, access_key):
secret_key = "****" # secret key (from portal or sub account)
secret_key = bytes(secret_key, 'UTF-8')
method = "POST"
message = method + " " + uri + "\n" + timestamp + "\n" + access_key
message = bytes(message, 'UTF-8')
signingKey = base64.b64encode(hmac.new(secret_key, message, digestmod=hashlib.sha256).digest())
and I tried to convert it by this C# code:
using (HMACSHA256 sha = new HMACSHA256(hmac_key))
{
var bytes = Encoding.UTF8.GetBytes(messageRaw);
string base64 = Convert.ToBase64String(bytes);
var message = Encoding.UTF8.GetBytes(base64);
// encode
var hash = sha.ComputeHash(message);
// base64 convert
return Convert.ToBase64String(hash);
}
I found out that these two code make different outputs despite of their same inputs.
Could anyone let me know how to convert it correctly?
To convert to Base64, you can use this:
public static string Base64Encode(string plainText)
{
var plainTextBytes = System.Text.Encoding.ASCII.GetBytes(plainText);
return System.Convert.ToBase64String(plainTextBytes);
}
And to convert back!
public static string Base64Decode(string base64EncodedData)
{
var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
return System.Text.Encoding.ASCII.GetString(base64EncodedBytes);
}
I am using RichTextBox for this example:
richTextBox1.Text = Base64Encode(richTextBox1.Text);, Convert TO Base64
richTextBox1.Text = Base64Decode(richTextBox1.Text);, Convert FROM Base64
You can change the ASCII Encoding to UTF-8, or any Encoding that Visual Studio offers :)
You don't necessarily HAVE to use a public static string, you can just take the code out and put it into buttons or MenuStrip Items
Now, prior to your question, here:
public static string Base64Encode(string plainText)
{
var plainTextBytes = System.Text.Encoding.ASCII.GetBytes(plainText);
var 1base64 = System.Convert.ToBase64String(plainTextBytes);
var 2base64 = System.Text.Encoding.ASCII.GetBytes(1base64);
return System.Convert.ToBase64String(2base64); //This is the double encryption :)
}
I hope this helps you :)
I have this C# code:
public static string Encript(string strData)
{
string hashValue = HashData(strData);
string hexHashData = ConvertStringToHex(hashValue);
return hexHashData;
}
public static string HashData(string textToBeEncripted)
{
//Convert the string to a byte array
Byte[] byteDataToHash = System.Text.Encoding.Unicode.GetBytes(textToBeEncripted);
//Compute the MD5 hash algorithm
Byte[] byteHashValue = new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(byteDataToHash);
return System.Text.Encoding.Unicode.GetString(byteHashValue);
}
public static string ConvertStringToHex(string asciiString)
{
string hex = "";
foreach (char c in asciiString)
{
int tmp = c;
hex += String.Format("{0:x2}", (uint) System.Convert.ToUInt32(tmp.ToString()));
}
return hex;
}
Here you can see an online version.As you can see for the string "test" I get the output "5c82e9e41c7599f790ef1d774b7e6bf"
And this is what I tried on php side
$a = "test";
$a = mb_convert_encoding($a, "UTF-16LE");
$a = md5($a);
echo $a;
But the value of the php code is "c8059e2ec7419f590e79d7f1b774bfe6".Why is not working?
Edit:Looks like the C# code is incorrect and needs to be replaced
The correct MD5 hash for 'test' is '098f6bcd4621d373cade4e832627b4f6' in PHP.
I tested it with this code in C#
public static string CreateMD5(string input)
{
// Use input string to calculate MD5 hash
using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
{
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
byte[] hashBytes = md5.ComputeHash(inputBytes);
// Convert the byte array to hexadecimal string
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hashBytes.Length; i++)
{
sb.Append(hashBytes[i].ToString("X2"));
}
return sb.ToString();
}
}
It will generate the same hash as PHP will, without the 'convert encoding' method you are using.
I believe converting the encoding is what is giving you a different answer, try it without
$a = mb_convert_encoding($a, "UTF-16LE");
The problem is that you are converting the result incorrectly in your C# code. If you put a breakpoint in the code after you call ComputeHash, and examine the value of byteHashValue, you'll see that it's c8059e2e....
Or, just add this code to your ComputeHash method:
Console.WriteLine(BitConverter.ToString(byteHashValue));
I would suggest rewriting your code to be:
public static string Encript(string strData)
{
string hashValue = HashData(strData);
return hashValue;
}
public static string HashData(string textToBeEncripted)
{
//Convert the string to a byte array
Byte[] byteDataToHash = System.Text.Encoding.Unicode.GetBytes(textToBeEncripted);
//Compute the MD5 hash algorithm
Byte[] byteHashValue = new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(byteDataToHash);
return BitConverter.ToString(byteHashValue).Replace("-", "");
}
Oh, and a side note: the word is "Encrypt," not "Encript."
The problem in your case is not the encoding, but your conversion to string on the C# side. As long as you use the same encoding everywhere, it should work as expected. But note, that most of the online hashers use ASCII encoding, whereas you use System.Text.Encoding.Unicode which is UTF-16, thus the results will differ from the online encoders.
The code below will give the same result as your PHP snippet (ie c8059e2ec7419f590e79d7f1b774bfe6)
public static void Main(string[] args)
{
string a = "test";
string en = HashData(a);
Console.WriteLine(en);
}
public static string HashData(string textToBeEncripted)
{
Byte[] byteDataToHash = System.Text.Encoding.Unicode.GetBytes(textToBeEncripted);
Byte[] byteHashValue = new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(byteDataToHash);
System.Text.StringBuilder s = new System.Text.StringBuilder();
foreach (var b in byteHashValue)
s.Append(b.ToString("x2"));
return s.ToString();
}
If you use System.Text.Encoding.ASCII instead, you will get 098f6bcd4621d373cade4e832627b4f6 as suggested in other answers. But then you'll have to use ASCII encoding in your PHP code as well.
This is because with UTF16 every character is represented by two bytes, and not only by one. Thus the byteDataToHash will have twice the size ([116, 0, 101, 0, 115, 0, 116, 0] vs [116, 101, 115, 116] in your case). And a different bytevector of course leads to a different hashvalue. But as said above, as long as all included components use the same encoding, it does not really matter which one you use.
I'm struggling with the usual conversion issue, but unfortunately I haven't been able to find anything for my specific problem.
My app is receiving a System.Net.Http.HttpResponseMessage, from a php server, UTF8 encoded, containing some characters like \u00c3\u00a0 (à) and I'm not able to convert them.
string message = await result.Content.ReadAsStringAsync();
byte[] messageBytes = Encoding.UTF8.GetBytes(message);
string newmessage = Encoding.UTF8.GetString(messageBytes, 0, messageBytes.Length);
This is just one of my try, but nothing happens, the resultring string still has the \u00c3\u00a0 characters.
I have also read some answers like How to convert a UTF-8 string into Unicode? but this solution doesn't work for me. This is the solution code:
public static string DecodeFromUtf8(this string utf8String)
{
// copy the string as UTF-8 bytes.
byte[] utf8Bytes = new byte[utf8String.Length];
for (int i=0;i<utf8String.Length;++i) {
//Debug.Assert( 0 <= utf8String[i] && utf8String[i] <= 255, "the char must be in byte's range");
utf8Bytes[i] = (byte)utf8String[i];
}
return Encoding.UTF8.GetString(utf8Bytes,0,utf8Bytes.Length);
}
DecodeFromUtf8("d\u00C3\u00A9j\u00C3\u00A0"); // déjà
I have noticed that when I try the above solution with a simple string like
string str = "Comunit\u00c3\u00a0"
the DecodeFromUtf8 method works perfectly, the problem is when I use my response message.
Any advice would be very appreciated
I've solved this problem by myself. I've discovered that the server response was a ISO string of a utf-8 json, so I had to remove the json escape characters and then convert the iso into a utf8
So I had to do the following:
private async Task<string> ResponseMessageAsync(HttpResponseMessage result)
{
string message = await result.Content.ReadAsStringAsync();
string parsedString = Regex.Unescape(message);
byte[] isoBites = Encoding.GetEncoding("ISO-8859-1").GetBytes(parsedString);
return Encoding.UTF8.GetString(isoBites, 0, isoBites.Length);
}
for me works change from:
string message = await result.Content.ReadAsStringAsync();
byte[] messageBytes = Encoding.UTF8.GetBytes(message);
string newmessage = Encoding.UTF8.GetString(messageBytes, 0, messageBytes.Length);
to:
byte[] bytes = await result.Content.ReadAsByteArrayAsync();
Encoding utf8 = Encoding.UTF8;
string newmessage = utf8.GetString(bytes);
So given this input string:
=?ISO-8859-1?Q?TEST=2C_This_Is_A_Test_of_Some_Encoding=AE?=
And this function:
private string DecodeSubject(string input)
{
StringBuilder sb = new StringBuilder();
MatchCollection matches = Regex.Matches(inputText.Text, #"=\?(?<encoding>[\S]+)\?.\?(?<data>[\S]+[=]*)\?=");
foreach (Match m in matches)
{
string encoding = m.Groups["encoding"].Value;
string data = m.Groups["data"].Value;
Encoding enc = Encoding.GetEncoding(encoding.ToLower());
if (enc == Encoding.UTF8)
{
byte[] d = Convert.FromBase64String(data);
sb.Append(Encoding.ASCII.GetString(d));
}
else
{
byte[] bytes = Encoding.Default.GetBytes(data);
string decoded = enc.GetString(bytes);
sb.Append(decoded);
}
}
return sb.ToString();
}
The result is the same as the data extracted from the input string. What am i doing wrong that this text is not getting decoded properly?
UPDATE
So i have this code for decoding quote-printable:
public string DecodeQuotedPrintable(string encoded)
{
byte[] buffer = new byte[1];
return Regex.Replace(encoded, "=(\r\n?|\n)|=([A-F0-9]{2})", delegate(Match m)
{
if (byte.TryParse(m.Groups[2].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out buffer[0]))
{
return Encoding.ASCII.GetString(buffer);
}
else
{
return string.Empty;
}
});
}
And that just leaves the underscores. Do i manually convert those to spaces (Replace("_"," ")), or is there something else i need to do to handle that?
Looks like you don't fully understand format of input line. Check it here: http://www.ietf.org/rfc/rfc2047.txt
format is: encoded-word = "=?" charset "?" encoding "?" encoded-text "?="
so you have to
Extranct charset(encoding in terms of .net). Not just UTF8 or Default (Utf16)
Extract encoding: either B for base64 Q for quoted-printable (your case!)
Then perform decoding to bytes then to string
The function's not even trying to decode the quoted-printable encoded stuff (the hex codes and underscores). You need to add that.
It's handling the encoding wrong (UTF-8 gets decoded with Encoding.ASCII for some bizarre reason)