Convert a String to binary sequence in C# [duplicate] - c#

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How do you convert a string to ascii to binary in C#?
How to convert string such as "Hello" to Binary sequence as 1011010 ?

Try this:
string str = "Hello";
byte []arr = System.Text.Encoding.ASCII.GetBytes(str);

string result = string.Empty;
foreach(char ch in yourString)
{
result += Convert.ToString((int)ch,2);
}
this will translate "Hello" to 10010001100101110110011011001101111

string testString = "Hello";
UTF8Encoding encoding = new UTF8Encoding();
byte[] buf = encoding.GetBytes(testString);
StringBuilder binaryStringBuilder = new StringBuilder();
foreach (byte b in buf)
{
binaryStringBuilder.Append(Convert.ToString(b, 2));
}
Console.WriteLine(binaryStringBuilder.ToString());

Use the BitConverter to get the bytes of the string and then format these bytes to their binary representation:
byte[] bytes = System.Text.Encoding.Default.GetBytes( "Hello" );
StringBuilder sb = new StringBuilder();
foreach ( byte b in bytes )
{
sb.AppendFormat( "{0:B}", b );
}
string binary = sb.ToString();

Related

C# code php equivalent md5 hash

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.

Ruby sha and hash to c#

Im trying to translate this to c#
f1 = Digest::SHA1.hexdigest(#password)
f2 = nonce + ":" + f1
Digest::MD5.hexdigest(f2)
My Code
private static string GetSHA1HashData(string data)
{
//create new instance of md5
SHA1 sha1 = SHA1.Create();
//convert the input text to array of bytes
byte[] hashData = sha1.ComputeHash(Encoding.Default.GetBytes(data));
//create new instance of StringBuilder to save hashed data
StringBuilder returnValue = new StringBuilder();
//loop for each byte and add it to StringBuilder
for (int i = 0; i < hashData.Length; i++)
{
returnValue.Append(hashData[i].ToString());
}
// return hexadecimal string
return returnValue.ToString();
}
public static string CreateMD5Hash(string input)
{
// Use input string to calculate MD5 hash
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"));
// To force the hex string to lower-case letters instead of
// upper-case, use he following line instead:
// sb.Append(hashBytes[i].ToString("x2"));
}
return sb.ToString();
}
Call
var nonce = "1386755695841";
var password = "edc123";
var sha = GetSHA1HashData(password);
var md5 = CreateMD5Hash(nonce + ":" + sha);
But i cant get it right, any ideas
The problem is that .NET uses UTF-16 by default whilst Ruby will use something else (normally UTF-8, but it may also respect encoding that has been set by database or web source).
I think you just need to alter one line:
//convert the input text to array of bytes
byte[] hashData = sha1.ComputeHash(Encoding.ASCII.GetBytes(data));
You may need UTF-8 or even some other encoding instead, depending on the range of passwords accepted by the Ruby version. However, the ASCII coding should at least prove correctness of this answer in general from your sample data.

Conversion between Base64String and Hexadecimal

I use in my C++/CLI project ToBase64String to give a string like /MnwRx7kRZEQBxLZEkXndA== I want to convert this string to Hexadecimal representation, How I can do that in C++/CLI or C#?
FromBase64String will take the string to bytes
byte[] bytes = Convert.FromBase64String(string s);
Then, BitConverter.ToString() will convert a byte array to a hex string ( byte[] to hex string )
string hex = BitConverter.ToString(bytes);
Convert the string to a byte array and then do a byte to hex conversion
string stringToConvert = "/MnwRx7kRZEQBxLZEkXndA==";
byte[] convertedByte = Encoding.Unicode.GetBytes(stringToConvert);
string hex = BitConverter.ToString(convertedByte);
Console.WriteLine(hex);
public string Base64ToHex(string strInput)
{
try
{
var bytes = Convert.FromBase64String(strInput);
var hex = BitConverter.ToString(bytes);
return hex.Replace("-", "").ToLower();
}
catch (Exception)
{
return "-1";
}
}
On the contrary: https://stackoverflow.com/a/61224761/3988122

how to convert from string to byte[] [duplicate]

I have the following code:
string s = "2563MNBJP89256666666685755854";
Byte[] bytes = encoding.GetBytes(s);
string hex = "";
foreach (byte b in bytes)
{
int c=b;
hex += String.Format("{0:x2}", (uint)System.Convert.ToUInt32(c.ToString()));
}
It prints the hex values . How can I add it in a vector ob bytes like this?
new byte [0x32,0x35..]
In hex I have : 323536....and so on. The next step is to add then in a byte[] vector in the following format 0x32,0x35..and so on; How to do this?
THX
Isn't bytes already the list of bytes you want?
C#: System.Text.Encoding.ASCII.GetBytes("test")
For C# you could try
System.Text.ASCIIEncoding encoding=new System.Text.ASCIIEncoding();
Byte[] bytes = encoding.GetBytes(strVar);//strVar is the string variable
in C# you can use Encoding.GetBytes Method

Text Decoding Problem

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)

Categories