Share via


Determine if value is hex or Base64

Question

Thursday, June 13, 2019 6:54 AM

Hi,

I take a value that is either in HEX format or in base64 format and if it is in base64 i must convert it to HEX. How can best practise check if the value is already converted or not? 

Value base 64: AAAAABpEc5CqZhHNm8gAqgAvxFoJAByiclq9jVVDpXaNc2n+dTUAAAAAH2oAADMm3IYAeWhMn4Fui+Vchl8ABCrkgNoAAA== 

Value hex: 000000001A447390AA6611CD9BC800AA002FC45A09001CA2725ABD8D5543A5768D7369FE7535000000001F6A00003326DC860079684C9F816E8BE55C865F00042AE480DA0000                                                                                                                                                            

       private static bool IsBase64String(string sStringToTest)
        {
            bool bIsBase64 = false;
            sStringToTest = sStringToTest.Trim();
           
            if ((sStringToTest.Length % 4) != 0)
            {
                bIsBase64 = false;
            }
            // Check that the string matches the base64 layout      
            if (Regex.IsMatch(sStringToTest, @"^[a-zA-Z0-9\+/]*={0,2}$"))
            {
                bIsBase64 = true;
            }
            return bIsBase64;
        }

All replies (2)

Thursday, June 13, 2019 11:26 AM ✅Answered | 1 vote

I think that it is not always possible to distinguish Base64 and Hex strings. For example, “ABCD” can be interpreted as 0, 0x10, 0x83 in Base64 or as 0xAB, 0xCD in Hex.


Thursday, June 13, 2019 1:50 PM ✅Answered | 1 vote

Base64 is hex. There is no difference. A base64 string is simply a byte array converted to a string. Not every hex string is Base64 though. The easiest way to test this is to simply try to convert it.

public static bool IsBase64 ( string value )
{
  try
  {
      Convert.FromBase64String(value);
      return true;
  } catch (FormatException)
  {
     return false;
  };
}

This function already handles the rules around Base64 such as padding, allowed characters, etc. No reason to reinvent the wheel.

Michael Taylor http://www.michaeltaylorp3.net