Senna <Se***@discussions.microsoft.com> wrote:
Have a symmetric encryption method that returns a base64 string. I then get
the hex representation of that string with the code below
public static string Base64ToHex(string input)
{
StringBuilder sb = new StringBuilder();
byte[] inputBytes = Encoding.UTF8.GetBytes(input);
foreach(byte b in inputBytes)
{
sb.Append(string.Format("{0:x2}", b));
}
return sb.ToString();
}
My question is: How do I get the hex string back to base64 string?
Ex.
base64: NuZ5uF0MHtJ54nMc+79t/NR9GAmmaY3vUJu7fZyvww0=
hexfrombase64: 4e755a357546304d48744a35346e4d632b3739742f4e523947 416d6d6159
3376554a7537665a79767777303d
base64fromhex: NuZ5uF0MHtJ54nMc+79t/NR9GAmmaY3vUJu7fZyvww0=
My previous answer was definitely somewhat suboptimal, I'm afraid.
Here's a method to actually do what you want.
Note that because you used UTF-8 and everything in Base64 is within the
ASCII character set, we don't need to do any conversion beyond casting
the hex value to a char. (Nor did you need to for your conversion,
btw.)
It could certainly be faster, but it'll do you fine, I'm sure:
static int ParseHexDigit(char c)
{
if (c >= '0' && c <= '9')
{
return c-'0';
}
if (c >= 'a' && c <= 'f')
{
return c-'a'+10;
}
if (c >= 'A' && c <= 'F')
{
return c-'A'+10;
}
throw new ArgumentException ("Invalid hex character");
}
public static string ParseHex(string hex)
{
char[] result = new char[hex.Length/2];
int hexIndex=0;
for (int i=0; i < result.Length; i++)
{
result[i] = (char)(ParseHexDigit(hex[hexIndex++])*16+
ParseHexDigit(hex[hexIndex++]));
}
return new string (result);
}
--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too