/// <summary> /// 获取远程信息 /// </summary> /// <param name="url">请求地址</param> /// <param name="encoding">请求编码</param> /// <param name="wc">客户端</param> public static string Get(string url, Encoding encoding = null, WebClient wc = null) { if (string.IsNullOrWhiteSpace(url)) { return string.Empty; } url = url.Replace("\\", "/"); if (encoding == null) encoding = Encoding.UTF8; var isNew = wc == null; if (wc == null) { wc = new WebClient(); wc.Proxy = null; wc.Headers.Add("Accept", "*/*"); wc.Headers.Add("Referer", url); wc.Headers.Add("Cookie", "bid=\"YObnALe98pw\";"); wc.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.5 Safari/537.31"); } string strResult = null; try { var data = wc.DownloadData(url); strResult = encoding.GetString(data); } catch { return string.Empty; } finally { if (!isNew) Cookies(wc); if (isNew) wc.Dispose(); } return strResult; }
public static string GetTextForChunked(byte[] bytes, int contentStartIndex, int contentLength, bool isGzip, Encoding coding) { string html = string.Empty; Stream contentStream = new MemoryStream(); int lastEnterIndex = contentStartIndex; for (int i = contentStartIndex; i < contentLength + contentStartIndex; i++) { if (bytes[i] == 13 && bytes[i + 1] == 10) { int chunkLength = int.Parse(coding.GetString(bytes, lastEnterIndex, i - lastEnterIndex).Trim(), System.Globalization.NumberStyles.AllowHexSpecifier); if (isGzip) { if (chunkLength > 0) contentStream.Write(bytes, i + 2, chunkLength); } else { html += coding.GetString(bytes, i + 2, chunkLength); } i = i + 4 + chunkLength; if (i + 1 >= contentLength + contentStartIndex) { //此步骤很有必要,因之前的write操作已将流指向最后,如果要重新读取则必须重置 contentStream.Seek(0, SeekOrigin.Begin); html = GetTextForGzip(contentStream, coding); } lastEnterIndex = i; } } return html; }
public FormFile(byte[] infob, byte[] content, Encoding encoding) { var info = encoding.GetString(infob); ContentType = null; Size = -1; var parts = info.Split(new[] {";", "\r\n"}, StringSplitOptions.RemoveEmptyEntries); foreach (var part in parts.Select(x => x.Trim())) { if (part.StartsWith("name=", StringComparison.OrdinalIgnoreCase)) { Name = UnEscape(part.Substring(5)); } else if (part.StartsWith("filename=", StringComparison.OrdinalIgnoreCase)) { FileName = UnEscape(part.Substring(9)); Size = content.Length; } else if (part.StartsWith("Content-Type: ", StringComparison.OrdinalIgnoreCase)) { ContentType = UnEscape(part.Substring(14)); } } _stream = ContentType != null ? new MemoryStream(content) : null; if (ContentType == null) FileName = encoding.GetString(content); }
internal static string ReadStringInternalDynamic(this Stream stream, Encoding encoding, char end) { int characterSize = encoding.GetByteCount("e"); Debug.Assert(characterSize == 1 || characterSize == 2 || characterSize == 4); string characterEnd = end.ToString(); int i = 0; byte[] data = new byte[128 * characterSize]; while (true) { if (i + characterSize > data.Length) { Array.Resize(ref data, data.Length + (128 * characterSize)); } int read = stream.Read(data, i, characterSize); Debug.Assert(read == characterSize); if (encoding.GetString(data, i, characterSize) == characterEnd) { break; } i += characterSize; } if (i == 0) { return ""; } return encoding.GetString(data, 0, i); }
/// <summary> /// Reads the file at the given path line by line. /// </summary> /// <param name="path"></param> /// <param name="encoding"></param> /// <returns></returns> public static IEnumerable<string> ReadLineByLine(string path, Encoding encoding) { bool isFirstLine = true; FileStream fs = new FileStream(path, FileMode.Open); try { int b = 0; List<byte> lineBuilder = new List<byte>(256); while ((b = fs.ReadByte()) >= 0) { if (b == '\n') { if (isFirstLine) { yield return encoding.GetString(lineBuilder.ToArray()).Substring(1); isFirstLine = false; } else { yield return encoding.GetString(lineBuilder.ToArray()); } lineBuilder.Clear(); } else if (b != '\r') { lineBuilder.Add((byte)b); } } } finally { fs.Close(); } }
// 获取网页的HTML内容,根据网页的charset自动判断Encoding public static string GetHtml(string url, Encoding encoding = null) { byte[] buf = new WebClient().DownloadData(url); if (encoding != null) return encoding.GetString(buf); string html = Encoding.UTF8.GetString(buf); encoding = GetEncodingFromHtml(html); if (encoding == null || encoding == Encoding.UTF8) return html; return encoding.GetString(buf); }
private static Message ReadMessage(BinaryReader BR, Encoding E) { Message M = new Message(); M.Category = BR.ReadByte(); M.Language = BR.ReadByte(); M.ParentGroup = BR.ReadByte(); M.ID = BR.ReadByte(); M.Text = E.GetString(BR.ReadBytes(BR.ReadByte())).TrimEnd('\0'); if (M.Category == 4) M.AlternateText = E.GetString(BR.ReadBytes(BR.ReadByte())).TrimEnd('\0'); return M; }
public BasicAuth(string encodedHeader, Encoding encoding) { HeaderValue = encodedHeader; var decodedHeader = encodedHeader.StartsWith(Prefix, StringComparison.OrdinalIgnoreCase) ? encoding.GetString(Convert.FromBase64String(encodedHeader.Substring(Prefix.Length))) : encoding.GetString(Convert.FromBase64String(encodedHeader)); var credArray = decodedHeader.Split(':'); if (credArray.Length > 0) _User = credArray[0]; if (credArray.Length > 1) _Password = credArray[1]; }
private static MessageGroup ReadMessageGroup(BinaryReader BR, Encoding E) { MessageGroup MG = new MessageGroup(); MG.Category = BR.ReadByte(); MG.Language = BR.ReadByte(); MG.ID = BR.ReadByte(); MG.ParentGroup = BR.ReadByte(); MG.Title = E.GetString(BR.ReadBytes(32)).TrimEnd('\0'); MG.Description = E.GetString(BR.ReadBytes(32)).TrimEnd('\0'); uint MessageCount = BR.ReadUInt32(); /* MessageBytes */ BR.ReadUInt32(); for (int i = 0; i < MessageCount; ++i) MG.Messages.Add(AutoTranslator.ReadMessage(BR, E)); return MG; }
/// <summary> /// Returns a decrypted string by a key /// </summary> /// <remarks> /// If something is broken this method returns an empty string /// </remarks> /// <param name="text">Text to decrypt</param> /// <param name="key">Key to decrypt</param> /// <param name="encoding" >Encoding to get bytes. UTF8 by default.</ param > /// <returns></returns> public static String Decrypt(String textoEncriptado, String clave, Encoding encoding = null) { try { if (String.IsNullOrEmpty(textoEncriptado) || String.IsNullOrEmpty(clave)) return String.Empty; byte[] keyBytes; byte[] encryptedBytes = Convert.FromBase64String(textoEncriptado); //Create a MD5 object to obtain a hash MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider(); keyBytes = hashmd5.ComputeHash(encoding.GetBytes(clave)); hashmd5.Clear(); //Create a Triple DES object to decrypt TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider(); tdes.Key = keyBytes; tdes.Mode = CipherMode.ECB; tdes.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = tdes.CreateDecryptor(); byte[] resultArray = cTransform.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length); tdes.Clear(); return encoding.GetString(resultArray); } catch (Exception) { return String.Empty; } }
public override void AppendAllText(string path, string contents, Encoding encoding) { var file = mockFileDataAccessor.GetFile(path); var originalText = encoding.GetString(file.Contents); var newText = originalText + contents; file.Contents = encoding.GetBytes(newText); }
/// <summary> /// 对已编码的字符串进行解码 /// </summary> /// <param name="str">待解码字符串</param> /// <param name="encoding">编码时使用的编码</param> /// <returns>string</returns> public static string Decode(string str, Encoding encoding) { if (String.IsNullOrEmpty(str)) { return ""; } str = str.ToLower(); StringBuilder binaryString = new StringBuilder(); foreach (char c in str.ToCharArray()) { binaryString.Append(Convert.ToString(CODE_CHARS.IndexOf(c), 2).PadLeft(BIT8, '0')); } int n = binaryString.Length / BIT8; string[] bit8Array = new string[n]; for (int i = 0; i < n; i++) { bit8Array[i] = binaryString.ToString(i * BIT8, BIT8).Substring(BIT8 - BIT5); } string bit8String = String.Join("", bit8Array); bit8Array = new string[bit8String.Length / BIT8]; for (int i = 0; i < bit8Array.Length; i++) { bit8Array[i] = bit8String.Substring(i * BIT8, BIT8); } byte[] decodedBytes = new byte[bit8Array.Length]; for (int i = 0; i < decodedBytes.Length; i++) { decodedBytes[i] = Convert.ToByte(bit8Array[i], 2); } return encoding.GetString(decodedBytes); }
/// <summary> Convert string from one codepage to another. </summary> /// <param name="input"> The string. </param> /// <param name="fromEncoding"> input encoding codepage. </param> /// <param name="toEncoding"> output encoding codepage. </param> /// <returns> the encoded string. </returns> static public string ConvertEncoding(string input, Encoding fromEncoding, Encoding toEncoding) { var byteArray = fromEncoding.GetBytes(input); var asciiArray = Encoding.Convert(fromEncoding, toEncoding, byteArray); var finalString = toEncoding.GetString(asciiArray); return finalString; }
/// <summary> /// 将返回的Byte尝试转化为字符串 /// </summary> public bool TryGetStringResult(Encoding encoding, out string stringResult) { if (_hasConvertToString && _convertToStringSuccess) { stringResult = _stringResult; return _convertToStringSuccess; } else { try { _stringResult = encoding.GetString(_result); _hasConvertToString = true; _convertToStringSuccess = true; } catch (Exception ex) { _stringResult = string.Empty; _hasConvertToString = true; _convertToStringSuccess = false; } finally { stringResult = _stringResult; } return _convertToStringSuccess; } }
public override string Decode(string s, Encoding encoding) { if (s == null) { throw new ArgumentNullException("s"); } if (encoding == null) { throw new ArgumentNullException("encoding"); } if (s.Trim() == string.Empty) { return s; } if (((s == null) || (s.Length <= 8)) || ((s.Length % 2) != 0)) { throw new ArgumentException("s"); } byte key = byte.Parse(s.Substring(s.Length - 4, 2), NumberStyles.HexNumber); s = s.Substring(2, s.Length - 6); byte[] bytes = new byte[s.Length / 2]; for (int i = 0; i < bytes.Length; i++) { byte b = byte.Parse(s.Substring(i * 2, 2), NumberStyles.HexNumber); bytes[i] = Decrypt(b, key); } return encoding.GetString(bytes); }
public static String PtrToString(byte* Pointer, Encoding Encoding) { if (Pointer == null) return null; List<byte> Bytes = new List<byte>(); for (; *Pointer != 0; Pointer++) Bytes.Add(*Pointer); return Encoding.GetString(Bytes.ToArray()); }
public static String PtrToString(byte* Pointer, int Length, Encoding Encoding) { if (Pointer == null) return null; List<byte> Bytes = new List<byte>(); for (int n = 0; n < Length; n++) Bytes.Add(Pointer[n]); return Encoding.GetString(Bytes.ToArray()); }
public static string ReadString(this BinaryReader br, int len, Encoding enc = null) { if (enc == null) enc = Encoding.Unicode; return enc.GetString(br.ReadBytes(len)); }
/// <summary> /// 新建一个邮件模板对象 /// </summary> /// <param name="templetFilePath">HTML模块文件路径</param> /// <param name="fileEnc">模板内容编码方式</param> public MailTemplet(string templetFilePath, Encoding fileEnc) { if (!File.Exists(templetFilePath)) throw new ArgumentException("模块文件在指定路径不存在!"); tptContent = fileEnc.GetString(File.ReadAllBytes(templetFilePath)); }
/// <summary> /// 利用WebClient 远程POST数据并返回数据 /// </summary> /// <param name="strUrl">远程URL地址</param> /// <param name="strParams">参数</param> /// <param name="RespEncode">POST数据的编码</param> /// <param name="ReqEncode">获取数据的编码</param> /// <returns></returns> public static string PostData(string strUrl, string strParams, Encoding RespEncode, Encoding ReqEncode) { HttpClient httpclient = new HttpClient(); try { //打开页面 httpclient.Credentials = CredentialCache.DefaultCredentials; //从指定的URI下载资源 byte[] responseData = httpclient.DownloadData(strUrl); string srcString = RespEncode.GetString(responseData); httpclient.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); string postString = strParams; // 将字符串转换成字节数组 byte[] postData = Encoding.ASCII.GetBytes(postString); // 上传数据,返回页面的字节数组 responseData = httpclient.UploadData(strUrl, "POST", postData); srcString = ReqEncode.GetString(responseData); return srcString; } catch (Exception ex) { //记录异常日志 //释放资源 httpclient.Dispose(); return string.Empty; } }
static void Main(string[] args) { encoding = Encoding.ASCII; SocketServer server; server = new SocketServer(new IPEndPoint(IPAddress.Loopback, 0)); server.Connected += c => { serverClient = new FramedClient(c); // When received is called, bs will contain no more and no less // data than whole packet as sent from client. serverClient.Received += bs => { var msg = encoding.GetString(bs.Array, bs.Offset, bs.Count); msg = "Hello, " + msg + "!"; serverClient.SendPacket(encoding.GetBytes(msg)); }; }; server.Start(); HandleClient(server.BindEndPoint.Port); Console.WriteLine("Press any key to stop..."); Console.ReadKey(); server.Stop(); client.Close(); serverClient.Close(); }
/// <summary> /// Gets the string from the byte array using the specified encoding. /// </summary> /// <param name="data">The data.</param> /// <param name="encoding">The encoding.</param> /// <returns>System.String.</returns> public static string GetString(this byte[] data, Encoding encoding) { Argument.IsNotNull("data", data); Argument.IsNotNull("encoding", encoding); return encoding.GetString(data, 0, data.Length); }
public static string Decode(string contents, Encoding encoding) { if (contents == null) { throw new ArgumentNullException("contents"); } // 替换被编码的内容 string result = Regex.Replace(contents, QpMutiplePattern, new MatchEvaluator(delegate(Match m) { List<byte> buffer = new List<byte>(); // 把匹配得到的多行内容逐个匹配得到后转换成byte数组 MatchCollection matches = Regex.Matches(m.Value, QpSinglePattern, RegexOptions.IgnoreCase | RegexOptions.Compiled); foreach (Match match in matches) { buffer.Add((byte)HexToByte(match.Groups[2].Value.Trim())); } return encoding.GetString(buffer.ToArray()); }), RegexOptions.IgnoreCase | RegexOptions.Compiled); // 替换多余的链接=号 result = Regex.Replace(result, @"=\s+", ""); return result; }
/// <inheritdoc/> public string ConvertBinaryToString(Encoding encoding, byte[] buffer) { Requires.NotNull(encoding, "encoding"); Requires.NotNull(buffer, "buffer"); return encoding.GetString(buffer, 0, buffer.Length); }
public string ReadTextFileContent(string filePath, Encoding encoding = null) { string fileContent = ""; using (var filestream = new FileStream(filePath, FileMode.Open)) { if (filestream.Length < 1) { throw new Exception("File is empty!"); } using (var reader = new System.IO.BinaryReader(filestream, Encoding.ASCII)) { var binData = reader.ReadBytes((int) filestream.Length); fileContent = encoding != null ? encoding.GetString(binData) : Encoding.UTF8.GetString(binData); if (StreamHelper.IsBinary(fileContent)) { throw new Exception("File is not a recognized text file"); } } } return fileContent; }
public static string ConvertEncoding(string srcStr, Encoding srcEnc, Encoding destEnc) { byte[] bytes = srcEnc.GetBytes(srcStr); bytes = Encoding.Convert(srcEnc, destEnc, bytes); return destEnc.GetString(bytes); }
private static string ConvertStringEncoding(Encoding encodingFrom, Encoding encodingTo, string content) { byte[] fromBytes = encodingFrom.GetBytes(content); byte[] toBytes = Encoding.Convert(encodingFrom, encodingTo, fromBytes); string converted = encodingTo.GetString(toBytes); return converted; }
/// <summary> /// Returns the content of the stream as a string /// </summary> /// <param name="ms"></param> /// <param name="encoding"></param> /// <returns></returns> public static string AsString(this MemoryStream ms, Encoding encoding = null) { if (encoding == null) encoding = Encoding.Unicode; return encoding.GetString(ms.ToArray()); }
private static Dictionary<string, string> ReadItemFields(string[] tags, BinaryReader databaseReader, Encoding encoding) { var dictionary = new Dictionary<string, string>(); // Loop over the fields. for (; ; ) { byte tagIndex = databaseReader.ReadByte(); if (tagIndex == 0xFF) break; // TODO: Or we could index the dictionary by tag index and do this later. string tagName = tags[tagIndex]; byte tagLength = databaseReader.ReadByte(); byte[] tagData = databaseReader.ReadBytes(tagLength); string tagValue = encoding.GetString(tagData); dictionary.Add(tagName, tagValue); // TODO: If we don't find an FF, this item is incorrectly terminated. } return dictionary; }
public string GetContents(Encoding enc) { var buffer = new byte[mem.Length]; mem.Position = 0; mem.Read(buffer, 0, buffer.Length); return enc.GetString(buffer, 0, buffer.Length); }
/// <summary> /// 从16进制转换成汉字,请勿按字节调用 /// </summary> /// <param name="hex"></param> /// <returns></returns> public static string GetChsFromHex(string hex) { if (hex == null) { throw new ArgumentNullException("hex not found"); } if (hex.Length <= 6) { throw new ArgumentException("请勿按字节调用该函数,请至少传入两个hex"); } if (hex.Length % 2 != 0) { hex += "20"; //空格 //throw new ArgumentException("hex is not a valid number!", "hex"); } hex = hex.Replace("&#x", "").Replace(";", ""); // 需要将 hex 转换成 byte 数组。 byte[] bytes = new byte[hex.Length / 2]; for (int i = 0; i < bytes.Length; i++) { try { // 每两个字符是一个 byte。 bytes[i] = byte.Parse(hex.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber); } catch { // Rethrow an exception with custom message. throw new ArgumentException("hex is not a valid hex number!", "hex"); } } // 获得 UTF-8,Chinese Simplified。 System.Text.Encoding chs = System.Text.Encoding.GetEncoding(codingType); return(chs.GetString(bytes)); }
private void Convert_val_Click(object sender, EventArgs e) { if (number.Text == null) { MessageBox.Show("Write Some values in First Box"); } else { string your_number = number.Text; int num = int.Parse(your_number); string hexValue = num.ToString("X4"); // int num2 = int.Parse(hexValue); string[] hex = hexValue.Split(); List <string> temp = new List <string>(); //foreach (string element in hex) // temp.Add(Convert.ToString(Convert.ToInt32(element, 16), 2)); //hexValue=string.Join("",temp); //int[] list = { 350, 290, 10 }; System.Text.Encoding encoding = System.Text.Encoding.Unicode; byte [] bytes = BitConverter.GetBytes(num); var result = encoding.GetString(BitConverter.GetBytes(num)); inUnicode.Text = string.Join("", result); //var utf_result = Convert.ToUInt16(result).ToString("X4"); string convertedUtf8 = Encoding.UTF8.GetString(bytes); char ch = (char)num; byte[] bytes_2 = Encoding.UTF8.GetBytes(new[] { ch }); foreach (byte c in bytes_2) { temp.Add(c.ToString("X2")); } inUTF8.Text = string.Join(" ", temp); } }
public static string Decrypt(string strText, string sDecrKey) { //------------------------------------------------------------------------ //Decryption algorithm code //------------------------------------------------------------------------ byte[] byKey = { }; byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef }; byte[] inputByteArray = new byte[strText.Length + 1]; strText = Microsoft.VisualBasic.Strings.Replace(strText, " ", "+"); try { byKey = System.Text.Encoding.UTF8.GetBytes(Microsoft.VisualBasic.Strings.Left(sDecrKey, 8)); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); inputByteArray = Convert.FromBase64String(strText); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); System.Text.Encoding encoding = System.Text.Encoding.UTF8; return(encoding.GetString(ms.ToArray())); } catch (Exception ex) { return(ex.Message); } }
internal static object UnmarshalStrses(Stream stream) { StringBuilder sb = new StringBuilder(); int flags = ReadByte(stream); System.Text.Encoding enc = System.Text.Encoding.GetEncoding( (flags & 0x1) != 0 ? "utf-8" : "iso-8859-1"); do { BoxTag part_tag = (BoxTag)ReadByte(stream); if (part_tag != BoxTag.DV_STRING && part_tag != BoxTag.DV_SHORT_STRING_SERIAL) { throw new SystemException( "Invalid data (tag=" + part_tag + ") in deserializing a string session"); } int n = (part_tag == BoxTag.DV_STRING) ? UnmarshalLongInt(stream) : ReadByte(stream); if (n > 0) { byte [] buffer = new byte[n]; for (int ofs = stream.Read(buffer, 0, n); ofs != n; ofs += stream.Read(buffer, ofs, n - ofs)) { ; } sb.Append(enc.GetString(buffer)); } else { break; } }while (true); return(sb.ToString()); }
public static bool FromBase64String(System.Text.Encoding encoding, string encodedText, out string decodedText) { if (encodedText == null) { decodedText = null; return(false); } try { byte[] textAsBytes = Convert.FromBase64String(encodedText); decodedText = encoding.GetString(textAsBytes); return(true); } catch (Exception) { decodedText = null; return(false); } }
/// <summary> /// 获取中文验证码字符串 /// </summary> /// <returns></returns> private string GetCnCodeString() { // 获取编码 System.Text.Encoding encoding = System.Text.Encoding.Default; // 产生随机中文汉字编码 object[] bytes = CreateCnCode(); string[] str = new string[Configer.CharNum]; System.Text.StringBuilder sb = new System.Text.StringBuilder(); for (int i = 0; i < Configer.CharNum; i++) { // 根据汉字编码的字节数组解码出中文汉字 str[i] = encoding.GetString((byte[])Convert.ChangeType(bytes[i], typeof(byte[]))); sb.Append(str[i].ToString()); } return(sb.ToString()); }
public static string ReadFileContentByID(int clickedFile) //GetFile from database by ID, unzip content { using (var db = new FilestorageContext()) { List <FileStorage> selectedFileRow = db.FileStorages.Where(x => x.Id == clickedFile).ToList(); byte[] content = selectedFileRow.FirstOrDefault().content; //Unzip content if it zipped Stream checkedZipStream = new MemoryStream(content); if (ZipFile.IsZipFile(checkedZipStream, false)) { content = UnzipContent(content); } System.Text.Encoding enc = System.Text.Encoding.UTF8; string selectedFile = enc.GetString(content); return(selectedFile); } }
private string file_get_contents(string url, System.Text.Encoding encode) { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); WebResponse response = request.GetResponse(); using (MemoryStream ms = new MemoryStream()) { using (Stream stream = response.GetResponseStream()) { int readc; byte[] buffer = encode.GetBytes(url);// new byte[1024]; while ((readc = stream.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, readc); } } return(encode.GetString(ms.ToArray())); } }
// decryption public string Decrypt(string stringToDecrypt, string sEncryptionKey) { byte[] inputByteArray = new byte[stringToDecrypt.Length]; try { key = System.Text.Encoding.UTF8.GetBytes(sEncryptionKey); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); inputByteArray = Convert.FromBase64String(stringToDecrypt); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); System.Text.Encoding encoding = System.Text.Encoding.UTF8; return(encoding.GetString(ms.ToArray())); } catch (Exception e) { return(e.Message); } }
private static string ReadStreamFile(HttpWebResponse resp) { const int CHUNKSIZE = 8192; StringBuilder s = new StringBuilder(); using (Stream strm = resp.GetResponseStream()) { byte[] bts = new byte[CHUNKSIZE]; for ( ; ;) { int nRead = strm.Read(bts, 0, CHUNKSIZE); if (nRead == 0) { break;// EOF } System.Text.Encoding enc = System.Text.Encoding.ASCII; s.Append(enc.GetString(bts, 0, nRead)); } } return(s.ToString()); }
/* * public void BuildApproverStage(String DN) * { * * DN = rtnData(DN); * * List<String> sup = new List<string>(); * dApprover adp = null; * String LocalDN = DN; * * * System.Data.SqlClient.SqlConnection cn = new System.Data.SqlClient.SqlConnection(db); * System.Data.SqlClient.SqlCommand cmd; * System.Data.SqlClient.SqlDataReader dr; * * System.Data.DataSet gData = new System.Data.DataSet(); * * try * { * * cn.Open(); * * cmd = new System.Data.SqlClient.SqlCommand("Select * from cmr_sup", cn); * cmd.CommandTimeout = 0; * cmd.CommandType = System.Data.CommandType.Text; * * dr = cmd.ExecuteReader(); * * if (dr.HasRows) * { * dr.Read(); * * do * { * sup.Add(dr["sup_email"].ToString()); * } * while(dr.Read()); * * int breakpoint = 5; * int i = 0; * * do * { * * adp = BuildApprovers(LocalDN, i); * if (sup.Find(delegate(String a) { return a.ToLower() == adp.Email.ToString().ToLower(); }) == null) * { * if (DN != LocalDN) // This is to make sure that requester isn't an approver * { * dApp.Add(adp); * } * i++; * * LocalDN = adp.ManagerDist; * if (this.ADError != "") * { * break; * * } * } * else * break; * * * }while(i<breakpoint|| LocalDN==""); * * } * } * catch (System.Data.SqlClient.SqlException ex) * { * this.ADError = ex.Message; * } * catch(Exception ex) * { * this.ADError = ex.Message; * } * finally * { * if (cn.State == System.Data.ConnectionState.Open) * cn.Close(); * } * * } * */ /* * private dApprover BuildApprovers(String DN,int step) * { * * dApprover d = new dApprover(); * * System.Collections.DictionaryEntry x; * DirectorySearcher ds = null; * * * * DirectoryEntry de = new DirectoryEntry(this.ADDomain); * int DataLevel = 0; * ds = BuildUserSearcher(de); * * ds.Filter = "(&(objectCategory=User)(distinguishedname=" + DN + "))"; * SearchResult sr; * * * sr = ds.FindOne(); * * if (sr != null) * { * * try * { * if (sr.Properties["samaccountname"].Count > 0) * { * d.NTID = rtnData(sr.Properties["samaccountname"][0]); * DataLevel++; * } * else * throw new Exception(); * * if (sr.Properties["name"].Count > 0) * { * d.Name = rtnData(sr.Properties["name"][0]); * DataLevel++; * } * else * throw new Exception(); * * * //if (Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["debug"].ToString())) * //{ * // d.Email = System.Configuration.ConfigurationManager.AppSettings["DistEmail"].ToString(); * // DataLevel++; * //} * //else * //{ * if (sr.Properties["targetaddress"].Count > 0) * { * d.Email = rtnData(sr.Properties["targetaddress"][0]); * DataLevel++; * } * else if (sr.Properties["mail"].Count > 0) * { * d.Email = rtnData(sr.Properties["mail"][0]); * DataLevel++; * } * else * throw new Exception(); * * //} * * * * if (sr.Properties["title"].Count > 0) * { * d.Title = rtnData(sr.Properties["title"][0]); * DataLevel++; * } * else * d.Title = "Not provided"; // throw new Exception(); * * * if (sr.Properties["manager"].Count > 0) * { * d.ManagerDist = rtnData(sr.Properties["manager"][0]); * DataLevel++; * } * else * { * if (d.Email.ToLower() == System.Configuration.ConfigurationManager.AppSettings["SEOEMail"].ToString()|| Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["debug"].ToString())) * { * d.ManagerDist = ""; * } * else * throw new Exception(); * } * * * d.Step = step.ToString(); * * } * catch (Exception ex) * { * switch (DataLevel) * { * case 0: * this.ADError = "Manager (" + DN + "} is missing <b>samaccountname</b> in Active Directory"; * break; * case 1: * this.ADError = "Manager (" + d.NTID + "} is missing <b>Name</b> in Active Directory"; * break; * case 2: * this.ADError = "Manager (" + d.NTID + "} is missing <b>TargetAddress or Email</b> in Active Directory"; * break; * case 3: * this.ADError = "Manager (" + d.NTID + "} is missing <b>title</b> in Active Directory"; * break; * case 4: * this.ADError = "Manager (" + d.NTID + "} is missing <b>manager</b> in Active Directory"; * break; * * } * * } * } * else * { * this.ADError = "Approver (" + DN + ") is missing from Active Directory"; * * } * * * return d; * } */ private String rtnData(object value) { String rtn = String.Empty; System.Text.Encoding enc = System.Text.Encoding.ASCII; //object value = ((ResultPropertyValueCollection)p.Value)[0]; if (value is System.Byte[]) { rtn = enc.GetString((byte[])value); } else { rtn = value.ToString(); } rtn = rtn.Replace("SMTP:", ""); return(rtn); }
/// <summary> /// 类测试 /// </summary> public static void Test() { System.Text.Encoding utf8 = System.Text.Encoding.UTF8; //key为abcdefghijklmnopqrstuvwx的Base64编码 byte[] key = Convert.FromBase64String("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4"); byte[] iv = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; //当模式为ECB时,IV无用 byte[] data = utf8.GetBytes("中国ABCabc123"); System.Console.WriteLine("ECB模式:"); byte[] str1 = Des3Util.Des3EncodeECB(key, iv, data); byte[] str2 = Des3Util.Des3DecodeECB(key, iv, str1); System.Console.WriteLine(Convert.ToBase64String(str1)); System.Console.WriteLine(System.Text.Encoding.UTF8.GetString(str2)); System.Console.WriteLine(); System.Console.WriteLine("CBC模式:"); byte[] str3 = Des3Util.Des3EncodeCBC(key, iv, data); byte[] str4 = Des3Util.Des3DecodeCBC(key, iv, str3); System.Console.WriteLine(Convert.ToBase64String(str3)); System.Console.WriteLine(utf8.GetString(str4)); System.Console.WriteLine(); }
//接收数据并修改部分数据然后发送回去 void sender_ReceiveData(IDataTransmit sender, NetEventArgs e) { string result; try { byte[] data = (byte[])e.EventArg; var json = encode.GetString(data); result = CRL.CacheServer.CacheService.Deal(json); } catch (Exception ex) { Log("处理数据出错:" + ex.Message); result = "error,服务器内部错误:" + ex.Message; } //发送数据 var data2 = encode.GetBytes(result); sender.Send(data2); }
/// <summary> /// AES解密 /// </summary> /// <param name="contentstring">base64</param> /// <param name="encoding">编码格式</param> /// <param name="key">密钥</param> /// <returns></returns> public static string DeAESbyKey(string contentstring, System.Text.Encoding encoding, string key) { byte[] content = ConvertBase64ToBytes(contentstring); byte[] enCodeFormat = Convert.FromBase64String(key); using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider()) { aesProvider.Key = enCodeFormat; aesProvider.Mode = CipherMode.ECB; aesProvider.Padding = PaddingMode.PKCS7; using (ICryptoTransform cryptoTransform = aesProvider.CreateDecryptor()) { byte[] inputBuffers = content; byte[] results = cryptoTransform.TransformFinalBlock(inputBuffers, 0, inputBuffers.Length); aesProvider.Clear(); return(encoding.GetString(results)); } } }
private string DecryptWithByteArray(string strText, string strEncrypt) { try { byte[] tmpKey = new byte[20]; tmpKey = System.Text.Encoding.UTF8.GetBytes(strEncrypt.Substring(0, 8)); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); Byte[] inputByteArray = inputByteArray = Convert.FromBase64String(strText); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(tmpKey, mInitializationVector), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); System.Text.Encoding encoding = System.Text.Encoding.UTF8; return(encoding.GetString(ms.ToArray())); } catch (Exception ex) { throw ex; } }
private string Decrypt(string strText, string strEncrypt) { byte[] bKey = new byte[20]; byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; try { bKey = System.Text.Encoding.UTF8.GetBytes(strEncrypt.Substring(0, 8)); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); Byte[] inputByteArray = inputByteArray = Convert.FromBase64String(strText); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(bKey, IV), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); System.Text.Encoding encoding = System.Text.Encoding.UTF8; return(encoding.GetString(ms.ToArray())); } catch (Exception ex) { throw ex; } }
public string Decrypt(string encryptedText) { string key = "jdsg432387#"; byte[] DecryptKey = { }; byte[] IV = { 55, 34, 87, 64, 87, 195, 54, 21 }; byte[] inputByte = new byte[encryptedText.Length]; DecryptKey = System.Text.Encoding.UTF8.GetBytes(key.Substring(0, 8)); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); inputByte = Convert.FromBase64String(encryptedText); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(DecryptKey, IV), CryptoStreamMode.Write); cs.Write(inputByte, 0, inputByte.Length); cs.FlushFinalBlock(); System.Text.Encoding encoding = System.Text.Encoding.UTF8; return(encoding.GetString(ms.ToArray())); }
public string GetHtml(string url) { using (System.Net.WebClient client = new System.Net.WebClient()) { client.Headers.Add( "User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; Touch; rv:11.0) like Gecko"); System.IO.Stream srmBuff = client.OpenRead(url); Byte[] bytBuff = {}; using (System.IO.MemoryStream srmMemory = new System.IO.MemoryStream()) { Byte[] bytRead = { }; int intRead = 0; Array.Resize(ref bytRead, 1024); intRead = srmBuff.Read(bytRead, 0, bytRead.Length); do { srmMemory.Write(bytRead, 0, intRead); intRead = srmBuff.Read(bytRead, 0, bytRead.Length); } while (intRead > 0); bytBuff = srmMemory.ToArray(); } srmBuff.Close(); System.Text.Encoding enc = GetCode(bytBuff); if (enc == null) { enc = System.Text.Encoding.ASCII; } string html = enc.GetString(bytBuff); return(html); } }
/// <summary> /// 从base64编码的字符串中还原字符串,支持中文 /// </summary> /// <param name="base64String">base64加密后的字符串</param> /// <param name="ens">System.Text.Encoding 对象,如创建中文编码集对象:System.Text.Encoding.GetEncoding(54936)</param> /// <returns>还原后的文本字符串</returns> public static string DecodingForString(string base64String, System.Text.Encoding ens = null) { /** * *********************************************************** * * 从base64String中取得的字节值为字符的机内码(ansi字符编码) * 一般的,用机内码转换为汉字是公式: * (char)(第一字节的二进制值*256+第二字节值) * 而在c#中的char或string由于采用了unicode编码,就不能按照上面的公式计算了 * ansi的字节编和unicode编码不兼容 * 故利用.net类库提供的编码类实现从ansi编码到unicode代码的转换 * * GetEncoding 方法依赖于基础平台支持大部分代码页。但是,对于下列情况提供系统支持:默认编码,即在执行此方法的计算机的区域设置中指定的编码;Little- Endian Unicode (UTF-16LE);Big-Endian Unicode (UTF-16BE);Windows 操作系统 (windows-1252);UTF-7;UTF-8;ASCII 以及 GB18030(简体中文)。 * *指定下表中列出的其中一个名称以获取具有对应代码页的系统支持的编码。 * * 代码页 名称 * 1200 “UTF-16LE”、“utf-16”、“ucs-2”、“unicode”或“ISO-10646-UCS-2” * 1201 “UTF-16BE”或“unicodeFFFE” * 1252 “windows-1252” * 65000 “utf-7”、“csUnicode11UTF7”、“unicode-1-1-utf-7”、“unicode-2-0-utf-7”、“x- unicode-1-1-utf-7”或“x-unicode-2-0-utf-7” * 65001 “utf-8”、“unicode-1-1-utf-8”、“unicode-2-0-utf-8”、“x-unicode-1-1-utf-8”或“x-unicode-2-0-utf-8” * 20127 “us-ascii”、“us”、“ascii”、“ANSI_X3.4-1968”、“ANSI_X3.4-1986”、“cp367”、 “csASCII”、“IBM367”、“iso-ir-6”、“ISO646-US”或“ISO_646.irv:1991” * 54936 “GB18030” * * 某些平台可能不支持特定的代码页。例如,Windows 98 的美国版本可能不支持日语 Shift-jis 代码页(代码页 932)。这种情况下,GetEncoding 方法将在执行下面的 C# 代码时引发 NotSupportedException: * * Encoding enc = Encoding.GetEncoding("shift-jis"); * * **************************************************************/ //从base64String中得到原始字符 try { ens = ens ?? (ens = System.Text.Encoding.GetEncoding(54936)); return(ens.GetString(Convert.FromBase64String(base64String))); } catch { return(base64String); } }
public static string LoadContentFromFile(string _path) { string fileContents = string.Empty; System.Text.Encoding encoding = null; FileInfo _file = new FileInfo(_path); using (FileStream fs = _file.OpenRead()) { Ude.CharsetDetector cdet = new Ude.CharsetDetector(); cdet.Feed(fs); cdet.DataEnd(); if (cdet.Charset != null) { encoding = System.Text.Encoding.GetEncoding(cdet.Charset); } else { encoding = System.Text.Encoding.UTF8; } fs.Position = 0; byte[] ar = new byte[_file.Length]; fs.Read(ar, 0, ar.Length); fileContents = encoding.GetString(ar); } if (fileContents.StartsWith("")) { fileContents = fileContents.Substring(3); } if (encoding != System.Text.Encoding.UTF8) { var datas = System.Text.Encoding.UTF8.GetBytes(fileContents); fileContents = System.Text.Encoding.UTF8.GetString(datas); } return(fileContents); }
private string ReadLine(System.Text.Encoding enc) { byte [] serverbuff = new Byte[1024]; System.Net.Sockets.NetworkStream stream = GetStream(); int count = 0; byte [] buff = new Byte[2]; while (true) { int bytes = stream.Read(buff, 0, 1); if (bytes == 1) { if (buff[0] != '\r' && buff[0] != '\n') { serverbuff[count++] = buff[0]; } if (buff[0] == '\n') { break; } if (count > 1000 && buff[0] != '\r') { break; } } else { break; } } ; string sLine = enc.GetString(serverbuff, 0, count); #if DEBUG ///Console.WriteLine(sLine); #endif return(sLine); }
//base64字符串解密为字符串,本类型:解密-(加密base64替换的数据) public static string AfterDecodeRspace(string base64string, System.Text.Encoding encode = null) { var abase64 = Convert.FromBase64String(CsharpLazycode.Module.base64.Util.AfterDecode(base64string)); string nobase64string = ""; try { if (encode == null) { encode = System.Text.Encoding.UTF8; } nobase64string = encode.GetString(abase64); } catch (Exception ex) { Console.WriteLine(string.Format("异常[{0}] [{1}]:{2}", System.Reflection.MethodBase.GetCurrentMethod().ReflectedType.FullName, System.Reflection.MethodBase.GetCurrentMethod().Name, ex.Message)); } return(nobase64string); }
public static string decryptPass(string str1) { str1 = str1.Replace(" ", "+"); string DecryptKey = "2013;[pnuLIT)WebCodeExpert"; byte[] byKey = { }; byte[] IV = { 18, 52, 86, 120, 144, 171, 205, 239 }; byte[] inputByteArray = new byte[str1.Length]; byKey = System.Text.Encoding.UTF8.GetBytes(DecryptKey.Substring(0, 8)); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); inputByteArray = Convert.FromBase64String(str1.Replace(" ", "+")); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); System.Text.Encoding encoding = System.Text.Encoding.UTF8; return(encoding.GetString(ms.ToArray())); }
public string Gethid() { try { var loader = new HidDeviceLoader(); var device = loader.GetDevices(0X045E, 0X00DB).First(); HidStream stream; device.TryOpen(out stream); string sendme = "<STX>'W'<ETX>"; System.Text.Encoding enc = System.Text.Encoding.ASCII; byte[] messagebyte = enc.GetBytes(sendme); stream.Write(messagebyte); byte[] fromscale = stream.Read(); string returnedmessage = enc.GetString(fromscale); return(returnedmessage); } catch (Exception e) { return("false"); } }
public static string JieMi(string strText) { Byte[] byKey64 = { 10, 20, 30, 37, 50, 60, 70, 80 }; Byte[] Iv64 = { 11, 22, 33, 44, 52, 66, 77, 85 }; Byte[] inputByteArray = new byte[strText.Length]; try { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); inputByteArray = Convert.FromBase64String(strText); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey64, Iv64), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); System.Text.Encoding encoding = System.Text.Encoding.UTF8; return(encoding.GetString(ms.ToArray())); } catch (Exception ex) { return(ex.Message); } }
/// <summary> /// 十六进制转汉字 /// </summary> /// <param name="hex"></param> /// <returns></returns> public static string hexToChainCode(string hex) //16进制转汉字 { // 需要将 hex 转换成 byte 数组。 byte[] bytes = new byte[hex.Length / 2]; for (int i = 0; i < bytes.Length; i++) { try { // 每两个字符是一个 byte。 bytes[i] = byte.Parse(hex.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber); } catch (Exception msg) { Log.LogWrite(msg); } } // 获得 GB2312,Chinese Simplified。 System.Text.Encoding chs = System.Text.Encoding.GetEncoding("GB2312"); return(chs.GetString(bytes)); }
/// <summary> /// バイト配列から文字列、文字列からバイト配列に変換し、文字コードを判別します。 /// </summary> /// <param name="srcBytes">文字コードを判別するバイト配列</param> /// <param name="encoding">変換する文字コード</param> /// <returns><paramref name="srcBytes"/> から文字コードが判定できた場合は true</returns> private static bool DetectEncoding(byte[] srcBytes, System.Text.Encoding encoding) { string encodedStr = encoding.GetString(srcBytes); byte[] encodedByte = encoding.GetBytes(encodedStr); if (srcBytes.Length != encodedByte.Length) { return(false); } for (int i = 0; i < srcBytes.Length; i++) { if (srcBytes[i] != encodedByte[i]) { return(false); } } return(true); }
// // Summary: // Persists all updates to the data source with the specified System.Data.Objects.SaveOptions. // // Parameters: // options: // A System.Data.Objects.SaveOptions value that determines the behavior of the // operation. // // Returns: // The number of objects in an System.Data.EntityState.Added, System.Data.EntityState.Modified, // or System.Data.EntityState.Deleted state when System.Data.Objects.ObjectContext.SaveChanges() // was called. // // Exceptions: // System.Data.OptimisticConcurrencyException: // An optimistic concurrency violation has occurred. //public new int SaveChanges(SaveOptions options)//3 //{ // return SaveChanges_Helper(1, true, options); //} //#region PropertyInfo //private static PropertyInfo GetPropertyInfo(Type classType, String propertyName) //{ // PropertyInfo info = classType.GetProperty(propertyName); // return info; //} //private static PropertyInfo[] GetPropertiesInfo(Type classType) //{ // PropertyInfo[] infos = classType.GetProperties(); // return infos; //} //private static PropertyInfo GetPropertyInfo(String fullClassTypeName, String propertyName) //{ // Type type = Type.GetType(fullClassTypeName); // return GetPropertyInfo(type, propertyName); //} //private static PropertyInfo[] GetPropertiesInfo(String fullClassTypeName) //{ // Type type = Type.GetType(fullClassTypeName); // return GetPropertiesInfo(type); //} //#endregion //#region GetPropertyValue //private static object GetPropertyValue(object objectToGet, string propertyName) //{ // Type objectType = objectToGet.GetType(); // PropertyInfo propertyInfo = objectType.GetProperty(propertyName); // object propertyValue = null; // if ((propertyInfo != null) && (propertyInfo.CanRead)) // { // propertyValue = propertyInfo.GetValue(objectToGet, null); // } // return propertyValue; //} //private static TResult GetPropertyValue<TResult>(object objectToGet, string propertyName) //{ // Type objectType = objectToGet.GetType(); // PropertyInfo info = objectType.GetProperty(propertyName); // object value = null; // if ((info != null) && (info.CanRead)) // { // value = info.GetValue(objectToGet, null); // } // return (TResult)value; //} //private static void SetProperty(object objectToSet, string propertyName, object propertyValue) //{ // Type objectType = objectToSet.GetType(); // PropertyInfo propertyInfo = objectType.GetProperty(propertyName); // if ((propertyInfo != null) && (propertyInfo.CanWrite)) // propertyInfo.SetValue(objectToSet, propertyValue, null); //} //#endregion //private static PropertyInfo GetPublicInstancePropertyInfoInObjectContext<TObjectContext>(String propertyName) //{ // Type type = typeof(TObjectContext); // //Type type = Type.GetType(fullClassTypeName); // PropertyInfo info = type.GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance); // return info; //} public static string SerializeObjectToXmlString(object obj, System.Text.Encoding encoding) { try { String xmlizedString = null; var memoryStream = new MemoryStream(); var xs = new XmlSerializer(obj.GetType()); var xmlTextWriter = new XmlTextWriter(memoryStream, encoding); xs.Serialize(xmlTextWriter, obj); memoryStream = (MemoryStream)xmlTextWriter.BaseStream; byte[] bytes = memoryStream.ToArray(); xmlizedString = encoding.GetString(bytes, 0, bytes.Length);//ByteArrayUtil.BytesToString(memoryStream.ToArray(), encoding); return(xmlizedString); } catch (Exception ex) { } return(string.Empty); }
// 序列化xml/反序列化 /// <summary> /// 对象序列化为XML /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <param name="encoding"></param> /// <returns></returns> /// <remarks></remarks> public static string ObjectToXML <T>(T obj, System.Text.Encoding encoding) { XmlSerializer ser = new XmlSerializer(obj.GetType()); Encoding utf8EncodingWithNoByteOrderMark = new UTF8Encoding(false); using (MemoryStream mem = new MemoryStream()) { XmlWriterSettings settings = new XmlWriterSettings { OmitXmlDeclaration = true, Encoding = utf8EncodingWithNoByteOrderMark }; using (XmlWriter XmlWriter = XmlWriter.Create(mem, settings)) { XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", ""); ser.Serialize(XmlWriter, obj, ns); return(encoding.GetString(mem.ToArray())); } } }/// <summary>
public string Decrypt(string username, string pass) { string DecryptKey = username; byte[] byKey = { }; byte[] IV = { 18, 52, 86, 120, 144, 171, 205, 239 }; byte[] inputByteArray = new byte[pass.Length]; byKey = System.Text.Encoding.UTF8.GetBytes(DecryptKey.Substring(0, 8)); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); inputByteArray = Convert.FromBase64String(pass); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); System.Text.Encoding encoding = System.Text.Encoding.UTF8; return(encoding.GetString(ms.ToArray())); }