Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to decode a string of text from a Base64 to a byte array, and the get the string property of this byte array without data corruption

Ok so I have a string of text, encoded in Base 64 like below:

string myText = "abcBASE64TEXTGOESHEREdef==";  // actual string is 381 characters long with trailing '=='

I then convert my string from Base 64 to a byte array like so:

byte[] decodedFromBase64 = Convert.FromBase64String(myText);

At this point, I want to get the string value of this byte array and save this in a text file without data loss or corruption. The code below doesn't seem to be doing it:

string myDecodedText = Encoding.ASCII.GetString(decodedFromBase64);
StreamWriter myStreamWriter = new StreamWriter("C:\\OpenSSL-Win32\\bin\\textToDecrypt.txt");
myStreamWriter.Write(myString);
myStreamWriter.Flush();
myStreamWriter.Close();

Can somebody please tell me where I'm going wrong.

Edit: The output is unreadable, I need to take the decoded string and then use OpenSSL to decrypt it. The Output and the result from OpenSSL are both below:

Output

OpenSSL

like image 963
JMK Avatar asked Dec 27 '11 13:12

JMK


People also ask

How do I decode Base64 text files?

To decode a file with contents that are base64 encoded, you simply provide the path of the file with the --decode flag. As with encoding files, the output will be a very long string of the original file. You may want to output stdout directly to a file.

Can Base64 encoding be decoded?

In JavaScript there are two functions respectively for decoding and encoding Base64 strings: btoa() : creates a Base64-encoded ASCII string from a "string" of binary data ("btoa" should be read as "binary to ASCII"). atob() : decodes a Base64-encoded string ("atob" should be read as "ASCII to binary").

Is Base64 a byte array?

The ToBase64String method is designed to process a single byte array that contains all the data to be encoded. To encode data from a stream, use the System. Security.

How do I find Base64 encoded strings?

In base64 encoding, the character set is [A-Z, a-z, 0-9, and + /] . If the rest length is less than 4, the string is padded with '=' characters. ^([A-Za-z0-9+/]{4})* means the string starts with 0 or more base64 groups.


2 Answers

public static string base64Decode(string data)
{
     byte[] toDecodeByte = Convert.FromBase64String(data);

     System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
     System.Text.Decoder utf8Decode = encoder.GetDecoder();

     int charCount = utf8Decode.GetCharCount(toDecodeByte, 0, toDecodeByte.Length);

     char[] decodedChar = new char[charCount];
     utf8Decode.GetChars(toDecodeByte, 0, toDecodeByte.Length, decodedChar, 0);
     string result = new String(decodedChar);
     return result;
}
like image 140
Hussein Zawawi Avatar answered Sep 19 '22 20:09

Hussein Zawawi


static void Main(string[] args)
    {
        string completeUrl = SERVICE_URL;
        WebRequest request = WebRequest.Create(completeUrl);
        request.Credentials = CredentialCache.DefaultCredentials;
        WebProxy proxyObject = new WebProxy(SERVICE_URL, true);
        request.Proxy = proxyObject;
        HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();
        byte[] data;
        const int BUFFER_SIZE = 2048;
        int bytesRead;
        byte[] buffer = new byte[BUFFER_SIZE];
        using (MemoryStream mss = new MemoryStream())
        {
            using (BinaryReader readers = new
            BinaryReader(webResponse.GetResponseStream(), System.Text.Encoding.UTF8))
            {
                while ((bytesRead = readers.Read(buffer, 0, BUFFER_SIZE)) > 0)
                {
                    mss.Write(buffer, 0, bytesRead);
                }
                data = mss.ToArray();
                System.Text.Encoding enc = System.Text.Encoding.GetEncoding("iso-8859-1");
                string str = enc.GetString(data);
                XmlDocument xdoc = new XmlDocument();
                xdoc.LoadXml(str);
                XmlNode xmlList = xdoc.ChildNodes[1];
                XmlNode item = xmlList.ChildNodes[1]; //this is your data : JVBERi0xLjUNCiXNzc3NDQoxIDAgb2JqDQo8PA0KL0NyZWF0b3IgKERvY3VtZW50UHJ
                Base64Decode(item.InnerText.ToString());
                Console.WirteLine("File successfully saved");
                Console.ReadLine();
            }
        }
    }

    public static void Base64Decode(string base64EncodedData)
    {
        var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
        File.WriteAllBytes("pdf.pdf", base64EncodedBytes);
    }
like image 31
Tshepo Kwienana Avatar answered Sep 22 '22 20:09

Tshepo Kwienana