Convert a hex string to base64 - c#

byte[] ba = Encoding.Default.GetBytes(input);
var hexString = BitConverter.ToString(ba);
hexString = hexString.Replace("-", "");
Console.WriteLine("Or: " + hexString + " in hexadecimal");
So I got this, now how would I convert hexString to a base64 string?
I tried this, got the error:
Cannot convert from string to byte[]
If that solution works for anyone else, what am I doing wrong?
edit:
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
return System.Convert.ToBase64String(plainTextBytes);
I tried this, but it
returns "Cannot implicitly convert type 'byte[]' to 'string'" on the first
line, then "Argument 1: cannot convert from 'string' to 'byte[]'".

You first need to convert your hexstring to a byte-array, which you can then convert to base-64.
To convert from your hexstring to Base-64, you can use:
public static string HexString2B64String(this string input)
{
return System.Convert.ToBase64String(input.HexStringToHex());
}
Where HexStringToHex is:
public static byte[] HexStringToHex(this string inputHex)
{
var resultantArray = new byte[inputHex.Length / 2];
for (var i = 0; i < resultantArray.Length; i++)
{
resultantArray[i] = System.Convert.ToByte(inputHex.Substring(i * 2, 2), 16);
}
return resultantArray;
}

Since .NET5 it can be done using standard library only:
string HexStringToBase64String(string hexString)
{
// hex-string is converted to byte-array
byte[] stringBytes = System.Convert.FromHexString(hexString);
// byte-array is converted base64-string
string res = System.Convert.ToBase64String(stringBytes);
return res;
}
Also there are good examples in docs

public string HexToBase64(string strInput)
{
try
{
var bytes = new byte[strInput.Length / 2];
for (var i = 0; i < bytes.Length; i++)
{
bytes[i] = Convert.ToByte(strInput.Substring(i * 2, 2), 16);
}
return Convert.ToBase64String(bytes);
}
catch (Exception)
{
return "-1";
}
}
On the contrary: https://stackoverflow.com/a/61224900/3988122

Related

Convert hex code to text c# hex string different the other page

I am working on network conversion (unicode) code, but the results are not what I want.
For reference, this is what I want to achieve: http://www.unit-conversion.info/texttools/hexadecimal/
E.g.
Input "E5BC B5E6 9F8F E6A6 86", received "張柏榆" <-----this is what i need
But I use the following reference code
public static string ConvertStringToHex(String input, System.Text.Encoding encoding)
{
Byte[] stringBytes = encoding.GetBytes(input);
StringBuilder sbBytes = new StringBuilder(stringBytes.Length * 2);
foreach (byte b in stringBytes)
{
sbBytes.AppendFormat("{0:X2}", b);
}
return sbBytes.ToString();
}
I get hex string "355F CF67 8669"
It does not convert the hex code into "張柏榆".
public static string ConvertHexToString(String hexInput, System.Text.Encoding encoding)
{
int numberChars = hexInput.Length;
byte[] bytes = new byte[numberChars / 2];
for (int i = 0; i < numberChars; i += 2)
{
bytes[i / 2] = Convert.ToByte(hexInput.Substring(i, 2), 16);
}
return encoding.GetString(bytes);
}
Any advice would be appreciated.
I tried your function, and it did give an error while trying to convert. Weirdly, when I tried with the string "E5BCB5E69F8FE6A686" (your string without the spaces), it worked.
You could modify your code to replace out the spaces automatically, I also added a line to remove any "-" signs (in case they are included):
public static string ConvertHexToString(String hexInput, System.Text.Encoding encoding)
{
hexInput = hexInput.Replace(" ", "").Replace("-", ""); //Edited here to not declare a new string, suggested by Clonkex in comment
int numberChars = hexInput.Length;
byte[] bytes = new byte[numberChars / 2];
for (int i = 0; i < numberChars; i += 2)
{
bytes[i / 2] = Convert.ToByte(hexInput.Substring(i, 2), 16);
}
return encoding.GetString(bytes);
}
You only use System.Text.Encoding.UTF8
string temp = ConvertStringToHex("張柏榆", System.Text.Encoding.UTF8);
string temp1 = ConvertHexToString(temp, System.Text.Encoding.UTF8);
You can use this. I hope it will work for you.

Convert little endian to big endian in c#

I want to convert string "8BABEEF9D2472E65" to big endian.
I already input in this function, I receive UINT Size error.. How can i do?
Function :
string bigToLittle(string data)
{
int number = Convert.ToInt32(data, 16);
byte[] bytes = BitConverter.GetBytes(number);
string retval = "";
foreach (byte b in bytes)
retval += b.ToString("X2");
return retval;
}
I think you can use System.Runtime.Remoting.Metadata.W3cXsd2001.SoapHexBinary class.
string input = "8BABEEF9D2472E65";
var output = new SoapHexBinary(SoapHexBinary.Parse(input).Value.Reverse().ToArray())
.ToString();
Output: 652E47D2F9EEAB8B
Or Maybe
var output = IPAddress.HostToNetworkOrder(long.Parse(input, NumberStyles.HexNumber))
.ToString("X");
As we can not guess what exacly you want as output I let myself write missing possibilities(in code comments)... you can choose which you trully need:
internal class Program
{
private static int ReverseBytes(long val)
{
byte[] intAsBytes = BitConverter.GetBytes(val);
Array.Reverse(intAsBytes);
return BitConverter.ToInt32(intAsBytes, 0);
}
private static string IntToBinaryString(long v)
{
string s = Convert.ToString(v, 2);
string t = s.PadLeft(32, '0');
string res = "";
for (int i = 0; i < t.Length; ++i)
{
if (i > 0 && i%8 == 0)
res += " ";
res += t[i];
}
return res;
}
private static void Main(string[] args)
{
string sValue = "8BABEEF9D2472E65";
long sValueAsInt = long.Parse(sValue, System.Globalization.NumberStyles.HexNumber);
//output {-8382343524677898651}
string sValueAsStringAgain = IntToBinaryString(sValueAsInt);
//output {10001011 10101011 11101110 11111001 11010010 01000111 00101110 01100101}
byte[] data = Encoding.BigEndianUnicode.GetBytes(sValue);
string decodedX = Encoding.BigEndianUnicode.GetString(data);
string retval = data.Aggregate("", (current, b) => current + b.ToString("X2"));
//output {0038004200410042004500450046003900440032003400370032004500360035}
char[] decodedX2 = Encoding.BigEndianUnicode.GetString(data).Reverse().ToArray();
StringBuilder retval2 = new StringBuilder(); //output {56E2742D9FEEBAB8}
foreach (var b in decodedX2)
retval2.Append(b);
Console.ReadLine();
}
}
}
and bout yours Method:
public static string bigToLittle(string data)
{
long sValueAsInt = long.Parse(data, System.Globalization.NumberStyles.HexNumber);
byte[] bytes = BitConverter.GetBytes(sValueAsInt);
string retval = "";
foreach (byte b in bytes)
retval += b.ToString("X2");
return retval; //output {652E47D2F9EEAB8B}
}
I liked #Sebatsian's answer but I ran into issues with the entry being padded by extra zeroes, so I modified it slightly, in case you are doing something like converting Linux VMUUID's in Azure over to standard format. I made use of IPAddress.HostToNetworkOrder, which handles breaking your long into bytes and reversing them.
private string BigToLittle(string data)
{
long sValueAsInt = long.Parse(data, System.Globalization.NumberStyles.HexNumber);
var length = data.Length;
return IPAddress.HostToNetworkOrder(sValueAsInt).ToString("X2").Substring(0, length);
}
In usage:
string uuid = "090556DA-D4FA-764F-A9F1-63614EDA0163";
private string BigToLittle(string data)
{
long sValueAsInt = long.Parse(data, System.Globalization.NumberStyles.HexNumber);
var length = data.Length;
return IPAddress.HostToNetworkOrder(sValueAsInt).ToString("X2").Substring(0, length);
}
var elements = uuid.Split(new char[] { '-' });
var outMe = new List<string> { };
foreach (var item in elements)
{
outMe.Add(BigToLittle(item));
}
var output = String.Join("-", outMe);
//DA560509-FAD4-4F76-F1A9-6301DA4E6163

Binary to string/string to binary

I want to convert text into binary and after that, to try convert binary into string text.
How can i convert tobin back into text if it is already a string?
private void iTalk_Button_12_Click(object sender, EventArgs e)
{
ambiance_RichTextBox2.Text = tobin(ambiance_RichTextBox1.Text);
}
public string tobin(string inp)
{
StringBuilder sb = new StringBuilder();
foreach (char L in inp.ToCharArray())
{
sb.Append(Convert.ToString(L, 2).PadLeft(8, '0'));
}
return sb.ToString();
}
private void iTalk_Button_12_Click(object sender, EventArgs e)
{
ambiance_RichTextBox2.Text = BinaryToString(ambiance_RichTextBox1.Text);
//use what u need: BinaryToString or StringToBinary.
}
Convert String to Binary:
public static string StringToBinary(string data)
{
StringBuilder sb = new StringBuilder();
foreach (char c in data.ToCharArray())
{
sb.Append(Convert.ToString(c, 2).PadLeft(8, '0'));
}
return sb.ToString();
}
Convert Binary to String:
public static string BinaryToString(string data)
{
List<Byte> byteList = new List<Byte>();
for (int i = 0; i < data.Length; i += 8)
{
byteList.Add(Convert.ToByte(data.Substring(i, 8), 2));
}
return Encoding.ASCII.GetString(byteList.ToArray());
}
Good luck!
You can use like this,
public static string BinaryToString(string data)
{
List<Byte> byteList = new List<Byte>();
for (int i = 0; i < data.Length; i += 8)
{
byteList.Add(Convert.ToByte(data.Substring(i, 8), 2));
}
return Encoding.ASCII.GetString(byteList.ToArray());
}
Currently you are converting a char (which can be represented as a number) to its binary representation (this number is the ASCII number). But if you want to convert a string to binary, you should use an encoding. The encoding determines how the text is converted to binary.
For example:
static void Main(string[] args)
{
string input = "This is an example text.";
Console.WriteLine(input);
string asBin = ToBinary(input);
Console.WriteLine(asBin);
string asText = ToText(asBin);
Console.WriteLine(asText);
}
static string ToBinary(string input, System.Text.Encoding encoding = null)
{
if (encoding == null)
encoding = System.Text.Encoding.UTF8;
var builder = new System.Text.StringBuilder();
var bytes = encoding.GetBytes(input); // Convert the text to bytes using the encoding
foreach (var b in bytes)
builder.Append(Convert.ToString(b, 2).PadLeft(8, '0')); //Convert the byte to its binary representation
return builder.ToString();
}
static string ToText(string bytes, System.Text.Encoding encoding = null)
{
if (encoding == null)
encoding = System.Text.Encoding.UTF8;
var byteCount = 8;
var byteArray = new byte[bytes.Length / 8]; // An array for the bytes
for (int i = 0; i < bytes.Length / byteCount; i++)
{
var subBytes = bytes.Substring(i * byteCount, byteCount); // Get a subpart of 8 bits
var b = Convert.ToByte(subBytes.TrimStart('0'), 2); // Convert the subpart to a byte
byteArray[i] = b; // Add the byte to the array
}
return encoding.GetString(byteArray); // Convert the array to text using the right encoding.
}
Now if you want to use ASCII encoding, you can call the functions as follows:
Console.WriteLine(input);
string asBin = ToBinary(input, System.Text.Encoding.ASCII);
Console.WriteLine(asBin);
string asText = ToText(asBin, System.Text.Encoding.ASCII);
Console.WriteLine(asText);
To convert a string to binary
string s = "hai";
byte []arr = System.Text.Encoding.ASCII.GetBytes(s);
To convert binary to string
byte[] arr ;
string s = Encoding.ASCII.GetString(arr);

Binary To Corresponding ASCII String Conversion

Hi i was able to convert a ASCII string to binary using a binarywriter .. as 10101011 . im required back to convert Binary ---> ASCII string .. any idea how to do it ?
This should do the trick... or at least get you started...
public Byte[] GetBytesFromBinaryString(String binary)
{
var list = new List<Byte>();
for (int i = 0; i < binary.Length; i += 8)
{
String t = binary.Substring(i, 8);
list.Add(Convert.ToByte(t, 2));
}
return list.ToArray();
}
Once the binary string has been converted to a byte array, finish off with
Encoding.ASCII.GetString(data);
So...
var data = GetBytesFromBinaryString("010000010100001001000011");
var text = Encoding.ASCII.GetString(data);
If you have ASCII charters only you could use Encoding.ASCII.GetBytes and Encoding.ASCII.GetString.
var text = "Test";
var bytes = Encoding.ASCII.GetBytes(text);
var newText = Encoding.ASCII.GetString(bytes);
Here is complete code for your answer
FileStream iFile = new FileStream(#"c:\test\binary.dat",
FileMode.Open);
long lengthInBytes = iFile.Length;
BinaryReader bin = new BinaryReader(aFile);
byte[] byteArray = bin.ReadBytes((int)lengthInBytes);
System.Text.Encoding encEncoder = System.Text.ASCIIEncoding.ASCII;
string str = encEncoder.GetString(byteArray);
Take this as a simple example:
public void ByteToString()
{
Byte[] arrByte = { 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0 };
string x = Convert.ToBase64String(arrByte);
}
This linked answer has interesting details about this kind of conversion:
binary file to string
Sometimes instead of using the built in tools it's better to use "custom" code.. try this function:
public string BinaryToString(string binary)
{
if (string.IsNullOrEmpty(binary))
throw new ArgumentNullException("binary");
if ((binary.Length % 8) != 0)
throw new ArgumentException("Binary string invalid (must divide by 8)", "binary");
StringBuilder builder = new StringBuilder();
for (int i = 0; i < binary.Length; i += 8)
{
string section = binary.Substring(i, 8);
int ascii = 0;
try
{
ascii = Convert.ToInt32(section, 2);
}
catch
{
throw new ArgumentException("Binary string contains invalid section: " + section, "binary");
}
builder.Append((char)ascii);
}
return builder.ToString();
}
Tested with 010000010100001001000011 it returned ABC using the "raw" ASCII values.

Convert PHP encryption code to C#

I'm trying to convert this piece of code from PHP to C#. It's part of a Captive Portal. Could somebody explain what it does?
$hexchal = pack ("H32", $challenge);
if ($uamsecret) {
$newchal = pack ("H*", md5($hexchal . $uamsecret));
} else {
$newchal = $hexchal;
}
$response = md5("\0" . $password . $newchal);
$newpwd = pack("a32", $password);
$pappassword = implode ("", unpack("H32", ($newpwd ^ $newchal)));
I also encountered the need of php's pack-unpack functions in c# but did not get any good resource.
So i thought to do it myself. I have verified the function's input with pack/unpack/md5 methods found at onlinephpfunctions.com. Since i have done code only as per my requirements. This can be extended for other formats
Pack
private static string pack(string input)
{
//only for H32 & H*
return Encoding.Default.GetString(FromHex(input));
}
public static byte[] FromHex(string hex)
{
hex = hex.Replace("-", "");
byte[] raw = new byte[hex.Length / 2];
for (int i = 0; i < raw.Length; i++)
{
raw[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
}
return raw;
}
MD5
private static string md5(string input)
{
byte[] asciiBytes = Encoding.Default.GetBytes(input);
byte[] hashedBytes = MD5CryptoServiceProvider.Create().ComputeHash(asciiBytes);
string hashedString = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
return hashedString;
}
Unpack
private static string unpack(string p1, string input)
{
StringBuilder output = new StringBuilder();
for (int i = 0; i < input.Length; i++)
{
string a = Convert.ToInt32(input[i]).ToString("X");
output.Append(a);
}
return output.ToString();
}
Eduardo,
if you take a look at the pack manual, pack is used to convert a string in (hex, octal, binary )to his number representation.
so
$hexcal = pack('H32', $challenge);
would convert a string like 'cca86bc64ec5889345c4c3d8dfc7ade9' to the actual 0xcca... de9
if $uamsecret exist do the same things with the MD5 of hexchal concacteate with the uamsecret.
if ($uamsecret) {
$newchal = pack ("H*", md5($hexchal . $uamsecret));
} else {
$newchal = $hexchal;
}
$response = md5("\0" . $password . $newchal);
MD% '\0' + $password + $newchal
$newpwd = pack("a32", $password);
pad password to 32 byte
$pappassword = implode ("", unpack("H32", ($newpwd ^ $newchal)));
do a xor newpwd and newchal and convert it to a hexadecimal string, I don't get the implode() maybe it's to convert to string to an array of character.

Categories

Resources