2
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[]'".

Oliver
  • 493
  • 2
  • 8
  • 15

3 Answers3

16

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;
}
oerkelens
  • 5,053
  • 1
  • 22
  • 29
1

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

urpok23
  • 11
  • 3
-1
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