Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
400 views
in Technique[技术] by (71.8m points)

c# - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...