Join two Base64 strings and then decode them

你。 提交于 2019-12-11 02:04:19

问题


I'm trying to figure out how to join two strings that are encoded Base64 and then decode and get the combined result.

Example:

string1 Hello --- string1 Base64 SGVsbG8=

string2 World --- string2 Base64 V29ybGQ=

If I join the base64 I get something that wont decode SGVsbG8=V29ybGQ=

I want the result to say: Hello World

I don't want only this example to work but rather something that will work with any string. This is a very simplified problem which is a step on an application I'm trying to write I'm stuck on.


回答1:


I found a best way to do this, add plus between one string and other, and add ONE, and only ONE equals char ('=') at the end of string. The return will be "Hello>World", then remove the ">":

class Program
{
    static void Main(string[] args)
    {
        string base64String = "SGVsbG8+V29ybGQ=";
        byte[] encodedByte = Convert.FromBase64String(base64String);
        var finalString = Encoding.Default.GetString(encodedByte)).Replace(">", " ");
        Console.WriteLine(finalString.ToString());
    }
 }

(Old way) In C# I do something like this:

class Program
{
    static void Main(string[] args)
    {
        string base64String = "SGVsbG8=V29ybGQ=";
        Console.WriteLine(DecodeBase64String(base64String));
        Console.ReadLine();
    }

    public static string DecodeBase64String(string base64String)
    {
        StringBuilder finalString = new StringBuilder();

        foreach (var text in base64String.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries))
        {
            byte[] encodedByte = Convert.FromBase64String(text + "=");

            finalString.Append(Encoding.Default.GetString(encodedByte));
            finalString.Append(" "); //This line exists only to attend the "Hello World" case. The correct is remove this and let the one that will receive the return to decide what will do with returned string.
        }

        return finalString.ToString();
    }
}


来源:https://stackoverflow.com/questions/28726466/join-two-base64-strings-and-then-decode-them

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!