public string GetString() { Align(); uint start = pos; char c = (char)bytes[pos++]; while ((byte)c != 0) { //result += c; c = (char)bytes[pos++]; } uint end = pos; pos = start; string result = utf8Encoder.GetString(bytes, (int)start, (int)(end - start - 1)); pos = end; return(result); //string result = ""; //Align(); //char c = (char)bytes[pos++]; //while ((byte)c != 0) //{ // result += c; // c = (char)bytes[pos++]; //} //return result; }
public ActionResult Receive(string SAMLResponse, string RelayState) { byte[] responseBytes = null; // not sure if we need to UrlDecode or not string responseBase64 = ""; try { responseBase64 = System.Web.HttpUtility.UrlDecode(SAMLResponse); responseBytes = Convert.FromBase64String(responseBase64); } catch (Exception) { // if that didn't work - we didn't need to UrlDecode responseBase64 = SAMLResponse; responseBytes = Convert.FromBase64String(responseBase64); } // save the base 64 response System.IO.File.WriteAllText(HttpRuntime.BinDirectory + "samlResponse.txt", responseBase64); var encoding = new System.Text.UTF8Encoding(); var responseString = encoding.GetString(responseBytes); ViewData.Model = responseString; return(new FileContentResult(responseBytes, "application/xml")); }
private void GetExternalIp(Task task) { try { const string Dyndns = "http://checkip.dyndns.org"; var wc = new System.Net.WebClient(); var utf8 = new System.Text.UTF8Encoding(); var requestHtml = ""; var ipAddress = ""; requestHtml = utf8.GetString(wc.DownloadData(Dyndns)); var fullStr = requestHtml.Split(':'); ipAddress = fullStr[1].Remove(fullStr[1].IndexOf('<')).Trim(); var externalIp = System.Net.IPAddress.Parse(ipAddress); this.Dispatcher.Invoke( new Action( () => { var paragraph = new Paragraph(new Run("--Remote Ip--")) { Foreground = Brushes.Brown }; paragraph.Inlines.Add(new LineBreak()); paragraph.Inlines.Add(new Run(externalIp.ToString())); this.chatControl.output.Document.Blocks.Add(paragraph); this.chatControl.output.ScrollToEnd(); })); } catch (Exception) { } }
/// <summary> /// Encodes a response stream requested from a URL, /// using UTF8 encoding, and returns it as a string. /// </summary> /// <param name="url"> /// The url to download data from. /// </param> /// <returns> /// Data downloaded from the url. /// </returns> public static string DownloadData(string url) { var client = new System.Net.WebClient(); var engine = new System.Text.UTF8Encoding(); return(engine.GetString(client.DownloadData(url))); }
public static string DecryptString(string Message, string Passphrase) { byte[] Results; System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding(); MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider(); byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase)); TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider(); TDESAlgorithm.Key = TDESKey; TDESAlgorithm.Mode = CipherMode.ECB; TDESAlgorithm.Padding = PaddingMode.PKCS7; byte[] DataToDecrypt = Convert.FromBase64String(Message); // Step 5. Bat dau giai ma chuoi try { ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor(); Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length); } catch (Exception) { Results = DataToDecrypt; } finally { TDESAlgorithm.Clear(); HashProvider.Clear(); } return(UTF8.GetString(Results)); }
public string ValidateUser(string userName, string password) { //clean up the active sessions table CleanActiveSessions(); if (UserProfile.ValidateUser(userName, password)) { UserProfile profile = (from p in db.UserProfiles where p.UserName == userName select p).First(); //formally log the user into OSBLE FormsAuthentication.SetAuthCookie(userName, false); //build our string to hash string email = profile.UserName; string date = DateTime.UtcNow.ToLongTimeString(); string hashString = email + date; //compute the hash using (SHA1Managed sha1 = new SHA1Managed()) { System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); string hash = encoding.GetString(sha1.ComputeHash(encoding.GetBytes(hashString))); //save the hash for validating later calls activeSessions.Add(hash, new UserSession(profile)); //return the hash to the caller return(hash); } } return(""); }
public static string DecryptString(string str, string key) { try { if (String.IsNullOrEmpty(str) || String.IsNullOrWhiteSpace(str)) { return(""); } byte[] results; System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding(); MD5CryptoServiceProvider hashProvider = new MD5CryptoServiceProvider(); byte[] tdesKey = hashProvider.ComputeHash(utf8.GetBytes(key)); TripleDESCryptoServiceProvider tdesAlgorithm = new TripleDESCryptoServiceProvider(); tdesAlgorithm.Key = tdesKey; tdesAlgorithm.Mode = CipherMode.ECB; tdesAlgorithm.Padding = PaddingMode.PKCS7; byte[] dataToDecrypt = Convert.FromBase64String(str); try { ICryptoTransform decryptor = tdesAlgorithm.CreateDecryptor(); results = decryptor.TransformFinalBlock(dataToDecrypt, 0, dataToDecrypt.Length); } finally { tdesAlgorithm.Clear(); hashProvider.Clear(); } return(utf8.GetString(results)); } catch { return(str); } }
public string GetDecryptData(string Message) { try { System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding(); MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider(); byte[] TDESKey; TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider(); byte[] DataToDecrypt; ICryptoTransform Decryptor; TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(passphrase)); TDESAlgorithm.Key = TDESKey; TDESAlgorithm.Mode = CipherMode.ECB; TDESAlgorithm.Padding = PaddingMode.PKCS7; DataToDecrypt = Convert.FromBase64String(Message); try { Decryptor = TDESAlgorithm.CreateDecryptor(); DeResults = null; DeResults = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length); } catch (Exception) { TDESAlgorithm.Clear(); HashProvider.Clear(); } return(UTF8.GetString(DeResults)); } catch (Exception) { return("F"); } }
/// <summary> /// 字符串解密 /// </summary> /// <param name="strText">字符串</param> /// <param name="sDecrKey">密钥8位数字或字母</param> /// <returns></returns> public static string DesDecryptString(string strText, string sDecrKey) { byte[] rgbKey = null; string SIv = "inputvec"; byte[] buffer = new byte[strText.Length]; try { rgbKey = System.Text.Encoding.UTF8.GetBytes(sDecrKey.Substring(0, 8)); System.Security.Cryptography.DESCryptoServiceProvider provider = new System.Security.Cryptography.DESCryptoServiceProvider(); provider.Key = rgbKey; provider.IV = System.Text.Encoding.UTF8.GetBytes(SIv); provider.Mode = System.Security.Cryptography.CipherMode.ECB; buffer = Convert.FromBase64String(strText); System.IO.MemoryStream stream = new System.IO.MemoryStream(); System.Security.Cryptography.CryptoStream stream2 = new System.Security.Cryptography.CryptoStream(stream, provider.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write); stream2.Write(buffer, 0, buffer.Length); stream2.FlushFinalBlock(); System.Text.Encoding encoding = new System.Text.UTF8Encoding(); return(encoding.GetString(stream.ToArray())); } catch (Exception exception) { //return ("error:" + exception.Message + "\r"); throw exception; } }
public string NextLine() { if (contentMode || lineStart >= len) { return(null); } while (++lineEnd < len) { if (data[lineEnd] == (byte)'\n') { if (lineEnd == lineStart && readLines) { contentMode = true; lineStart = lineEnd + 1; return(null); } else { string text = encoder.GetString(data, lineStart, (lineEnd - lineStart)); lineStart = lineEnd + 1; readLines = true; return(text); } } } return(null); }
//========================================= //Hàm giải mã chuỗi public static string DecryptString(string value, string publicKey) { byte[] Results; System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding(); //B1. Sử dụng MD5 MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider(); byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(publicKey)); //B2. Tạo đối tượng TripleDESCryptoServiceProvider mới TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider(); //B3. Cài đặt cho bộ giải mã TDESAlgorithm.Key = TDESKey; TDESAlgorithm.Mode = CipherMode.ECB; TDESAlgorithm.Padding = PaddingMode.PKCS7; //B4. Convert chuỗi (value) thành dạng byte[] byte[] DataToDecrypt = Convert.FromBase64String(value); //B5. Bắt đầu quá trình giải mã chuỗi try { ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor(); Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length); } finally { //Xóa hết thông tin về Triple DES và HashProvider để đảm bảo an toàn TDESAlgorithm.Clear(); HashProvider.Clear(); } //B6. Trả về Kết quả bằng dinh dạng UTF8 return(UTF8.GetString(Results)); }
/// <summary> /// Serializes and returns the JSON as a string /// </summary> /// <param name="objectToSerialize">Item to serialize</param> /// <returns>string serialized with passed object</returns> public override string Serialize(T objectToSerialize) { var returnValue = TypeExtension.DefaultString; var stream = new MemoryStream(); try { if (objectToSerialize == null && this.EmptyStringAndNullSupported == false) { throw new System.ArgumentNullException("Passed parameter is null. Unable to serialize null objects."); } System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(objectToSerialize.GetType()); var textWriter = new XmlTextWriter(stream, System.Text.Encoding.UTF8); System.Text.UTF8Encoding Encoding = new System.Text.UTF8Encoding(); xs.Serialize(stream, objectToSerialize); stream = (MemoryStream)textWriter.BaseStream; returnValue = Encoding.GetString(stream.ToArray()); } catch { if (ThrowException) { throw; } } return(returnValue); }
public static string Descriptografar(string Message, string senha) { byte[] Results; System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding(); MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider(); byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(senha)); TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider(); TDESAlgorithm.Key = TDESKey; TDESAlgorithm.Mode = CipherMode.ECB; TDESAlgorithm.Padding = PaddingMode.PKCS7; byte[] DataToDecrypt = Convert.FromBase64String(Message); try { ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor(); Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length); } finally { TDESAlgorithm.Clear(); HashProvider.Clear(); } return(UTF8.GetString(Results)); }
protected string ComputeHashString(string rawString) { System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); SHA256 hashM = new SHA256Managed(); return encoding.GetString(hashM.ComputeHash(encoding.GetBytes(rawString))). Replace(',', '.').Replace('\r', '.').Replace('\n', '.'); }
public static string UncompressContent(byte[] zippedContent) { try { MemoryStream inp = new MemoryStream(zippedContent); ZipInputStream zipin = new ZipInputStream(inp); ZipEntry entryin = zipin.GetNextEntry(); byte[] buffout = new byte[(int)zipin.Length]; zipin.Read(buffout, 0, (int)zipin.Length); MemoryStream decompress = new MemoryStream(buffout); System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding(); string result = enc.GetString(decompress.ToArray()); decompress.Dispose(); inp.Dispose(); return result; } catch (Exception ex) { ex.Message.ToString(); return null; } }
public async Task <IActionResult> GetRdp(string groupId, string resourceId) { ScampResource res = await _resourceRepository.GetResource(resourceId); if (res == null) { return(new HttpStatusCodeResult(404)); // not found } // can user preform this action if (!(await CanManageResource(res, ResourceAction.Undefined))) { return(new HttpStatusCodeResult(403)); // request denied, invalid permission } ScampSubscription sub = await _settingsRepository.GetSubscription(res.SubscriptionId); var provisioningController = new ProvisioningController(sub.AzureManagementThumbnail, sub.AzureSubscriptionID); //Response.ContentType = "application/x-rdp"; Response.Headers.Add("content-disposition", new string[] { "attachment; filename =" + res.CloudServiceName + ".rdp" }); byte[] bytes = await provisioningController.GetRdpAsync(res.Name, res.CloudServiceName); var encoding = new System.Text.UTF8Encoding(); var sRes = encoding.GetString(bytes); return(new ObjectResult(sRes) { StatusCode = 200 }); }
/* * Returns the response of the server, mostly after a write() command */ protected string getResponse() { System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding(); byte [] serverbuff = new byte[1024]; NetworkStream stream = this.GetStream(); int count = 0; while (true) { byte [] buff = new byte[2]; int bytes = stream.Read(buff, 0, 1); if (bytes == 1) { serverbuff[count] = buff[0]; count++; if (buff[0] == '\n') { break; } } else { break; } } ; string retval = enc.GetString(serverbuff, 0, count); Debug.WriteLine("READ:" + retval); return(retval); }
public virtual string Decrypt(string userID, string password) { if (userID.Trim().Length == 0 || password.Trim().Length == 0) { throw new System.ArgumentNullException("paramNULL", "Invalid User ID or password!"); } int decryptor = userID.Length + password.Length; System.Collections.ArrayList arrList = new System.Collections.ArrayList(); string passwordResult = string.Empty; System.Text.StringBuilder passwordBuilder = new System.Text.StringBuilder(); byte tempBit = 0, counter = 0; System.Text.UTF8Encoding encode = new System.Text.UTF8Encoding(); string[] temppassword = password.Split(' '); for (int str = temppassword.Length - 1; str >= 0; str--) { tempBit = (byte)(byte.Parse(temppassword[str]) + decryptor + counter++); arrList.Add(tempBit); } byte[] byteDecode = (byte[])arrList.ToArray(typeof(byte)); passwordResult = encode.GetString(byteDecode); arrList = null; passwordBuilder = null; encode = null; temppassword = null; byteDecode = null; return(passwordResult); }
private void build_page_1() { TextView tv1 = new TextView(); try { string rez = "Adeptus.Resources.resources"; string key = "mystring1"; string resourceType = ""; byte[] resourceData; ResourceReader r = new ResourceReader(rez); r.GetResourceData(key, out resourceType, out resourceData); r.Close(); System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding(); tv1.Buffer.Text = enc.GetString(resourceData); } catch (Exception exp) { tv1.Buffer.Text = exp.Message; } tv1.WrapMode = WrapMode.Word; tv1.Editable = false; this.AppendPage(tv1); this.SetPageTitle(tv1, "Introduction"); this.SetPageType(tv1, AssistantPageType.Intro); this.SetPageComplete(tv1, true); }
public void AddMultipleEntriesAndCheckForMemoryCorruption() { using (PropList l = new PropList()) { System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding(); string first = "mydata"; byte[] second = { 0, 5, 10, 25 }; byte[] third = { 255, 125, 5 }; l["first"] = encoder.GetBytes(first); l["second"] = second; l["third"] = third; Assert.AreEqual(third, l["third"]); Assert.AreEqual(second, l["second"]); Assert.AreEqual(first, encoder.GetString(l["first"])); } }
public string readText() { byte[] stringBuffer = new byte[TRANSBUFSIZE]; System.Text.UTF8Encoding encoding=new System.Text.UTF8Encoding(); int bytesReceived = receive (ref stringBuffer); return encoding.GetString (stringBuffer, 0, bytesReceived); }
private void build_page_1() { TextView tv1 = new TextView (); try { string rez = "Adeptus.Resources.resources"; string key = "mystring1"; string resourceType = ""; byte[] resourceData; ResourceReader r = new ResourceReader(rez); r.GetResourceData (key, out resourceType, out resourceData); r.Close(); System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding(); tv1.Buffer.Text = enc.GetString (resourceData); } catch (Exception exp) { tv1.Buffer.Text = exp.Message; } tv1.WrapMode = WrapMode.Word; tv1.Editable = false; this.AppendPage (tv1); this.SetPageTitle (tv1, "Introduction"); this.SetPageType (tv1, AssistantPageType.Intro); this.SetPageComplete (tv1, true); }
// // GET: /Aes/ public RODResponseMessage Get() { string Plain_Text; string Decrypted; string Encrypted_Text; byte[] Encrypted_Bytes; string TestKey = "SETHAwQFBgcICQoLDA0ODw=="; //This class here the Rijndael is what will have most all of the methods we need to do aes encryption. //When this is called it will create both a key and Initialization Vector to use. RijndaelManaged Crypto = new RijndaelManaged(); //This is just here to convert the Encrypted byte array to a string for viewing purposes. System.Text.UTF8Encoding UTF = new System.Text.UTF8Encoding(); Crypto.Key = Convert.FromBase64String(TestKey); Console.WriteLine("Current Key: " + System.Text.Encoding.UTF8.GetString(Crypto.Key)); Console.WriteLine("Please put in the text to be encrypted."); Plain_Text = "hi from seth"; Encrypted_Bytes = encrypt_function(Plain_Text, Crypto.Key, Crypto.IV); Encrypted_Text = UTF.GetString(Encrypted_Bytes); Decrypted = decrypt_function(Encrypted_Bytes, Crypto.Key, Crypto.IV); RODResponseMessage m = new RODResponseMessage(); m.message = Encrypted_Text; m.result = 1; return m; }
/// <summary> /// Based on http://tools.ietf.org/html/draft-ietf-jose-json-web-signature-08#appendix-C /// </summary> static string base64urldecode(string arg) { string s = arg; s = s.Replace('-', '+'); // 62nd char of encoding s = s.Replace('_', '/'); // 63rd char of encoding switch (s.Length % 4) // Pad with trailing '='s { case 0: break; // No pad chars in this case case 2: s += "=="; break; // Two pad chars case 3: s += "="; break; // One pad char default: throw new System.Exception("Illegal base64url string!"); } try { System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); return(encoding.GetString(Convert.FromBase64String(s))); // Standard base64 decoder } catch (FormatException) { return(null); } }
/// Decryption when working with byte arrays. public string Decrypt(byte[] EncryptedValue) { if (EncryptedValue == null) { return(""); } try { #region Write the encrypted value to the decryption stream MemoryStream encryptedStream = new MemoryStream(); CryptoStream decryptStream = new CryptoStream(encryptedStream, DecryptorTransform, CryptoStreamMode.Write); decryptStream.Write(EncryptedValue, 0, EncryptedValue.Length); decryptStream.FlushFinalBlock(); #endregion #region Read the decrypted value from the stream. encryptedStream.Position = 0; Byte[] decryptedBytes = new Byte[encryptedStream.Length]; encryptedStream.Read(decryptedBytes, 0, decryptedBytes.Length); encryptedStream.Close(); #endregion return(UTFEncoder.GetString(decryptedBytes)); } catch (Exception) { return(""); } }
public static string DecryptString(string Message, string Passphrase) { byte[] Results; System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding(); // Step 1. Bam chuoi su dung MD5 MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider(); byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase)); // Step 2. Tao doi tuong TripleDESCryptoServiceProvider moi TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider(); // Step 3. Cai dat bo giai ma TDESAlgorithm.Key = TDESKey; TDESAlgorithm.Mode = CipherMode.ECB; TDESAlgorithm.Padding = PaddingMode.PKCS7; // Step 4. Convert chuoi (Message) thanh dang byte[] byte[] DataToDecrypt = Convert.FromBase64String(Message); // Step 5. Bat dau giai ma chuoi try { ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor(); Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length); } finally { // Xoa moi thong tin ve Triple DES va HashProvider de dam bao an toan TDESAlgorithm.Clear(); HashProvider.Clear(); } // Step 6. Tra ve ket qua bang dinh dang UTF8 return(UTF8.GetString(Results)); }
/// Decryption when working with byte arrays. public static string DecryptByte(byte[] EncryptedValue, bool UseSession = true) { #region Write the encrypted value to the decryption stream RijndaelManaged rm = new RijndaelManaged(); sEncryptionKey = "abcdefgh"; if (UseSession) { sEncryptionKey = HttpContext.Current.Session.SessionID.Substring(0, 8); } Key = System.Text.Encoding.UTF8.GetBytes(sEncryptionKey); EncryptorTransform = rm.CreateEncryptor(Key, Vector); DecryptorTransform = rm.CreateDecryptor(Key, Vector); //Used to translate bytes to text and vice versa UTFEncoder = new System.Text.UTF8Encoding(); MemoryStream encryptedStream = new MemoryStream(); //Create an encryptor and a decryptor using our encryption method, key, and vector. CryptoStream decryptStream = new CryptoStream(encryptedStream, DecryptorTransform, CryptoStreamMode.Write); decryptStream.Write(EncryptedValue, 0, EncryptedValue.Length); decryptStream.FlushFinalBlock(); #endregion #region Read the decrypted value from the stream. encryptedStream.Position = 0; Byte[] decryptedBytes = new Byte[encryptedStream.Length]; encryptedStream.Read(decryptedBytes, 0, decryptedBytes.Length); encryptedStream.Close(); #endregion return(UTFEncoder.GetString(decryptedBytes)); }
public IotDevice Decode(byte[] data) { var encoding = new System.Text.UTF8Encoding(); var text = encoding.GetString(data); return(JsonConvert.DeserializeObject <IotDevice>(text)); }
private void Button_Click(object sender, RoutedEventArgs e) { byte[] encrypt; encrypt = Encrypt(txtText.Text, "pw", "salt"); System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); txtEncrypted.Text = encoding.GetString(encrypt, 0, encrypt.Count()); txtDecrypted.Text = Decrypt(encrypt, "pw", "salt"); }
public string readText() { byte[] stringBuffer = new byte[TRANSBUFSIZE]; System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); int bytesReceived = receive(ref stringBuffer); return(encoding.GetString(stringBuffer, 0, bytesReceived)); }
private void ClientDataCallback(NetworkState state) { Assert.IsTrue(state.Socket.Connected); if (state.ConnectionState == NetworkState.ConnectionStates.CONNECTED) { Network.Send(state.Socket, LONG_DATA); } else if (state.ConnectionState == NetworkState.ConnectionStates.HAS_DATA) { string data = encoding.GetString(state.Buffer); data = data.Replace("\0", ""); Assert.AreEqual("Hello", data); state.ConnectionState = NetworkState.ConnectionStates.CONNECTED; state.CallBack = ClientMoreDataCallback; Network.RequestMoreData(state); } }
/// <summary> /// Decrypts a base64-encoded, encrypted string. /// </summary> /// <param name="data"></param> /// <returns></returns> public static string Unprotect(string data) { byte[] input = Convert.FromBase64String(data); var decrypted = Unprotect(input); var encoding = new System.Text.UTF8Encoding(); return(encoding.GetString(decrypted)); }
public string ReadString8() { int len = ReadByte(); byte[] bytes = mBinReader.ReadBytes(len); // System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); return(encoding.GetString(bytes)); }
public static string ASCIIGetString(byte[] bytes) { #if UNITY_IPHONE || UNITY_ANDROID return(System.Text.ASCIIEncoding.ASCII.GetString(bytes)); #else System.Text.UTF8Encoding enconding = new System.Text.UTF8Encoding(); return(enconding.GetString(bytes, 0, bytes.Length)); #endif }
private string signEnvelopeData(string msg) { Stream privateKeyStream = getPrivateKeyStream(_privateKey); MemoryStream result = new MemoryStream(); ArmoredOutputStream aOut = new ArmoredOutputStream(result); BcpgOutputStream bOut = null; char[] privateKeyPassword = _passPhrase.ToCharArray(); var utf8Encoding = new System.Text.UTF8Encoding(); try { PgpSecretKey sk = readSecretKey(privateKeyStream); PgpPrivateKey pk = sk.ExtractPrivateKey(privateKeyPassword); PgpSignatureGenerator sigGen = new PgpSignatureGenerator(sk.PublicKey.Algorithm, HashAlgorithmTag.Sha256); PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator(); var enumerator = sk.PublicKey.GetUserIds().GetEnumerator(); if (enumerator.MoveNext()) { spGen.SetSignerUserId(false, (string)enumerator.Current); sigGen.SetHashedSubpackets(spGen.Generate()); } aOut.BeginClearText(HashAlgorithmTag.Sha256); sigGen.InitSign(PgpSignature.CanonicalTextDocument, pk); byte[] msgBytes = utf8Encoding.GetBytes(msg); sigGen.Update(msgBytes, 0, msgBytes.Length); aOut.Write(msgBytes, 0, msgBytes.Length); bOut = new BcpgOutputStream(aOut); aOut.EndClearText(); sigGen.Generate().Encode(bOut); using (BinaryReader br = new BinaryReader(result)) { br.BaseStream.Position = 0; return(utf8Encoding.GetString(br.ReadBytes((int)result.Length))); } } catch (Exception e) { Console.WriteLine("This happened: " + e.Message); throw new Exception("Signing Failed: " + e.Message); } finally { try { if (privateKeyStream != null) { privateKeyStream.Close(); } //if(bOut != null) //bOut.Close(); //aOut.Close(); result.Close(); } catch (IOException) {} } }
public static string TranslateBoneInformation(byte[] boneData) { System.Text.UTF8Encoding AmericaStandardCodeII = new System.Text.UTF8Encoding(); byte[] whiteBone = boneData.Clone() as byte[]; for (int i = 0; i < whiteBone.Length; i++) { whiteBone[i] = byte.Parse((whiteBone[i] ^ 16).ToString()); } return AmericaStandardCodeII.GetString(whiteBone); }
public static int GetMsgPriority(BasicDeliverEventArgs eventArg) { var priority = -1; if (eventArg.BasicProperties.Headers != null && eventArg.BasicProperties.Headers.ContainsKey("Priority")) { //It's a byte, has to convert to char var enc = new System.Text.UTF8Encoding(); string str = enc.GetString((byte[])eventArg.BasicProperties.Headers["Priority"]); int.TryParse(str, out priority); } return priority; }
public static string GetEmailBody(string templatePath) { System.Net.WebClient objWebClient = new System.Net.WebClient(); byte[] aRequestedHTML = null; string strRequestedHTML = null; aRequestedHTML = objWebClient.DownloadData(templatePath); System.Text.UTF8Encoding objUTF8 = new System.Text.UTF8Encoding(); strRequestedHTML = objUTF8.GetString(aRequestedHTML); return strRequestedHTML; }
/// <summary> /// Convert byte array to string. /// </summary> /// <returns>The string.</returns> /// <param name="bytes">Byte array.</param> public static string ToString (byte[] bytes) { Support.LogDebug("Converting " + bytes.Length + " bytes to string."); if (bytes != null && bytes.Length > 0) { System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding(); string result = enc.GetString(bytes); Support.LogDebug("Converted '" + result + "'"); return result; } else return ""; }
public static TocEntry Create(byte[] item) { var ret = new TocEntry(); var enc = new System.Text.UTF8Encoding(); int ix = 0; var namelength = BitConverter.ToInt32(item, ix); ix += sizeof (Int32); ret.Name = enc.GetString(item, ix, namelength); ix += namelength; ret.Length = BitConverter.ToUInt32(item, ix); ix += sizeof (uint); ret.Handle = BitConverter.ToUInt32(item, ix); return ret; }
/// <summary> /// Decrypts a string. /// </summary> /// <param name="Message">The string to decrypt.</param> /// <param name="Passphrase">The passphrase to use.</param> /// <returns></returns> public static string DecryptString( string Message ) { string encryptionPhrase = ConfigurationManager.AppSettings["EncryptionPhrase"]; if ( String.IsNullOrWhiteSpace( encryptionPhrase ) ) encryptionPhrase = "Rock Rocks!"; byte[] Results; System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding(); // Step 1. We hash the passphrase using MD5 // We use the MD5 hash generator as the result is a 128 bit byte array // which is a valid length for the TripleDES encoder we use below MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider(); byte[] TDESKey = HashProvider.ComputeHash( UTF8.GetBytes( encryptionPhrase ) ); // Step 2. Create a new TripleDESCryptoServiceProvider object TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider(); // Step 3. Setup the decoder TDESAlgorithm.Key = TDESKey; TDESAlgorithm.Mode = CipherMode.ECB; TDESAlgorithm.Padding = PaddingMode.PKCS7; // Step 4. Convert the input string to a byte[] byte[] DataToDecrypt = Convert.FromBase64String( Message ); // Step 5. Attempt to decrypt the string try { ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor(); Results = Decryptor.TransformFinalBlock( DataToDecrypt, 0, DataToDecrypt.Length ); } finally { // Clear the TripleDes and Hashprovider services of any sensitive information TDESAlgorithm.Clear(); HashProvider.Clear(); } // Step 6. Return the decrypted string in UTF8 format return UTF8.GetString( Results ); }
static void Main(string[] args) { System.Net.WebClient webClient = new System.Net.WebClient(); const string request = "http://search.yahooapis.com/WebSearchService/V1/webSearch?appid=YahooDemo&query=madonna&results=2"; byte[] responseXML; try { responseXML = webClient.DownloadData(request); System.Text.UTF8Encoding objUTF8 = new System.Text.UTF8Encoding(); System.Console.WriteLine(objUTF8.GetString(responseXML)); } catch (System.Exception) { System.Console.WriteLine("Web services request failed"); } }
public async Task<IActionResult> GetRdp(string groupId, string resourceId) { ScampResource res = await _resourceRepository.GetResource(resourceId); if (res == null) return new HttpStatusCodeResult(404); // not found // can user preform this action if (!(await CanManageResource(res, ResourceAction.Undefined))) return new HttpStatusCodeResult(403); // request denied, invalid permission ScampSubscription sub = await _settingsRepository.GetSubscription(res.SubscriptionId); var provisioningController = new ProvisioningController(sub.AzureManagementThumbnail, sub.AzureSubscriptionID); //Response.ContentType = "application/x-rdp"; Response.Headers.Add("content-disposition", new string[] { "attachment; filename =" + res.CloudServiceName + ".rdp" }); byte[] bytes = await provisioningController.GetRdpAsync(res.Name, res.CloudServiceName); var encoding = new System.Text.UTF8Encoding(); var sRes = encoding.GetString(bytes); return new ObjectResult(sRes) { StatusCode = 200 }; }
public static string ComputePasswordHash(string password, int salt) { if (String.IsNullOrEmpty(password)) throw new ArgumentNullException("password", "Password string can't be null!"); var utf8Encoder = new System.Text.UTF8Encoding(); // Create byte arrays byte[] passwordBytes = utf8Encoder.GetBytes(password); byte[] saltBytes = { (byte)(salt >> 24), (byte)(salt >> 16), (byte)(salt >> 8), (byte)salt }; // Combine two byte arrays byte[] bytes = new byte[passwordBytes.Length + saltBytes.Length]; Array.Copy(passwordBytes, 0, bytes, 0, passwordBytes.Length); Array.Copy(saltBytes, 0, bytes, passwordBytes.Length, saltBytes.Length); // Encrypt byte array byte[] hash = (SHA512Managed.Create()).ComputeHash(bytes); return utf8Encoder.GetString(hash); }
public static string Descriptografar(string Message) { byte[] Results; System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding(); MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider(); byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(senha)); TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider(); TDESAlgorithm.Key = TDESKey; TDESAlgorithm.Mode = CipherMode.ECB; TDESAlgorithm.Padding = PaddingMode.PKCS7; byte[] DataToDecrypt = Convert.FromBase64String(Message); try { ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor(); Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length); } finally { TDESAlgorithm.Clear(); HashProvider.Clear(); } return UTF8.GetString(Results); }
public static string DecryptString(string message, string passphrase) { byte[] results; var utf8 = new System.Text.UTF8Encoding(); // Step 1. We hash the passphrase using MD5 // We use the MD5 hash generator as the result is a 128 bit byte array // which is a valid length for the TripleDES encoder we use below var hashProvider = new MD5CryptoServiceProvider(); var tdesKey = hashProvider.ComputeHash(utf8.GetBytes(passphrase)); // Step 2. Create a new TripleDESCryptoServiceProvider object var tdesAlgorithm = new TripleDESCryptoServiceProvider {Key = tdesKey, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7}; // Step 3. Setup the decoder // Step 4. Convert the input string to a byte[] var dataToDecrypt = Convert.FromBase64String(message); // Step 5. Attempt to decrypt the string try { var decryptor = tdesAlgorithm.CreateDecryptor(); results = decryptor.TransformFinalBlock(dataToDecrypt, 0, dataToDecrypt.Length); } finally { // Clear the TripleDes and Hashprovider services of any sensitive information tdesAlgorithm.Clear(); hashProvider.Clear(); } // Step 6. Return the decrypted string in UTF8 format return utf8.GetString(results); }
/// <summary> /// Writes a specified number of bytes into the stream object starting at the current seek pointer. /// </summary> public void Write(byte[] pv, int cb, System.IntPtr pcbWritten) { // Create a UTF-8 encoding, and use that to write out the string. // This isn't very efficient, but... System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding(); string s = utf8.GetString(pv, 0, cb); m_writer.Write(s); System.Runtime.InteropServices.Marshal.WriteInt32(pcbWritten, cb); }
public string DecryptString(string Message) { byte[] Results; System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding(); // Step 1. We hash the passphrase using MD5 // We use the MD5 hash generator as the result is a 128 bit byte array // which is a valid length for the TripleDES encoder we use below Stream stream = File.OpenRead(this.KeyPath); byte[] buffer = new byte[(int)stream.Length]; stream.Close(); // MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider(); // byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase)); // Step 2. Create a new TripleDESCryptoServiceProvider object TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider { Key = buffer, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 }; // Step 3. Setup the decoder // Step 4. Convert the input string to a byte[] byte[] DataToDecrypt = Convert.FromBase64String(Message); // Step 5. Attempt to decrypt the string try { ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor(); Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length); } finally { // Clear the TripleDes and Hashprovider services of any sensitive information TDESAlgorithm.Clear(); // HashProvider.Clear(); } // Step 6. Return the decrypted string in UTF8 format return UTF8.GetString(Results); }
public ScriptInstance(IScriptEngine engine, SceneObjectPart part, UUID itemID, UUID assetID, string assembly, AppDomain dom, string primName, string scriptName, int startParam, bool postOnRez, StateSource stateSource, int maxScriptQueue) { State = "default"; EventQueue = new Queue(32); Engine = engine; LocalID = part.LocalId; ObjectID = part.UUID; RootLocalID = part.ParentGroup.LocalId; RootObjectID = part.ParentGroup.UUID; ItemID = itemID; AssetID = assetID; PrimName = primName; ScriptName = scriptName; m_Assembly = assembly; StartParam = startParam; m_MaxScriptQueue = maxScriptQueue; m_stateSource = stateSource; m_postOnRez = postOnRez; m_AttachedAvatar = part.ParentGroup.AttachedAvatar; m_RegionID = part.ParentGroup.Scene.RegionInfo.RegionID; if (part != null) { lock (part.TaskInventory) { if (part.TaskInventory.ContainsKey(ItemID)) { ScriptTask = part.TaskInventory[ItemID]; } } } ApiManager am = new ApiManager(); foreach (string api in am.GetApis()) { m_Apis[api] = am.CreateApi(api); m_Apis[api].Initialize(engine, part, LocalID, itemID); } try { if (dom != System.AppDomain.CurrentDomain) m_Script = (IScript)dom.CreateInstanceAndUnwrap( Path.GetFileNameWithoutExtension(assembly), "SecondLife.Script"); else m_Script = (IScript)Assembly.Load( Path.GetFileNameWithoutExtension(assembly)).CreateInstance( "SecondLife.Script"); //ILease lease = (ILease)RemotingServices.GetLifetimeService(m_Script as ScriptBaseClass); //RemotingServices.GetLifetimeService(m_Script as ScriptBaseClass); // lease.Register(this); } catch (Exception e) { m_log.ErrorFormat( "[SCRIPT INSTANCE]: Error loading assembly {0}. Exception {1}{2}", assembly, e.Message, e.StackTrace); } try { foreach (KeyValuePair<string,IScriptApi> kv in m_Apis) { m_Script.InitApi(kv.Key, kv.Value); } // // m_log.Debug("[Script] Script instance created"); part.SetScriptEvents(ItemID, (int)m_Script.GetStateEventFlags(State)); } catch (Exception e) { m_log.ErrorFormat( "[SCRIPT INSTANCE]: Error loading script instance from assembly {0}. Exception {1}{2}", assembly, e.Message, e.StackTrace); return; } m_SaveState = true; string savedState = Path.Combine(Path.GetDirectoryName(assembly), ItemID.ToString() + ".state"); if (File.Exists(savedState)) { string xml = String.Empty; try { FileInfo fi = new FileInfo(savedState); int size = (int)fi.Length; if (size < 512000) { using (FileStream fs = File.Open(savedState, FileMode.Open, FileAccess.Read, FileShare.None)) { System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding(); Byte[] data = new Byte[size]; fs.Read(data, 0, size); xml = enc.GetString(data); ScriptSerializer.Deserialize(xml, this); AsyncCommandManager.CreateFromData(Engine, LocalID, ItemID, ObjectID, PluginData); // m_log.DebugFormat("[Script] Successfully retrieved state for script {0}.{1}", PrimName, m_ScriptName); part.SetScriptEvents(ItemID, (int)m_Script.GetStateEventFlags(State)); Running = false; if (ShuttingDown) m_startOnInit = false; // we get new rez events on sim restart, too // but if there is state, then we fire the change // event // We loaded state, don't force a re-save m_SaveState = false; m_startedFromSavedState = true; } } else { m_log.ErrorFormat( "[SCRIPT INSTANCE]: Unable to load script state from assembly {0}: Memory limit exceeded", assembly); } } catch (Exception e) { m_log.ErrorFormat( "[SCRIPT INSTANCE]: Unable to load script state from assembly {0}. XML is {1}. Exception {2}{3}", assembly, xml, e.Message, e.StackTrace); } } // else // { // ScenePresence presence = Engine.World.GetScenePresence(part.OwnerID); // if (presence != null && (!postOnRez)) // presence.ControllingClient.SendAgentAlertMessage("Compile successful", false); // } }
private string signEnvelopeData(string msg) { Stream privateKeyStream = getPrivateKeyStream(_privateKey); MemoryStream result = new MemoryStream(); ArmoredOutputStream aOut = new ArmoredOutputStream(result); BcpgOutputStream bOut = null; char[] privateKeyPassword = _passPhrase.ToCharArray(); var utf8Encoding = new System.Text.UTF8Encoding(); try { PgpSecretKey sk = readSecretKey(privateKeyStream); PgpPrivateKey pk = sk.ExtractPrivateKey(privateKeyPassword); PgpSignatureGenerator sigGen = new PgpSignatureGenerator(sk.PublicKey.Algorithm,HashAlgorithmTag.Sha256); PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator(); var enumerator = sk.PublicKey.GetUserIds().GetEnumerator(); if(enumerator.MoveNext()) { spGen.SetSignerUserId(false, (string)enumerator.Current); sigGen.SetHashedSubpackets(spGen.Generate()); } aOut.BeginClearText(HashAlgorithmTag.Sha256); sigGen.InitSign(PgpSignature.CanonicalTextDocument, pk); byte[] msgBytes = utf8Encoding.GetBytes(msg); sigGen.Update(msgBytes, 0, msgBytes.Length); aOut.Write(msgBytes, 0, msgBytes.Length); bOut = new BcpgOutputStream(aOut); aOut.EndClearText(); sigGen.Generate().Encode(bOut); using (BinaryReader br = new BinaryReader(result)) { br.BaseStream.Position = 0; return utf8Encoding.GetString(br.ReadBytes((int)result.Length)); } } catch (Exception e) { Console.WriteLine("This happened: " + e.Message); throw new Exception("Signing Failed: " + e.Message); } finally { try { if (privateKeyStream != null) privateKeyStream.Close(); //if(bOut != null) //bOut.Close(); //aOut.Close(); result.Close(); } catch (IOException) {} } }
public override string ToString() { string postDataAsString = string.Empty; if (null != PostData) { System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding(); postDataAsString = enc.GetString(PostData); } string h = string.Empty; if (null != Headers && Headers.Count > 0) { foreach (var key in Headers.Keys) { h += string.Format(@" -> {0}: {1} ", key, Headers[key]); } } return string.Format( @"WwwRequest ============ Url: {0} Headers: {1} PostData: {2} Form: {3} ============", Url ?? "-", string.Empty != h ? h : "-", null == PostData ? "-" : postDataAsString, null != Form ? "Yes" : "No"); }
public static string ReadString(byte[] data, Cursor cursor) { int len = Utils.ReadInt32(data, cursor); if (len == 0) { return null; } System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding(); string s = enc.GetString(data, cursor.index, len); cursor.index += len; return s; }
public static string ReadString(string s) { string RetVal; byte[] b = Base64.Decode(s); System.Text.UTF8Encoding U = new System.Text.UTF8Encoding(); return(U.GetString(b)); }
public Yield UserLogin(DreamContext context, DreamMessage request, Result<DreamMessage> response) { string userSuppliedIdentifier = context.GetParam("url", null); if (String.IsNullOrEmpty(userSuppliedIdentifier)) { _log.Info("No identifier was specified"); throw new DreamBadRequestException("No identifier was specified."); } XUri returnUri = new XUri(context.GetParam("returnurl", null)); String realm = context.GetParam("realm", null); if (String.IsNullOrEmpty(realm)) { realm = returnUri.WithoutPathQueryFragment().ToString(); } IAuthenticationRequest openIdRequest; // dummy parameters required by DotNetOpenId 2.x; in 3.x, you can // just pass null to the OpenIdRelyingParty constructor. Uri identifierUri = new Uri(userSuppliedIdentifier); NameValueCollection queryCol = System.Web.HttpUtility.ParseQueryString(identifierUri.Query); OpenIdRelyingParty openid = new OpenIdRelyingParty(null, identifierUri, queryCol); // creating an OpenID request will authenticate that // the endpoint exists and is an OpenID provider. _log.DebugFormat("Creating OpenID request: identifier {0}, return URL {1}, realm {2}", userSuppliedIdentifier, returnUri.ToString(), realm); try { openIdRequest = openid.CreateRequest( userSuppliedIdentifier, realm, returnUri.ToUri()); } catch (OpenIdException ex) { _log.WarnFormat("'{0}' rejected as OpenID identifier: {1}", userSuppliedIdentifier, ex.Message); throw new DreamBadRequestException(string.Format("'{0}' is not a valid OpenID identifier. {1}", userSuppliedIdentifier, ex.Message)); } // Ask for the e-mail address on this request. // Use both SREG and AX, to increase the odds of getting it. openIdRequest.AddExtension(new ClaimsRequest{ Email = DemandLevel.Require, }); var fetch = new FetchRequest(); fetch.AddAttribute(new AttributeRequest(WellKnownAttributes.Contact.Email, true)); openIdRequest.AddExtension(fetch); // The RedirectingResponse either contains a "Location" header for // a HTTP GET, which will return in the response as 'endpoint', or // a HTML FORM which needs to be displayed to the user, which will // return in the response as 'form'. IResponse wr = openIdRequest.RedirectingResponse; XDoc result = new XDoc("openid"); if (String.IsNullOrEmpty(wr.Headers["Location"])) { System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding(); string formBody = enc.GetString(wr.Body); _log.DebugFormat("OpenID redirect by HTML FORM: {0}", formBody); result.Attr("form", formBody); } else { string redirectUrl = wr.Headers["Location"]; _log.DebugFormat("OpenID redirect URL: {0}", redirectUrl); result.Attr("endpoint", redirectUrl); } response.Return(DreamMessage.Ok(result)); yield break; }
internal void ParseSCPD(String XML) { OpenSource.Utilities.EventLogger.Log (this, System.Diagnostics.EventLogEntryType.SuccessAudit,"Embarking on an xml journey"); bool loadSchema = false; string schemaUrn = ""; if (XML == "") { return; } string evented = "no"; string multicast = "no"; StringReader MyString = new StringReader(XML); XmlTextReader XMLDoc = new XmlTextReader(MyString); XMLDoc.Read(); XMLDoc.MoveToContent(); if (XMLDoc.LocalName == "scpd") { if (XMLDoc.HasAttributes) { // May be UPnP/1.1 SCPD for (int i = 0; i < XMLDoc.AttributeCount; i++) { XMLDoc.MoveToAttribute(i); if (XMLDoc.Prefix == "xmlns") { loadSchema = true; schemaUrn = XMLDoc.Value; } // ToDo: Try to load the schema from the network first // if (XMLDoc.LocalName=="schemaLocation") // { // if (XMLDoc.Value=="http://www.vendor.org/Schemas/Sample.xsd") // { // schemaUrn = XMLDoc.LookupNamespace(XMLDoc.Prefix); // } // } } XMLDoc.MoveToElement(); if (loadSchema) { // Prompt Application for local Schema Location System.Windows.Forms.OpenFileDialog fd = new System.Windows.Forms.OpenFileDialog(); fd.Multiselect = false; fd.Title = schemaUrn; if (fd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { FileStream fs = (FileStream)fd.OpenFile(); System.Text.UTF8Encoding U = new System.Text.UTF8Encoding(); byte[] buffer = new byte[(int)fs.Length]; fs.Read(buffer, 0, buffer.Length); UPnPComplexType[] complexTypes = UPnPComplexType.Parse(U.GetString(buffer)); fs.Close(); foreach (UPnPComplexType complexType in complexTypes) { this.AddComplexType(complexType); } } } } // TODO This parsing is hideous. We should use a proper parser! XMLDoc.Read(); XMLDoc.MoveToContent(); while ((XMLDoc.LocalName != "scpd") && (XMLDoc.EOF == false)) { if (XMLDoc.LocalName == "actionList" && !XMLDoc.IsEmptyElement) { XMLDoc.Read(); XMLDoc.MoveToContent(); while ((XMLDoc.LocalName != "actionList") && (XMLDoc.EOF == false)) { if (XMLDoc.LocalName == "action") { OpenSource.Utilities.EventLogger.Log(this, System.Diagnostics.EventLogEntryType.SuccessAudit, "Found an action, lets parse it!"); ParseActionXml("<action>\r\n" + XMLDoc.ReadInnerXml() + "</action>"); } if (!XMLDoc.IsStartElement()) { if (XMLDoc.LocalName != "actionList") { XMLDoc.Read(); XMLDoc.MoveToContent(); } } } } else { if (XMLDoc.LocalName == "serviceStateTable") { XMLDoc.Read(); XMLDoc.MoveToContent(); while ((XMLDoc.LocalName != "serviceStateTable") && (XMLDoc.EOF == false)) { if (XMLDoc.LocalName == "stateVariable") { evented = "no"; multicast = "no"; XMLDoc.MoveToAttribute("sendEvents"); if (XMLDoc.LocalName == "sendEvents") { evented = XMLDoc.GetAttribute("sendEvents"); } XMLDoc.MoveToAttribute("multicast"); if (XMLDoc.LocalName == "multicast") { multicast = XMLDoc.GetAttribute("multicast"); } XMLDoc.MoveToContent(); ParseStateVarXml(evented, multicast, XMLDoc); } if (!XMLDoc.IsStartElement()) { if (XMLDoc.LocalName != "serviceStateTable") { XMLDoc.Read(); XMLDoc.MoveToContent(); } } } } else { XMLDoc.Skip(); } } if (!XMLDoc.IsStartElement()) { XMLDoc.Read(); XMLDoc.MoveToContent(); } } // End of While // Add Associations foreach (UPnPAction A in this.Actions) { foreach (UPnPArgument G in A.Arguments) { if (G.RelatedStateVar == null) { OpenSource.Utilities.EventLogger.Log(this, System.Diagnostics.EventLogEntryType.FailureAudit, "About to throw an exception"); throw (new InvalidRelatedStateVariableException("Action: " + A.Name + " Arg: " + G.Name + " Contains invalid reference: " + G.StateVarName)); } G.RelatedStateVar.AddAssociation(A.Name, G.Name); } } } // End of If }
public string GetComplexSchemaForNamespace(string ns) { string RetVal; MemoryStream m = new MemoryStream(); XmlTextWriter X = new XmlTextWriter(m, System.Text.Encoding.UTF8); ArrayList a = (ArrayList)this.ComplexType_NamespaceTables[ns]; if (a != null) { X.WriteStartDocument(); X.WriteStartElement("xs", "schema", "http://www.w3.org/2001/XMLSchema"); X.WriteAttributeString("targetNamespace", ns); X.WriteAttributeString("xmlns", ns); foreach (UPnPComplexType CT in a) { CT.GetComplexTypeSchemaPart(X); } X.WriteEndElement(); X.WriteEndDocument(); X.Flush(); System.Text.UTF8Encoding U = new System.Text.UTF8Encoding(); RetVal = U.GetString(m.GetBuffer(), 3, (int)m.Length - 3); X.Close(); return (RetVal); } else { return (null); } }
// TODO (#5525): This is a helper method copied from WebHeaderCollection.HeaderEncoding.DecodeUtf8FromString. // Merge this code and move to System.Net.Common. // // The normal client header parser just casts bytes to chars (see GetString). // Check if those bytes were actually utf-8 instead of ASCII. // If not, just return the input value. internal static string DecodeUtf8FromString(string input) { if (string.IsNullOrWhiteSpace(input)) { return input; } bool possibleUtf8 = false; for (int i = 0; i < input.Length; i++) { if (input[i] > (char)255) { return input; // This couldn't have come from the wire, someone assigned it directly. } else if (input[i] > (char)127) { possibleUtf8 = true; break; } } if (possibleUtf8) { byte[] rawBytes = new byte[input.Length]; for (int i = 0; i < input.Length; i++) { if (input[i] > (char)255) { return input; // This couldn't have come from the wire, someone assigned it directly. } rawBytes[i] = (byte)input[i]; } try { // We don't want '?' replacement characters, just fail. #if PHONE || NETNative System.Text.Encoding decoder = new System.Text.UTF8Encoding(encoderShouldEmitUTF8Identifier: true, throwOnInvalidBytes: true); #else System.Text.Encoding decoder = System.Text.Encoding.GetEncoding("utf-8", System.Text.EncoderFallback.ExceptionFallback, System.Text.DecoderFallback.ExceptionFallback); #endif return decoder.GetString(rawBytes, 0, rawBytes.Length); } catch (ArgumentException) { } // Not actually Utf-8 } return input; }
/// <summary> /// Parses a service xml into the UPnPservice instance. The instance will have been created by /// parsing the Service element from the Device xml, see <see cref="UPnPService.Parse">Parse method</see> /// </summary> /// <param name="XML">the xml containing the service description</param> internal void ParseSCPD(String XML) { bool loadSchema = false; string schemaUrn = ""; if (XML == "") { return; } string evented = "no"; string multicast = "no"; StringReader MyString = new StringReader(XML); XmlTextReader XMLDoc = new XmlTextReader(MyString); XMLDoc.Read(); XMLDoc.MoveToContent(); if (XMLDoc.LocalName == "scpd") { if (XMLDoc.HasAttributes) { // May be UPnP/1.1 SCPD for (int i = 0; i < XMLDoc.AttributeCount; i++) { XMLDoc.MoveToAttribute(i); if (XMLDoc.Prefix == "xmlns") { loadSchema = true; schemaUrn = XMLDoc.Value; } // ToDo: Try to load the schema from the network first // if (XMLDoc.LocalName=="schemaLocation") // { // if (XMLDoc.Value=="http://www.vendor.org/Schemas/Sample.xsd") // { // schemaUrn = XMLDoc.LookupNamespace(XMLDoc.Prefix); // } // } } XMLDoc.MoveToElement(); if (loadSchema) { // Prompt Application for local Schema Location System.Windows.Forms.OpenFileDialog fd = new System.Windows.Forms.OpenFileDialog(); fd.Multiselect = false; fd.Title = schemaUrn; if (fd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { FileStream fs = (FileStream)fd.OpenFile(); System.Text.UTF8Encoding U = new System.Text.UTF8Encoding(); byte[] buffer = new byte[(int)fs.Length]; fs.Read(buffer, 0, buffer.Length); UPnPComplexType[] complexTypes = UPnPComplexType.Parse(U.GetString(buffer)); fs.Close(); foreach (UPnPComplexType complexType in complexTypes) { this.AddComplexType(complexType); } } } } XMLDoc.Read(); XMLDoc.MoveToContent(); while ((XMLDoc.LocalName != "scpd") && (XMLDoc.EOF == false)) { if (XMLDoc.LocalName == "actionList" && !XMLDoc.IsEmptyElement) { XMLDoc.Read(); XMLDoc.MoveToContent(); while ((XMLDoc.LocalName != "actionList") && (XMLDoc.EOF == false)) { if (XMLDoc.LocalName == "action") { string actionxml = "Failed to read the Action element from the source xml."; try { //TODO: DONE Resilience case 4 & 2 - if action fails itself (or underlying arguments), don't add it. //Wrap in try-catch actionxml = "<action>\r\n" + XMLDoc.ReadInnerXml() + "</action>"; ParseActionXml(actionxml); } catch (Exception e) { OpenSource.Utilities.EventLogger.Log(this, System.Diagnostics.EventLogEntryType.Error, "Invalid Action XML"); OpenSource.Utilities.EventLogger.Log(e, "XML content: \r\n" + actionxml); OpenSource.Utilities.EventLogger.Log(this, System.Diagnostics.EventLogEntryType.Warning, "Dropping failed Action and commencing parsing remainder of device"); } } if (!XMLDoc.IsStartElement()) { if (XMLDoc.LocalName != "actionList") { XMLDoc.Read(); XMLDoc.MoveToContent(); } } } } else { if (XMLDoc.LocalName == "serviceStateTable") { XMLDoc.Read(); XMLDoc.MoveToContent(); while ((XMLDoc.LocalName != "serviceStateTable") && (XMLDoc.EOF == false)) { if (XMLDoc.LocalName == "stateVariable") { // TODO: DONE Resilience case 1 - wrap block in try-catch, with error logging try { evented = "no"; multicast = "no"; XMLDoc.MoveToAttribute("sendEvents"); if (XMLDoc.LocalName == "sendEvents") { evented = XMLDoc.GetAttribute("sendEvents"); } XMLDoc.MoveToAttribute("multicast"); if (XMLDoc.LocalName == "multicast") { multicast = XMLDoc.GetAttribute("multicast"); } XMLDoc.MoveToContent(); ParseStateVarXml(evented, multicast, XMLDoc); } catch (Exception e) { OpenSource.Utilities.EventLogger.Log(this, System.Diagnostics.EventLogEntryType.Error, "Invalid StateVariable XML"); OpenSource.Utilities.EventLogger.Log(e); OpenSource.Utilities.EventLogger.Log(this, System.Diagnostics.EventLogEntryType.Warning, "Dropping failed StateVariable and commencing parsing remainder of device"); } } if (!XMLDoc.IsStartElement()) { if (XMLDoc.LocalName != "serviceStateTable") { XMLDoc.Read(); XMLDoc.MoveToContent(); } } } } else { XMLDoc.Skip(); } } if (!XMLDoc.IsStartElement()) { XMLDoc.Read(); XMLDoc.MoveToContent(); } } // End of While // TODO: DONE Resilience case 3 - log error, and mark faulty Action // Add Associations System.Collections.ArrayList skiplist = new System.Collections.ArrayList(); foreach (UPnPAction A in this.Actions) { try { foreach (UPnPArgument G in A.Arguments) { if (G.RelatedStateVar == null) { throw (new InvalidRelatedStateVariableException("Action: " + A.Name + " Arg: " + G.Name + " Contains invalid reference: " + G.StateVarName)); } G.RelatedStateVar.AddAssociation(A.Name, G.Name); } } catch (Exception e) { // adding it failed, so add to skiplist skiplist.Add(A); OpenSource.Utilities.EventLogger.Log(this, System.Diagnostics.EventLogEntryType.Error, "Invalid Action; could not create Argument-Statevariable association for action: " + A.Name); OpenSource.Utilities.EventLogger.Log(e); OpenSource.Utilities.EventLogger.Log(this, System.Diagnostics.EventLogEntryType.Warning, "Dropping failed StateVariable and arguments, commencing parsing remainder of actions"); } } // Ditch the faulty ones // TODO: DONE Resilience case 3 - remove faulty Action and its Arguments and their relations foreach (UPnPAction A in skiplist) { // remove previously added associations foreach (UPnPArgument G in A.Arguments) { if (G.RelatedStateVar != null) { G.RelatedStateVar.RemoveAssociation(A.Name, G.Name); } } // remove action itself RemoteMethods.Remove(A.Name); } } // End of If }
internal void ParseSCPD(String XML, int startLine) { bool loadSchema = false; string schemaUrn = ""; if (XML == "") { return; } string evented = "no"; string multicast = "no"; StringReader MyString = new StringReader(XML); XmlTextReader XMLDoc = new XmlTextReader(MyString); XMLDoc.Read(); XMLDoc.MoveToContent(); if (XMLDoc.LocalName == "scpd") { try { if (XMLDoc.HasAttributes) { // May be UPnP/1.1 SCPD for (int i = 0; i < XMLDoc.AttributeCount; i++) { XMLDoc.MoveToAttribute(i); if (XMLDoc.Prefix == "xmlns") { loadSchema = true; schemaUrn = XMLDoc.Value; } // ToDo: Try to load the schema from the network first // if (XMLDoc.LocalName=="schemaLocation") // { // if (XMLDoc.Value=="http://www.vendor.org/Schemas/Sample.xsd") // { // schemaUrn = XMLDoc.LookupNamespace(XMLDoc.Prefix); // } // } } XMLDoc.MoveToElement(); if (loadSchema) { // Prompt Application for local Schema Location System.Windows.Forms.OpenFileDialog fd = new System.Windows.Forms.OpenFileDialog(); fd.Multiselect = false; fd.Title = schemaUrn; if (fd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { FileStream fs = (FileStream)fd.OpenFile(); System.Text.UTF8Encoding U = new System.Text.UTF8Encoding(); byte[] buffer = new byte[(int)fs.Length]; fs.Read(buffer, 0, buffer.Length); UPnPComplexType[] complexTypes = UPnPComplexType.Parse(U.GetString(buffer)); fs.Close(); foreach (UPnPComplexType complexType in complexTypes) { this.AddComplexType(complexType); } } } } XMLDoc.Read(); XMLDoc.MoveToContent(); while ((XMLDoc.LocalName != "scpd") && (XMLDoc.EOF == false)) { if (XMLDoc.LocalName == "actionList" && !XMLDoc.IsEmptyElement) { XMLDoc.Read(); XMLDoc.MoveToContent(); while ((XMLDoc.LocalName != "actionList") && (XMLDoc.EOF == false)) { if (XMLDoc.LocalName == "action") { int embeddedLine = XMLDoc.LineNumber; //ParseActionXml("<action>\r\n" + XMLDoc.ReadInnerXml() + "</action>", embeddedLine); ParseActionXml(XMLDoc.ReadOuterXml(), embeddedLine-1); } if (!XMLDoc.IsStartElement()) { if (XMLDoc.LocalName != "actionList") { XMLDoc.Read(); XMLDoc.MoveToContent(); } } } } else { if (XMLDoc.LocalName == "serviceStateTable") { XMLDoc.Read(); XMLDoc.MoveToContent(); while ((XMLDoc.LocalName != "serviceStateTable") && (XMLDoc.EOF == false)) { if (XMLDoc.LocalName == "stateVariable") { evented = "no"; multicast = "no"; XMLDoc.MoveToAttribute("sendEvents"); if (XMLDoc.LocalName == "sendEvents") { evented = XMLDoc.GetAttribute("sendEvents"); } XMLDoc.MoveToAttribute("multicast"); if (XMLDoc.LocalName == "multicast") { multicast = XMLDoc.GetAttribute("multicast"); } XMLDoc.MoveToContent(); ParseStateVarXml(evented, multicast, XMLDoc, startLine); } if (!XMLDoc.IsStartElement()) { if (XMLDoc.LocalName != "serviceStateTable") { XMLDoc.Read(); XMLDoc.MoveToContent(); } } } } else { XMLDoc.Skip(); } } if (!XMLDoc.IsStartElement()) { XMLDoc.Read(); XMLDoc.MoveToContent(); } } // End of While } catch (XMLParsingException ex) { throw ex; } catch (Exception ex) { throw new XMLParsingException("Invalid SCPD XML", startLine + XMLDoc.LineNumber, XMLDoc.LinePosition, ex); } // Add Associations foreach (UPnPAction A in this.Actions) { foreach (UPnPArgument G in A.Arguments) { if (G.RelatedStateVar == null) { throw (new InvalidRelatedStateVariableException("Action: " + A.Name + " Arg: " + G.Name + " Contains invalid reference: " + G.StateVarName)); } G.RelatedStateVar.AddAssociation(A.Name, G.Name); } } } // End of If }