private static string UriEncodeAnyUrl(string text, Encoding encoding) { if (text == null) throw new ArgumentNullException("text"); if (encoding == null) throw new ArgumentNullException("encoding"); if (text.Length == 0) return text; StringBuilder builder = new StringBuilder(); byte[] data = encoding.GetBytes(text); for (int i = 0; i < data.Length; i++) { if (_unreservedCharacters[data[i]]) { builder.Append((char)data[i]); } else { switch ((char)data[i]) { case '(': case ')': case '*': case '!': builder.Append((char)data[i]); break; default: builder.Append('%').Append(data[i].ToString("x2")); break; } } } return builder.ToString(); }
/// <summary> /// Writes a line to the stream using the specified encoding asynchronously /// </summary> /// <param name="encoding">Encoding used for writing the line</param> /// <param name="buf">The data to write</param> /// <param name="token">The <see cref="CancellationToken"/> for this task</param> public async Task WriteLineAsync(System.Text.Encoding encoding, string buf, CancellationToken token) { byte[] data = encoding.GetBytes(buf + "\r\n"); await WriteAsync(data, 0, data.Length, token); }
private int EmitHeader() { byte[] commentBytes = (Comment == null) ? null : DefaultEncoding.GetBytes(Comment); byte[] filenameBytes = (FileName == null) ? null : DefaultEncoding.GetBytes(FileName); int cbLength = (Comment == null) ? 0 : commentBytes.Length + 1; int fnLength = (FileName == null) ? 0 : filenameBytes.Length + 1; int bufferLength = 10 + cbLength + fnLength; byte[] header = new byte[bufferLength]; int i = 0; // ID header[i++] = 0x1F; header[i++] = 0x8B; // compression method header[i++] = 8; byte flag = 0; if (Comment != null) { flag ^= 0x10; } if (FileName != null) { flag ^= 0x8; } // flag header[i++] = flag; // mtime if (!LastModified.HasValue) { LastModified = SystemTime.UtcNow; } System.TimeSpan delta = LastModified.Value - _unixEpoch; Int32 timet = (Int32)delta.TotalSeconds; Array.Copy(BitConverter.GetBytes(timet), 0, header, i, 4); i += 4; // xflg header[i++] = 0; // this field is totally useless // OS header[i++] = 0xFF; // 0xFF == unspecified // extra field length - only if FEXTRA is set, which it is not. //header[i++]= 0; //header[i++]= 0; // filename if (fnLength != 0) { Array.Copy(filenameBytes, 0, header, i, fnLength - 1); i += fnLength - 1; header[i++] = 0; // terminate } // comment if (cbLength != 0) { Array.Copy(commentBytes, 0, header, i, cbLength - 1); i += cbLength - 1; header[i++] = 0; // terminate } _baseStream._stream.Write(header, 0, header.Length); return(header.Length); // bytes written }
private static byte[] GenCentralDirectoryFooter(long StartOfCentralDirectory, long EndOfCentralDirectory, Zip64Option zip64, int entryCount, string comment, System.Text.Encoding encoding) { int j = 0; int bufferLength = 22; byte[] block = null; Int16 commentLength = 0; if ((comment != null) && (comment.Length != 0)) { block = encoding.GetBytes(comment); commentLength = (Int16)block.Length; } bufferLength += commentLength; byte[] bytes = new byte[bufferLength]; int i = 0; // signature byte[] sig = BitConverter.GetBytes(ZipConstants.EndOfCentralDirectorySignature); Array.Copy(sig, 0, bytes, i, 4); i += 4; // number of this disk // (this number may change later) bytes[i++] = 0; bytes[i++] = 0; // number of the disk with the start of the central directory // (this number may change later) bytes[i++] = 0; bytes[i++] = 0; // handle ZIP64 extensions for the end-of-central-directory if (entryCount >= 0xFFFF || zip64 == Zip64Option.Always) { // the ZIP64 version. for (j = 0; j < 4; j++) { bytes[i++] = 0xFF; } } else { // the standard version. // total number of entries in the central dir on this disk bytes[i++] = (byte)(entryCount & 0x00FF); bytes[i++] = (byte)((entryCount & 0xFF00) >> 8); // total number of entries in the central directory bytes[i++] = (byte)(entryCount & 0x00FF); bytes[i++] = (byte)((entryCount & 0xFF00) >> 8); } // size of the central directory Int64 SizeOfCentralDirectory = EndOfCentralDirectory - StartOfCentralDirectory; if (SizeOfCentralDirectory >= 0xFFFFFFFF || StartOfCentralDirectory >= 0xFFFFFFFF) { // The actual data is in the ZIP64 central directory structure for (j = 0; j < 8; j++) { bytes[i++] = 0xFF; } } else { // size of the central directory (we just get the low 4 bytes) bytes[i++] = (byte)(SizeOfCentralDirectory & 0x000000FF); bytes[i++] = (byte)((SizeOfCentralDirectory & 0x0000FF00) >> 8); bytes[i++] = (byte)((SizeOfCentralDirectory & 0x00FF0000) >> 16); bytes[i++] = (byte)((SizeOfCentralDirectory & 0xFF000000) >> 24); // offset of the start of the central directory (we just get the low 4 bytes) bytes[i++] = (byte)(StartOfCentralDirectory & 0x000000FF); bytes[i++] = (byte)((StartOfCentralDirectory & 0x0000FF00) >> 8); bytes[i++] = (byte)((StartOfCentralDirectory & 0x00FF0000) >> 16); bytes[i++] = (byte)((StartOfCentralDirectory & 0xFF000000) >> 24); } // zip archive comment if ((comment == null) || (comment.Length == 0)) { // no comment! bytes[i++] = (byte)0; bytes[i++] = (byte)0; } else { // the size of our buffer defines the max length of the comment we can write if (commentLength + i + 2 > bytes.Length) { commentLength = (Int16)(bytes.Length - i - 2); } bytes[i++] = (byte)(commentLength & 0x00FF); bytes[i++] = (byte)((commentLength & 0xFF00) >> 8); if (commentLength != 0) { // now actually write the comment itself into the byte buffer for (j = 0; (j < commentLength) && (i + j < bytes.Length); j++) { bytes[i + j] = block[j]; } i += j; } } // s.Write(bytes, 0, i); return(bytes); }
// из списка слов находим базовые // вход - список слов на русском // выход - массив базовых слова private static List <string>[] FindBaseWord(List <string> lst) { List <string> rl1 = new List <string>(); List <string> rl2 = new List <string>(); List <string> rl3 = new List <string>(); List <string> rl4 = new List <string>(); List <string>[] res = new List <string> [4]; res[0] = rl1; // сущ res[1] = rl2; // прил res[2] = rl3; // глаг res[3] = rl4; // проч if (lst.Count == 0) { return(res); } string v = "индульгенция"; foreach (string v3 in lst) { v = v + " " + v3; } string v2 = ""; System.Text.Encoding utf8 = System.Text.Encoding.UTF8; byte[] b4 = utf8.GetBytes(v.ToLower()); for (int j = 0; j < b4.Length; j++) { if (b4[j] != 32) { v2 += "%" + b4[j].ToString("X"); } else { v2 += "+"; } } v2 = "http://goldlit.ru/component/slog?words=" + v2; System.Net.WebClient cl = new System.Net.WebClient(); cl.Encoding = System.Text.Encoding.UTF8; string re = ""; bool isNeedReadPage = true; int CountTry = 0; while (isNeedReadPage) { try { re = cl.DownloadString(v2); isNeedReadPage = false; } catch { System.Threading.Thread.Sleep(TimeToSleepMs); CountTry++; if (CountTry == MaxTryToReadPage) { Log.Write("words ERROR: не удолось получить базовые слова", v2, v.Replace("индульгенция ", "")); Log.Store("words", re); re = ""; isNeedReadPage = false; } } } cl.Dispose(); if (re == "") { Log.Write("words ERROR: длина страницы нулевая"); return(res); } Log.Store("words", re); int ii1 = re.IndexOf("Начальная форма"); while (ii1 != -1) { re = re.Substring(ii1); re = re.Substring(re.IndexOf(":") + 1); string v5 = re.Substring(0, re.IndexOf("<")).ToLower().TrimEnd().TrimStart(); re = re.Substring(re.IndexOf("Часть речи") + 1); re = re.Substring(re.IndexOf(":") + 1); string v5_s = re.Substring(0, re.IndexOf("<")).ToLower().TrimEnd().TrimStart(); if (v5_s == "существительное") { rl1.Add(v5); } else { if (v5_s == "прилагательное") { rl2.Add(v5); } else { if (v5_s.Length >= 6) { if (v5_s.Substring(0, 6) == "глагол") { rl3.Add(v5); } else { rl4.Add(v5); } } else { rl4.Add(v5); } } } ii1 = re.IndexOf("Начальная форма"); } rl1.Remove("индульгенция"); res[0] = rl1; // сущ res[1] = rl2; // прил res[2] = rl3; // глаг res[3] = rl4; // проч return(res); }
public static byte[] ToRiakString(this string value) { return(value == null ? null : RiakEncoding.GetBytes(value)); }
protected override void Serialize(string value, Stream stream) { var size = m_encoding.GetBytes(value, 0, value.Length, m_buf, 0); stream.Write(m_buf, 0, size); }
public static string ChangeEncoding(string Text, System.Text.Encoding FromEncoding, System.Text.Encoding ToEncoding) { return(ToEncoding.GetString(FromEncoding.GetBytes(Text))); }
/// <summary>Compile a c# script.</summary> /// <param name="code">The c# code to compile.</param> /// <param name="model">The model owning the script.</param> /// <param name="referencedAssemblies">Optional referenced assemblies.</param> /// <returns>Compile errors or null if no errors.</returns> public Results Compile(string code, IModel model, IEnumerable <MetadataReference> referencedAssemblies = null) { string errors = null; if (code != null) { // See if we have compiled the code already. If so then no need to compile again. PreviousCompilation compilation = previousCompilations?.Find(c => c.Code == code); bool newlyCompiled; if (compilation == null || compilation.Code != code) { newlyCompiled = true; bool withDebug = System.Diagnostics.Debugger.IsAttached; IEnumerable <MetadataReference> assemblies = GetReferenceAssemblies(referencedAssemblies, model.Name); // We haven't compiled the code so do it now. string sourceName; Compilation compiled = CompileTextToAssembly(code, assemblies, out sourceName); List <EmbeddedText> embeddedTexts = null; if (withDebug) { System.Text.Encoding encoding = System.Text.Encoding.UTF8; byte[] buffer = encoding.GetBytes(code); SourceText sourceText = SourceText.From(buffer, buffer.Length, encoding, canBeEmbedded: true); embeddedTexts = new List <EmbeddedText> { EmbeddedText.FromSource(sourceName, sourceText), }; } MemoryStream ms = new MemoryStream(); MemoryStream pdbStream = new MemoryStream(); using (MemoryStream xmlDocumentationStream = new MemoryStream()) { EmitResult emitResult = compiled.Emit( peStream: ms, pdbStream: withDebug ? pdbStream : null, xmlDocumentationStream: xmlDocumentationStream, embeddedTexts: embeddedTexts ); if (!emitResult.Success) { // Errors were found. Add then to the return error string. errors = null; foreach (Diagnostic diag in emitResult.Diagnostics) { if (diag.Severity == DiagnosticSeverity.Error) { errors += $"{diag.ToString()}{Environment.NewLine}"; } } // Because we have errors, remove the previous compilation if there is one. if (compilation != null) { previousCompilations.Remove(compilation); } compilation = null; } else { // No errors. // If we don't have a previous compilation, create one. if (compilation == null) { compilation = new PreviousCompilation() { ModelFullPath = model.FullPath }; if (previousCompilations == null) { previousCompilations = new List <PreviousCompilation>(); } previousCompilations.Add(compilation); } // Write the assembly to disk ms.Seek(0, SeekOrigin.Begin); string fileName = Path.Combine(Path.GetTempPath(), compiled.AssemblyName + ".dll"); using (FileStream file = new FileStream(fileName, FileMode.Create, FileAccess.Write)) ms.WriteTo(file); // Write XML Documentation file. string documentationFile = Path.ChangeExtension(fileName, ".xml"); xmlDocumentationStream.Seek(0, SeekOrigin.Begin); using (FileStream documentationWriter = new FileStream(documentationFile, FileMode.Create, FileAccess.Write)) xmlDocumentationStream.WriteTo(documentationWriter); // Set the compilation properties. ms.Seek(0, SeekOrigin.Begin); pdbStream.Seek(0, SeekOrigin.Begin); compilation.Code = code; compilation.Reference = compiled.ToMetadataReference(); compilation.CompiledAssembly = System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromStream(ms, pdbStream); } } } else { newlyCompiled = false; } if (compilation != null) { // We have a compiled assembly so get the class name. var regEx = new Regex(@"class\s+(\w+)\s"); var match = regEx.Match(code); if (!match.Success) { throw new Exception($"Cannot find a class declaration in script:{Environment.NewLine}{code}"); } var className = match.Groups[1].Value; // Create an instance of the class and give it to the model. var instanceType = compilation.CompiledAssembly.GetTypes().ToList().Find(t => t.Name == className); return(new Results(compilation.CompiledAssembly, instanceType.FullName, newlyCompiled)); } else { return(new Results(errors)); } } return(null); }
public static Utf8String From(string src) { return(new Utf8String(Encoding.GetBytes(src))); }
protected override long GetSize(string value) { m_buf = m_encoding.GetBytes(value); return(m_buf.Length); }
public static void Run() { Console.WriteLine("IP:"); string ipStr = Console.ReadLine(); IPAddress ip; if (!IPAddress.TryParse(ipStr, out ip)) { Console.WriteLine("IP地址[{0}]无效。", ipStr); return; } Console.WriteLine("Port:"); string portStr = Console.ReadLine(); ushort port; if (!ushort.TryParse(portStr, out port)) { Console.WriteLine("端口[{0}]无效。", portStr); return; } //IPAddress address = IPAddress.Parse("127.0.0.1"); IPAddress address = ip; IPEndPoint endPoint = new IPEndPoint(address, port); Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Bind(endPoint); socket.Listen(10); Console.WriteLine("开始监听,端口号:{0}.", endPoint.Port); while (true) { Socket client = socket.Accept(); Console.WriteLine(client.RemoteEndPoint); byte[] buffer = new byte[4096]; int length = client.Receive(buffer, buffer.Length, SocketFlags.None); System.Text.Encoding utf8 = System.Text.Encoding.UTF8; string requestString = utf8.GetString(buffer, 0, length); Console.WriteLine(requestString); string statusLine = "HTTP/1.1 200 OK\r\n"; byte[] statusLineBytes = utf8.GetBytes(statusLine); string responseBody = "<html><head><title>测试</title></head><body><h1>HAHAHAHAHAH</h1></body></html>"; byte[] responseBodyBytes = utf8.GetBytes(responseBody); string responseHeader = string.Format("Content-Type: text/html;charset=UTF-8\r\nContent-Length: {0}\r\n", responseBody.Length); byte[] responseHeaderBytes = utf8.GetBytes(responseHeader); client.Send(statusLineBytes); client.Send(responseHeaderBytes); client.Send(new byte[] { 13, 10 }); client.Send(responseBodyBytes); client.Close(); if (Console.KeyAvailable) { break; } } socket.Close(); }
internal static bool TestCase() { using (tcpHttp.tcpServer server = new tcpHttp.tcpServer()) { if (server.Start()) { fastCSharp.code.cSharp.tcpServer tcpServer = fastCSharp.code.typeAttribute.GetAttribute <fastCSharp.code.cSharp.tcpServer>(typeof(tcpHttp), false, false); System.Text.Encoding encoding = System.Text.Encoding.UTF8; string url = "http://" + tcpServer.Host + ":" + tcpServer.Port.toString() + "/"; using (tcpHttp.tcpClient client = new tcpHttp.tcpClient()) using (fastCSharp.net.webClient webClient = new fastCSharp.net.webClient()) { incValue = 0; //TCP调用 client.Inc(); if (incValue != 1) { return(false); } //HTTP+JSON调用 incValue = 0; webClient.KeepAlive = false; if (webClient.UploadData(url + "Inc", new byte[0]).deSerialize() != web.ajax.Object || incValue != 1) { return(false); } //HTTP+POST调用 incValue = 0; if (webClient.UploadValues(url + "Inc", new NameValueCollection()).deSerialize() != web.ajax.Object || incValue != 1) { return(false); } //HTTP+GET调用 incValue = 0; if (webClient.DownloadData(url + "Inc").deSerialize() != web.ajax.Object || incValue != 1) { return(false); } client.Set(3); if (incValue != 3) { return(false); } incValue = 0; if (webClient.UploadData(url + "Set", encoding.GetBytes(3.ToJson())).deSerialize() != web.ajax.Object || incValue != 3) { return(false); } //incValue = 0; //if (webClient.UploadValues(url + "Set", fastCSharp.emit.formGetter<.form.Get(new { a = 3 })).deSerialize() != web.ajax.Object || incValue != 3) return false; //incValue = 0; //if (webClient.DownloadData(url + "Set?" + urlQuery.query.Get(new { a = 3 }, encoding)).deSerialize() != web.ajax.Object || incValue != 3) return false; client.Add(2, 3); if (incValue != 5) { return(false); } incValue = 0; if (webClient.UploadData(url + "Add", encoding.GetBytes(fastCSharp.emit.jsonSerializer.ObjectToJson(new { a = 2, b = 3 }))).deSerialize() != web.ajax.Object || incValue != 5) { return(false); } //incValue = 0; //if (webClient.UploadValues(url + "Add", urlQuery.form.Get(new { a = 2, b = 3 })).deSerialize() != web.ajax.Object || incValue != 5) return false; //incValue = 0; //if (webClient.DownloadData(url + "Add?" + urlQuery.query.Get(new { a = 2, b = 3 }, encoding)).deSerialize() != web.ajax.Object || incValue != 5) return false; if (client.inc().Value != 6 || incValue != 6) { return(false); } incValue = 5; if (fastCSharp.emit.jsonParser.Parse <int>(webClient.UploadData(url + "inc", new byte[0]).deSerialize()) != 6 || incValue != 6) { return(false); } incValue = 5; if (fastCSharp.emit.jsonParser.Parse <int>(webClient.UploadValues(url + "inc", new NameValueCollection()).deSerialize()) != 6 || incValue != 6) { return(false); } incValue = 5; if (fastCSharp.emit.jsonParser.Parse <int>(webClient.DownloadData(url + "inc").deSerialize()) != 6 || incValue != 6) { return(false); } if (client.inc(8).Value != 9) { return(false); } if (fastCSharp.emit.jsonParser.Parse <int>(webClient.UploadData(url + "inc1", encoding.GetBytes(8.ToJson())).deSerialize()) != 9) { return(false); } //if (webClient.UploadValues(url + "inc1", urlQuery.form.Get(new { a = 8 })).deSerialize() != "9") return false; //if (webClient.DownloadData(url + "inc1?" + urlQuery.query.Get(new { a = 8 }, encoding)).deSerialize() != "9") return false; if (client.add(10, 13).Value != 23) { return(false); } if (fastCSharp.emit.jsonParser.Parse <int>(webClient.UploadData(url + "add", encoding.GetBytes(fastCSharp.emit.jsonSerializer.ObjectToJson(new { a = 10, b = 13 }))).deSerialize()) != 23) { return(false); } //if (webClient.UploadValues(url + "add", urlQuery.form.Get(new { a = 10, b = 13 })).deSerialize() != "23") return false; //if (webClient.DownloadData(url + "add?" + urlQuery.query.Get(new { a = 10, b = 13 }, encoding)).deSerialize() != "23") return false; int a; incValue = 15; if (client.inc(out a).Value != 16 || a != 15) { return(false); } incValue = 15; outReturn value = fastCSharp.emit.jsonParser.Parse <outReturn>(webClient.UploadData(url + "inc2", new byte[0]).deSerialize()); if (value.Return != 16 || value.outValue != 15) { return(false); } incValue = 15; value = fastCSharp.emit.jsonParser.Parse <outReturn>(webClient.UploadValues(url + "inc2", new NameValueCollection()).deSerialize()); if (value.Return != 16 || value.outValue != 15) { return(false); } incValue = 15; value = fastCSharp.emit.jsonParser.Parse <outReturn>(webClient.DownloadData(url + "inc2").deSerialize()); if (value.Return != 16 || value.outValue != 15) { return(false); } if (client.inc(20, out a).Value != 21 || a != 20) { return(false); } value = fastCSharp.emit.jsonParser.Parse <outReturn>(webClient.UploadData(url + "inc3", encoding.GetBytes(fastCSharp.emit.jsonSerializer.ObjectToJson(new { a = 20 }))).deSerialize()); if (value.Return != 21 || value.outValue != 20) { return(false); } //if (webClient.UploadValues(url + "inc3", urlQuery.form.Get(new { a = 20 })).deSerialize() != @"{""b"":20,""_Return_"":21}") return false; //if (webClient.DownloadData(url + "inc3?" + urlQuery.query.Get(new { a = 20 }, encoding)).deSerialize() != @"{""b"":20,""_Return_"":21}") return false; if (client.add(30, 33, out a).Value != 63 || a != 33) { return(false); } value = fastCSharp.emit.jsonParser.Parse <outReturn>(webClient.UploadData(url + "add1", encoding.GetBytes(fastCSharp.emit.jsonSerializer.ObjectToJson(new { a = 30, b = 33 }))).deSerialize()); if (value.Return != 63 || value.outValue != 33) { return(false); } //if (webClient.UploadValues(url + "add1", urlQuery.form.Get(new { a = 30, b = 33 })).deSerialize() != @"{""c"":33,""_Return_"":63}") return false; //if (webClient.DownloadData(url + "add1?" + urlQuery.query.Get(new { a = 30, b = 33 }, encoding)).deSerialize() != @"{""c"":33,""_Return_"":63}") return false; if (webClient.UploadData(url + "setCookie", encoding.GetBytes(fastCSharp.emit.jsonSerializer.ObjectToJson(new { name = "a", value = "b" }))).deSerialize() != web.ajax.Object) { return(false); } if (webClient.ResponseHeaders["Set-Cookie"] != "a=b") { return(false); } //if (webClient.UploadValues(url + "setCookie", urlQuery.form.Get(new { name = "c", value = "d" })).deSerialize() != web.ajax.Object) return false; //if (webClient.ResponseHeaders["Set-Cookie"] != "c=d") return false; //if (webClient.DownloadData(url + "setCookie?" + urlQuery.query.Get(new { name = "e", value = "f" }, encoding)).deSerialize() != web.ajax.Object) return false; //if (webClient.ResponseHeaders["Set-Cookie"] != "e=f") return false; if (!fastCSharp.emit.jsonParser.Parse <bool>(webClient.UploadData(url + "setSession", encoding.GetBytes("b".ToJson())).deSerialize())) { return(false); } webClient.Cookies.SetCookies(new Uri(url), webClient.ResponseHeaders["Set-Cookie"].Split(';')[0]); if (fastCSharp.emit.jsonParser.Parse <string>(webClient.UploadData(url + "getSession", new byte[0]).deSerialize()) != "b") { return(false); } //if (webClient.UploadValues(url + "setSession", urlQuery.form.Get(new { value = "d" })).deSerialize() != @"1") return false; //if (webClient.UploadValues(url + "getSession", new NameValueCollection()).deSerialize() != @"""d""") return false; //if (webClient.DownloadData(url + "setSession?" + urlQuery.query.Get(new { value = "f" }, encoding)).deSerialize() != @"1") return false; //if (webClient.DownloadData(url + "getSession").deSerialize() != @"""f""") return false; #if APP #else //HTTP文件上传 #if MONO FileInfo fileInfo = new FileInfo((@"..\..\Program.cs").pathSeparator()); #else FileInfo fileInfo = new FileInfo((@"..\..\tcpHttp.cs").pathSeparator()); #endif if (fastCSharp.emit.jsonParser.Parse <long>(webClient.UploadFile(url + "httpUpload", fileInfo.FullName).deSerialize()) != fileInfo.Length) { return(false); } #endif return(true); } } } return(false); }
private void encryptButton_Click(System.Object sender, System.EventArgs e) { string result = ""; string result2 = ""; if (asciiRadioButton.Checked) { result = ASCIIProvider.Encrypt(TextBox1.Text); result2 = ASCIIProvider.Decrypt(result); } else if (rijndaelRadioButton.Checked) { System.Text.Encoding myEnc = null; myEnc = System.Text.Encoding.GetEncoding("Windows-1252"); byte[] t = myEnc.GetBytes(TextBox1.Text.ToCharArray()); //convert string to bytes //Dim input() As Byte = m_utf8.GetBytes(TextBox1.Text.ToCharArray()) byte[] R = RijndaelProvider.Encrypt(t); result = myEnc.GetString(R); result2 = myEnc.GetString(RijndaelProvider.Decrypt(R)); } else if (desRadioButton.Checked) { result = DESProvider.Encrypt(TextBox1.Text); result2 = DESProvider.Decrypt(result); } else if (tripleDesRadioButton.Checked) { result = TripleDESProvider.Encrypt(TextBox1.Text); result2 = TripleDESProvider.Decrypt(result); } else if (xorRadioButton.Checked) { result = XorProvider.Encrypt(TextBox1.Text); result2 = XorProvider.Decrypt(result); } else if (aesRadioButton.Checked) { result = AESProvider.Encrypt(TextBox1.Text); result2 = AESProvider.Decrypt(result); } else if (rcTwoRadioButton.Checked) { result = RC2Provider.Encrypt(TextBox1.Text); result2 = RC2Provider.Decrypt(result); } else if (rsaRadioButton.Checked) { try { result = RSAProvider.Encrypt(TextBox1.Text); result2 = RSAProvider.Decrypt(result); } catch (Exception ex) { Interaction.MsgBox(ex.ToString()); TextBox1.Text = ex.ToString(); } } else { Interaction.MsgBox("Invalid Option!!!"); return; } outputLabel.Text = "Encrypted Result: " + result + " Decrypted Result: " + result2; }
internal static byte[] UrlEncodeToBytes(string str, Encoding e) { if (str == null) return null; byte[] bytes = e.GetBytes(str); return UrlEncode(bytes, 0, bytes.Length, false); }
int EmitHeader() { var commentBytes = Comment == null ? null : iso8859dash1.GetBytes(Comment); var filenameBytes = FileName == null ? null : iso8859dash1.GetBytes(FileName); var cbLength = Comment == null ? 0 : commentBytes.Length + 1; var fnLength = FileName == null ? 0 : filenameBytes.Length + 1; var bufferLength = 10 + cbLength + fnLength; var header = new byte[bufferLength]; var i = 0; // ID header[i++] = 0x1F; header[i++] = 0x8B; // compression method header[i++] = 8; byte flag = 0; if (Comment != null) { flag ^= 0x10; } if (FileName != null) { flag ^= 0x8; } // flag header[i++] = flag; // mtime if (!LastModified.HasValue) { LastModified = DateTime.Now; } var delta = LastModified.Value - _unixEpoch; var timet = (int)delta.TotalSeconds; Array.Copy(BitConverter.GetBytes(timet), 0, header, i, 4); i += 4; // xflg header[i++] = 0; // this field is totally useless // OS header[i++] = 0xFF; // 0xFF == unspecified // extra field length - only if FEXTRA is set, which it is not. //header[i++]= 0; //header[i++]= 0; // filename if (fnLength != 0) { Array.Copy(filenameBytes, 0, header, i, fnLength - 1); i += fnLength - 1; header[i++] = 0; // terminate } // comment if (cbLength != 0) { Array.Copy(commentBytes, 0, header, i, cbLength - 1); i += cbLength - 1; header[i++] = 0; // terminate } _baseStream._stream.Write(header, 0, header.Length); return(header.Length); // bytes written }
public static byte[] GetBytes(string str) { return(_encoding.GetBytes(str ?? string.Empty)); }
public Boolean AcceptClient() { Console.WriteLine("クライアントと接続待ち。"); Client = Listener.AcceptTcpClient(); Console.WriteLine( string.Format("クライアント({0},{1})と接続しました。", ((System.Net.IPEndPoint)Client.Client.RemoteEndPoint).Address, ((System.Net.IPEndPoint)Client.Client.RemoteEndPoint).Port) ); System.Net.Sockets.NetworkStream ns = Client.GetStream(); ns.ReadTimeout = ReadTimeout; ns.WriteTimeout = WriteTimeout; System.Text.Encoding enc = System.Text.Encoding.UTF8; Boolean disconnected = false; do { System.IO.MemoryStream ms = new System.IO.MemoryStream(); int resSize = 0; byte[] resBytes = new byte[1024]; try { do { resSize = ns.Read(resBytes, 0, resBytes.Length); if (resSize == 0) { disconnected = true; Console.WriteLine("クライアントが切断しました。"); break; } ms.Write(resBytes, 0, resSize); //ns.Write(resBytes, 0, resSize); } while (ns.DataAvailable || resBytes[resSize - 1] != '\n'); } catch (IOException e) { disconnected = true; Console.WriteLine("Read Timeoutで切断しました。" + e); } string resMsg = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length); ms.Close(); //Console.WriteLine("[" + resMsg + "]"); if (disconnected) { //メッセージ解析 //返信処理 Console.WriteLine("通信終了。"); } else { //メッセージ解析 disconnected = !msg.Input(resMsg); //msg.Input(resMsg); //返信処理 string sendMsg = msg.Output(); byte[] sendByte = enc.GetBytes(sendMsg + "\n"); byte[] sendData = msg.OutputBinary(); try { ns.Write(sendByte, 0, sendByte.Length); ns.Write(sendData, 0, sendData.Length); } catch (IOException e) { disconnected = true; Console.WriteLine("Write Timeoutで切断しました。" + e); } //Console.WriteLine("[" + sendMsg + "]" + " 送信。"); Console.WriteLine("送信 text:" + sendByte.Length.ToString() + "bytes, binary:" + sendData.Length.ToString()); } } while (!disconnected); ns.Close(); Client.Close(); return(true); }
public static void KbdUpdateEventQueues() { AltNumericKey[] AltNumericKeys = { new AltNumericKey(0x9B00, 4), new AltNumericKey(0x9D00, 6), new AltNumericKey(0x9F00, 1), new AltNumericKey(0xA100, 3), new AltNumericKey(0x9700, 7), new AltNumericKey(0x9900, 9), new AltNumericKey(0x9800, 8), new AltNumericKey(0xA000, 2), new AltNumericKey(0xA200, 0), new AltNumericKey(0x4c00, 5) }; System.UInt32 EventCount; INPUT_RECORD[] InRec = new INPUT_RECORD[1]; bool FoundAlt; byte AltNumeric = 0; if (SysKeyCount > SysKeyQue.GetUpperBound(0)) { return; } do { EventCount = 0; bool x = Windows.GetNumberOfConsoleInputEvents(Windows.GetStdHandle((int)StdHandles.STD_INPUT_HANDLE), ref EventCount); if (EventCount == 0) { return; } //Windows.ReadConsoleInput(Windows.GetStdHandle((int)StdHandles.STD_INPUT_HANDLE), ref InRec, out EventCount); Windows.ReadConsoleInput(new IntPtr(Windows.GetStdHandle((int)StdHandles.STD_INPUT_HANDLE)), InRec, 1, out EventCount); if (EventCount == 0) { return; } switch ((EventTypes)InRec[0].EventType) { case EventTypes.KEY_EVENT: if (SysKeyCount <= SysKeyQue.GetUpperBound(0)) { if (InRec[0].KeyEvent.bKeyDown) { SysKeyQue[SysKeyCount].wKeyEvent = InRec[0].KeyEvent; SysShiftState = SysKeyQue[SysKeyCount].skeShiftState; switch ((int)InRec[0].KeyEvent.wVirtualKeyCode) { case VK_SHIFT: case VK_CONTROL: case VK_MENU: break; default: System.Text.Encoding enc = System.Text.Encoding.GetEncoding(866); byte[] bb = enc.GetBytes(new char[] { InRec[0].KeyEvent.UnicodeChar }); SysKeyQue[SysKeyCount].skeKeyCode = TranslateKeyCode((byte)InRec[0].KeyEvent.wVirtualKeyCode, (byte)InRec[0].KeyEvent.wVirtualScanCode, /*InRec.KeyEvent.AsciiChar*/ bb[0], InRec[0].KeyEvent.dwControlKeyState); SysKeyQue[SysKeyCount].wKeyEvent = InRec[0].KeyEvent; if (SysKeyQue[SysKeyCount].skeKeyCode == 0) { return; } FoundAlt = false; if (((SysKeyQue[SysKeyCount].skeShiftState & 0x08) == 0x08) && ((InRec[0].KeyEvent.dwControlKeyState & 0x100) == 0)) { if (SysPlatform == 1) { for (int i = 0; i < 10; i++) { if (SysKeyQue[SysKeyCount].skeKeyCode == AltNumericKeys[i].VK) { AltNumeric = (byte)((AltNumeric * 10) + AltNumericKeys[i].Value); FoundAlt = true; } } } else if (((int)InRec[0].KeyEvent.wVirtualKeyCode >= VK_NUMPAD0) && ((int)InRec[0].KeyEvent.wVirtualKeyCode <= VK_NUMPAD9)) { AltNumeric = (byte)((AltNumeric * 10) + InRec[0].KeyEvent.wVirtualKeyCode - VK_NUMPAD0); FoundAlt = true; } } if (!FoundAlt) { SysKeyCount++; AltNumeric = 0; } break; } } else { if ((int)InRec[0].KeyEvent.wVirtualKeyCode == VK_MENU) { if (AltNumeric != 0) { SysKeyQue[SysKeyCount].skeKeyCode = AltNumeric; AltNumeric = 0; SysKeyCount++; } } } } break; case EventTypes.MOUSE_EVENT: if (SysMouCount <= SysMouQue.GetUpperBound(0)) { SysMouQue[SysMouCount].smePos.X = InRec[0].MouseEvent.dwMousePosition.X; SysMouQue[SysMouCount].smePos.Y = InRec[0].MouseEvent.dwMousePosition.Y; SysMouQue[SysMouCount].smeButtons = (byte)InRec[0].MouseEvent.dwButtonState; SysMouQue[SysMouCount].smeTime = (int)SysSysMouseCount(); SysMouCount++; } break; } } while (true && (SysKeyCount <= SysKeyQue.GetUpperBound(0))); }
public Boolean Input(string msg) { // //header string[] rowStr = msg.Split('\n'); string[] colStr; retmsg = ""; retByte = new Byte[] { }; string connect = "Close"; foreach (string s in rowStr) { string ws = s.Replace("\r", ""); colStr = ws.Split(':'); ws = ""; if (colStr[0].CompareTo("Connection") == 0) { connect = colStr[1]; Console.WriteLine(colStr[1]); } } colStr = rowStr[0].Split(' '); Boolean statusflag = true; //msg = msg.TrimEnd('\n'); //msg = msg.TrimEnd('\r'); msg = colStr[0]; Console.WriteLine("[" + msg + "]"); switch (msg) { case "GET": /* HTTP/0.9 404 Not Found * 指定されたURIのリソースを取り出す。HTTPの最も基本的な動作で、HTTP/0.9では唯一のメソッド。 */ Console.WriteLine("filePath" + colStr[1]); string fileName = @colStr[1]; fileName = fileName.TrimStart('/'); if (fileName.Length == 0) { fileName = "index.html"; } if (System.IO.File.Exists(fileName)) { Console.WriteLine("'" + fileName + "'は存在します。"); System.IO.FileInfo fi = new System.IO.FileInfo(fileName); //ファイルのサイズを取得 Console.WriteLine("ファイルサイズ:" + fi.Length + " bytes"); colStr = fileName.Split('.'); string fileType = colStr[colStr.Length - 1]; Console.WriteLine("ファイルタイプ:" + fileType); switch (fileType) { case "txt": case "html": case "htm": case "css": //System.Text.Encoding enc = System.Text.Encoding.UTF8; System.Text.Encoding enc = System.Text.Encoding.GetEncoding("Shift_JIS"); //テキストファイルの中身をすべて読み込む string c_str = System.IO.File.ReadAllText(fileName, enc); retByte = enc.GetBytes(c_str); retmsg = "HTTP/0.9 200 OK" + CRLF; //retmsg += "Content-Type: text/html; charset=UTF-8" + CRLF; //retmsg += "Server: private_httpd" + CRLF; //retmsg += "Status: 200 OK" + CRLF; retmsg += "Content-Length: " + retByte.Length.ToString() + CRLF; retmsg += "Connection: " + connect + CRLF; retmsg += CRLF; break; case "jpg": case "jpeg": case "png": case "gif": case "ico": retByte = System.IO.File.ReadAllBytes(fileName); retmsg = "HTTP/0.9 200 OK" + CRLF; //retmsg += "Server: private_httpd" + CRLF; //retmsg += "Status: 200 OK" + CRLF; retmsg += "Content-Length: " + retByte.Length.ToString() + CRLF; retmsg += "Connection: " + connect + CRLF; //retmsg += CRLF; break; default: retmsg = "HTTP/0.9 415 Unsupported Media Type" + CRLF; retmsg += "Server: private_httpd" + CRLF; retmsg += "Status: 415 Unsupported Media Type" + CRLF; retmsg += "Content-Length: " + retByte.Length.ToString() + CRLF; retmsg += "Connection: " + connect + CRLF; break; } } else { Console.WriteLine("'" + fileName + "'は存在しません。"); retmsg = "HTTP/0.9 404 Not Found" + CRLF; retmsg += "Server: private_httpd" + CRLF; retmsg += "Status: 404 Not Found" + CRLF; retmsg += "Connection: " + connect + CRLF; } if (connect == "Keep-Alive") { statusflag = true; } else { statusflag = false; } break; case "POST": /* HTTP/1.0 * GETとは反対にクライアントがサーバにデータを送信する。 * Webフォームや電子掲示板への投稿などで使用される。 * GETの場合と同じく、サーバはクライアントにデータを返すことができる。 */ case "PUT": /* HTTP/1.0 201 Created 202 Accepted * 指定したURIにリソースを保存する。 * URIが指し示すリソースが存在しない場合は、サーバはそのURIにリソースを作成する。 * 画像のアップロードなどが代表的。 */ case "HEAD": /* HTTP/1.0 200 OK * GETと似ているが、サーバはHTTPヘッダのみ返す。 * クライアントはWebページを取得せずともそのWebページが存在するかどうかを知ることができる。 * 例えばWebページのリンク先が生きているか、データを全て取得することなく検証することができる */ case "DELETE": // HTTP/1.0 指定したURIのリソースを削除する case "OPTIONS": // HTTP/1.1 サーバを調査する。例えば、サーバがサポートしているHTTPバージョンなどを知ることができる。 case "TRACE": /* HTTP/1.1 * TRACEサーバまでのネットワーク経路をチェックする。 * サーバは受け取ったメッセージのそれ自体をレスポンスのデータにコピーして応答する。 * WindowsのTracertやUNIXのTracerouteとよく似た動作。 */ case "CONNECT": /* HTTP/1.1 * TRACEサーバまでのネットワーク経路をチェックする。サーバは受け取ったメッセージのそれ自体をレスポンスのデータにコピーして応答する。 * WindowsのTracertやUNIXのTracerouteとよく似た動作。CONNECTTCPトンネルを接続する。 * 暗号化したメッセージをプロキシサーバを経由して転送する際に用いる。 */ retmsg = "HTTP/0.9 501 Not Implemented\n\n"; statusflag = false; break; default: retmsg = "HTTP/0.9 400 Bad Request\n\n"; statusflag = false; break; } //true:接続継続 false:接続終了 return(statusflag); }
private static sbyte[] GetSBytesForEncoding(System.Text.Encoding encoding, string s) { sbyte[] sbytes = new sbyte[encoding.GetByteCount(s)]; encoding.GetBytes(s, 0, s.Length, (byte[])(object)sbytes, 0); return(sbytes); }
public byte[] Encrypt(string stringToEncrypt) { return(Encrypt(_utfEncoder.GetBytes(stringToEncrypt))); }
internal static byte[] StringToByteArray(string value, System.Text.Encoding encoding) { byte[] a = encoding.GetBytes(value); return(a); }
/// <summary> /// Sends standard output text in a specified encoding. /// </summary> /// <param name="text"> /// A <see cref="string" /> containing text to send. /// </param> /// <param name="encoding"> /// A <see cref="System.Text.Encoding" /> containing a /// encoding to use when converting the text. /// </param> /// <remarks> /// <para>FastCGI output data is analogous to CGI/1.1 /// standard output data.</para> /// </remarks> public void SendOutput(string text, System.Text.Encoding encoding) { SendOutput(encoding.GetBytes(text)); }
/// <summary> /// Writes a line to the stream using the specified encoding /// </summary> /// <param name="encoding">Encoding used for writing the line</param> /// <param name="buf">The data to write</param> public void WriteLine(System.Text.Encoding encoding, string buf) { byte[] data; data = encoding.GetBytes((buf + "\r\n")); Write(data, 0, data.Length); }
/// <summary> /// Sends standard error text in a specified encoding. /// </summary> /// <param name="text"> /// A <see cref="string" /> containing text to send. /// </param> /// <param name="encoding"> /// A <see cref="System.Text.Encoding" /> containing a /// encoding to use when converting the text. /// </param> /// <remarks> /// <para>FastCGI error data is analogous to CGI/1.1 standard /// error data.</para> /// </remarks> public void SendError(string text, System.Text.Encoding encoding) { SendError(encoding.GetBytes(text)); }
public static void Write(Stream p_Stream, String p_Value, System.Text.Encoding encoding) { byte[] bytes = encoding.GetBytes(p_Value); Write(p_Stream, bytes); }
public static int ns(string s) { int i = s.IndexOf('\0'); i = -1 < i ? i : s.Length; return(e.GetBytes(s.Substring(0, i)).Length); }
/// <summary> /// Writes a line to the stream using the specified encoding /// </summary> /// <param name="encoding">Encoding used for writing the line</param> /// <param name="buf">The data to write</param> public void WriteLine(System.Text.Encoding encoding, string buf) { byte[] data; data = encoding.GetBytes(string.Format("{0}\r\n", buf)); Write(data, 0, data.Length); }
static public void Run() { Console.WriteLine("IP:"); string ipStr = Console.ReadLine(); IPAddress ip; if (!IPAddress.TryParse(ipStr, out ip)) { Console.WriteLine("IP地址[{0}]无效。", ipStr); return; } Console.WriteLine("Port:"); string portStr = Console.ReadLine(); ushort port; if (!ushort.TryParse(portStr, out port)) { Console.WriteLine("端口[{0}]无效。", portStr); return; } IPAddress address = ip; IPEndPoint endPoint = new IPEndPoint(address, port); TcpListener newserver = new TcpListener(endPoint); newserver.Start(); Console.WriteLine("开始监听..."); while (true) { TcpClient newclient = newserver.AcceptTcpClient(); Console.WriteLine("已经建立连接!"); NetworkStream ns = newclient.GetStream(); System.Text.Encoding utf8 = System.Text.Encoding.UTF8; byte[] request = new byte[4096]; int length = ns.Read(request, 0, 4096); string requestString = utf8.GetString(request, 0, length); Console.WriteLine(requestString); string statusLine = "HTTP/1.1 200 OK\r\n"; byte[] statusLineBytes = utf8.GetBytes(statusLine); string responseBody = "<html><head><title>测试tcplistener</title></head><body><h1>HAHAHAHAHAH</h1></body></html>"; byte[] responseBodyBytes = utf8.GetBytes(responseBody); string responseHeader = string.Format("Content-Type: text/html;charset=UTF-8\r\nContent-Length: {0}\r\n", responseBody.Length); byte[] responseHeaderBytes = utf8.GetBytes(responseHeader); ns.Write(statusLineBytes, 0, statusLineBytes.Length); ns.Write(responseHeaderBytes, 0, responseHeaderBytes.Length); ns.Write(new byte[] { 13, 10 }, 0, 2); ns.Write(responseBodyBytes, 0, responseBodyBytes.Length); newclient.Close(); if (Console.KeyAvailable) { break; } } newserver.Stop(); }
private static string UriEncodeFragment(string text, Encoding encoding) { if (text == null) throw new ArgumentNullException("text"); if (encoding == null) throw new ArgumentNullException("encoding"); if (text.Length == 0) return text; StringBuilder builder = new StringBuilder(); byte[] data = encoding.GetBytes(text); for (int i = 0; i < data.Length; i++) { if (_allowedFragmentCharacters[data[i]]) builder.Append((char)data[i]); else builder.Append('%').Append(data[i].ToString("x2")); } return builder.ToString(); }
/// <summary> /// Writes a UTF-8 encoded string to the model file. /// </summary> /// /// <param name="data"> /// The string data to be persisted. /// </param> protected override void WriteString(string data) { mOutput.WriteByte((byte)(mEncoding.GetByteCount(data) / 256)); mOutput.WriteByte((byte)(mEncoding.GetByteCount(data) % 256)); mOutput.Write(mEncoding.GetBytes(data), 0, mEncoding.GetByteCount(data)); }
/// <summary> /// Remember to manage the URL and set it to some defualt stuff /// </summary> public void setDownLoadedBytes(string HTMLData) { if (!string.IsNullOrEmpty(HTMLData)) { DownloadedBytes = StrToByteArray(HTMLData); _WasDownloaded = true; _ContentType = "text/html"; _ContentLocation = " "; _TextEncoding = System.Text.Encoding.GetEncoding("Windows-1252"); //'Me.Url = _ContentLocation if (IsHtml) { _DownloadedBytes = _TextEncoding.GetBytes(ProcessHtml(ToString())); } if (IsCss) { _DownloadedBytes = _TextEncoding.GetBytes(ProcessCss(ToString())); } if (Storage != Builder.FileStorage.Memory) { SaveToFile(); } } }
public string Decode(string data, System.Text.Encoding encoding = null) { encoding = encoding ?? System.Text.Encoding.UTF8; return(Convert.ToBase64String(encoding.GetBytes(data))); }