[英]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
好的,我有一個字符串,以Base 64編碼,如下所示:
string myText = "abcBASE64TEXTGOESHEREdef=="; // actual string is 381 characters long with trailing '=='
然后,將我的字符串從Base 64轉換為字節數組,如下所示:
byte[] decodedFromBase64 = Convert.FromBase64String(myText);
此時,我想獲取此字節數組的字符串值,並將其保存在文本文件中, 而不會造成數據丟失或損壞 。 下面的代碼似乎沒有這樣做:
string myDecodedText = Encoding.ASCII.GetString(decodedFromBase64);
StreamWriter myStreamWriter = new StreamWriter("C:\\OpenSSL-Win32\\bin\\textToDecrypt.txt");
myStreamWriter.Write(myString);
myStreamWriter.Flush();
myStreamWriter.Close();
有人可以告訴我我要去哪里錯了。
編輯:輸出不可讀,我需要獲取解碼后的字符串,然后使用OpenSSL對其進行解密。 OpenSSL的輸出和結果都在下面:
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;
}
如果對字符串進行了編碼,則內容看起來很像文本文件中的內容。 但是為了確保文件不會損壞,您應該將文件內容寫為二進制文件,而不是使用文本編碼器。 檢出File.WriteAllBytes() 。
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.