Determine if a string contains a base64 string inside it

I am trying to figure out a way to parse a base64 string with a larger string.

I have a string "Hello <base64 content> World"and I want to be able to parse the contents of base64 and convert it back to string."Hello Awesome World"

Answers to C # are preferable.

Edit: Updated with a more realistic example.

--abcdef
\n
Content-Type: Text/Plain;
Content-Transfer-Encoding: base64
\n
<base64 content>
\n
--abcdef--

This is taken from 1 sample. The problem is that the content ... is very different from one record to another.

+5
source share
2 answers

In short form, you can:

  • split the string into any characters that are not valid base64 data or padding
  • try to convert each token
  • , ,

:

var delimiters = new char[] { /* non-base64 ASCII chars */ };
var possibles = value.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
//need to tweak to include padding chars in matches, but still split on padding?
//maybe better off creating a regex to match base64 + padding
//and using Regex.Split?

foreach(var match in possibles)
{
    try
    {
        var converted = Convert.FromBase64String(match);
        var text = System.Text.Encoding.UTF8.GetString(converted);
        if(!string.IsNullOrEmpty(text))
        {
            value = value.Replace(match, text);
        }
    } 
    catch (System.ArgumentNullException) 
    {
        //handle it
    }
    catch (System.FormatException) 
    {
        //handle it
    }
}

, , , base64, base64.

"Hello QXdlc29tZQ== World" "Hello Awesome World", - "Ć©eĀ”Ćā€¢ĆĀ½Āµ"¢¹]", base64, .

( ):

base64 '\n' "Content-Transfer-Encoding: base64\n", :

  • '\n'
  • , "Content-Transfer-Encoding: base64"
  • ( ) ( ),
  • ,

:

private string ConvertMixedUpTextAndBase64(string value)
{
    var delimiters = new char[] { '\n' };
    var possibles = value.Split(delimiters, 
                                StringSplitOptions.RemoveEmptyEntries);

    for (int i = 0; i < possibles.Length - 1; i++)
    {
        if (possibles[i].EndsWith("Content-Transfer-Encoding: base64"))
        {
            var nextTokenPlain = DecodeBase64(possibles[i + 1]);
            if (!string.IsNullOrEmpty(nextTokenPlain))
            {
                value = value.Replace(possibles[i + 1], nextTokenPlain);
                i++;
            }
        }                
    }
    return value;
}

private string DecodeBase64(string text)
{
    string result = null;
    try
    {
        var converted = Convert.FromBase64String(text);
        result = System.Text.Encoding.UTF8.GetString(converted);
    }
    catch (System.ArgumentNullException)
    {
        //handle it
    }
    catch (System.FormatException)
    {
        //handle it
    }
    return result;
}
+4

. , , , "Hello" ? , , base64 , 4, ""? 8- , base64 ( "Ā¢ Ć·" ~ Z0 "), , , -. , base64.

, base64, , , - , - ...

+8

All Articles