I would like to know how to reverse the process of the below DecodeBinaryBase64 so that I can have a matching Encode method. In short C# code that if given the output of this method it would return the same string that it took as input.
private static string DecodeBinaryBase64(string stringToDecode)
{
StringBuilder builder = new StringBuilder();
foreach (var b in Convert.FromBase64String(stringToDecode))
builder.Append(string.Format("{0:X2}", b));
return builder.ToString();
}
Here is an example of an encoded string and its decoded counterpart. The result is a SHA1 hash for a file. The above method is an example of understanding how the decoding works to get to the right string.
ENCODED
/KUGOuoESMWYuDb+BTMK1LaGe7k=
DECODED
FCA5063AEA0448C598B836FE05330AD4B6867BB9
or
0xFCA5063AEA0448C598B836FE05330AD4B6867BB9
Updated to reflect correct SHA1 value thanks to Porges and a fix for hex bug found by Dean 'codeka' Hardin.
Implemented Solution
Here is the the implementation I have now, it is from Porges post distilled down to two methods.
private static string EncodeFileDigestBase64(string digest)
{
byte[] result = new byte[digest.Length / 2];
for (int i = 0; i < digest.Length; i += 2)
result[i / 2] = byte.Parse(digest.Substring(i, 2), System.Globalization.NumberStyles.HexNumber);
if (result.Length != 20)
throw new ArgumentException("Not a valid SHA1 filedigest.");
return Convert.ToBase64String(result);
}
private static string DecodeFileDigestBase64(string encodedDigest)
{
byte[] base64bytes = Convert.FromBase64String(encodedDigest);
return string.Join(string.Empty, base64bytes.Select(x => x.ToString("X2")));
}