public static void ProcessCommand(string command, Stream io, int security, string user, Encoding encoding) { if (String.IsNullOrWhiteSpace(command)) { return; } try { byte[] writebuffer; var cmdsplit = command.Split(' '); if (cmdsplit.Length < 1) return; var label = cmdsplit[0]; if (SBWAPI.PluginManager.Default.ProcessCommand(label, command, io, security, user, encoding)) return; if (command.StartsWith("#")) { if (security < 4) { writebuffer = encoding.GetBytes( "\u001B[31mYou do not have permission to send special commands\u001B[0m\r\n"); io.Write(writebuffer, 0, writebuffer.Length); return; } if (CommandProcessors.ContainsKey(label)) CommandProcessors[label](command, io, security, user, encoding); return; } if (command.StartsWith("/")) { if (security < 3) { writebuffer = encoding.GetBytes( "\u001B[31mYou do not have permission to send commands\u001B[0m\r\n"); io.Write(writebuffer, 0, writebuffer.Length); return; } if (CommandProcessors.ContainsKey(label)) CommandProcessors[label](command, io, security, user, encoding); else { ServerHandler.ProcessHandler.ExtOutput(string.Format("<{0}> {1}", user, command)); ServerHandler.ProcessHandler.Instance.Command(command.Remove(0, 1)); } return; } CommandProcessors["\uFFFF"](command, io, security, user, encoding); } catch { } }
/// <summary> /// aes 加密 /// </summary> /// <param name="toEncrypt"></param> /// <param name="key"></param> /// <param name="encoding">加密编码方式 默认为 utf-8 </param> /// <returns></returns> public static string Encrypt(string toEncrypt, string key, Encoding encoding = null) { string result = string.Empty; if (string.IsNullOrEmpty(key)) throw new ArgumentNullException("key", "key值不能为空"); if (string.IsNullOrEmpty(toEncrypt)) return result; if (encoding==null) encoding=Encoding.UTF8; try { byte[] keyArray = encoding.GetBytes(key);// ToByte(key); byte[] toEncryptArray = encoding.GetBytes(toEncrypt); var resultArray = Encrypt(keyArray, toEncryptArray); result = Convert.ToBase64String(resultArray); } catch { } return result; }
//--- Extension Methods --- /// <summary> /// Write a string to <see cref="Stream"/> /// </summary> /// <param name="stream">Target <see cref="Stream"/></param> /// <param name="encoding">Encoding to use to convert the string to bytes</param> /// <param name="text">Regular string or composite format string to write to the <see cref="Stream"/></param> /// <param name="args">An System.Object array containing zero or more objects to format.</param> public static void Write(this Stream stream, Encoding encoding, string text, params object[] args) { const int bufferSize = BUFFER_SIZE / sizeof(char); if(text.Length > bufferSize) { // to avoid a allocating a byte array of greater than 64k, we chunk our string writing here if(args.Length != 0) { text = string.Format(text, args); } var length = text.Length; var idx = 0; var buffer = new char[bufferSize]; while(true) { var size = Math.Min(bufferSize, length - idx); if(size == 0) { break; } text.CopyTo(idx, buffer, 0, size); stream.Write(encoding.GetBytes(buffer, 0, size)); idx += size; } } else { if(args.Length == 0) { stream.Write(encoding.GetBytes(text)); } else { stream.Write(encoding.GetBytes(string.Format(text, args))); } } }
public BoundaryStreamReader(string boundary, Stream baseStream, Encoding streamEncoding, int bufferLength) { if (baseStream == null) { throw new ArgumentNullException("baseStream"); } if (!baseStream.CanSeek || !baseStream.CanRead) { throw new ArgumentException("baseStream must be a seekable readable stream."); } if (bufferLength < boundary.Length + 6) { throw new ArgumentOutOfRangeException( "bufferLength", "The buffer needs to be big enough to contain the boundary and control characters (6 bytes)"); } this.Log = NullLogger<IOLogSource>.Instance; this.BaseStream = baseStream; // by default if unspecified an encoding should be ascii // some people are of the opinion that utf-8 should be parsed by default // or that it should depend on the source page. // Need to test what browsers do in the wild. Encoding = streamEncoding; Encoding.GetBytes("--" + boundary); this.beginBoundary = Encoding.GetBytes("\r\n--" + boundary); this.localBuffer = new byte[bufferLength]; this.beginBoundaryAsString = "--" + boundary; this.AtPreamble = true; }
public MultipartWriter(string boundary, Stream underlyingStream, Encoding encoding) { this.boundary = boundary; this.underlyingStream = underlyingStream; this.encoding = encoding; this.beginBoundary = encoding.GetBytes("--" + boundary + "\r\n"); this.endBoundary = encoding.GetBytes("\r\n--" + boundary + "--\r\n"); }
public byte[] ParseView(IView view, string viewTemplate, Encoding encoding) { if (File.Exists(viewTemplate)) { return encoding.GetBytes(File.ReadAllText(viewTemplate)); } return encoding.GetBytes(viewTemplate + " not found"); }
public MultipartWriter(string boundary, Stream underlyingStream, Encoding encoding) { _boundary = boundary; _underlyingStream = underlyingStream; _encoding = encoding; _beginBoundary = encoding.GetBytes("--" + boundary +"\r\n" ); _endBoundary = encoding.GetBytes("\r\n--" + boundary + "--\r\n"); }
/// <summary> /// Creates an HMAC-MD5 fingerprint of the given data with the given key using the specified encoding /// </summary> /// <param name="data"></param> /// <param name="key"></param> /// <param name="enc"></param> /// <returns></returns> public static string HMACMD5(this string data, string key, Encoding enc) { var hmacKey = enc.GetBytes(key); var hmacData = enc.GetBytes(data); using (var hmacMd5 = new HMACMD5(hmacKey)) { return hmacMd5.ComputeHash(hmacData).ToHex().ToLower(); } }
public static byte[] CompressToByte(char[] str, bool needheadflag, Encoding enc) { if (str.Length < zipsizemin) return enc.GetBytes(str); Byte[] bTytes = enc.GetBytes(str); Byte[] retbytes = Compress(bTytes, needheadflag, enc); return retbytes; }
public StaticContentFilter(HttpResponse response, string imagePrefix, string javascriptPrefix, string cssPrefix) { this._Encoding = response.Output.Encoding; this._ResponseStream = response.Filter; this._ImagePrefix = _Encoding.GetBytes(imagePrefix); this._JavascriptPrefix = _Encoding.GetBytes(javascriptPrefix); this._CssPrefix = _Encoding.GetBytes(cssPrefix); }
public static int Authenticate(string user, string pass, Stream status, Encoding encoding) { var passhash = Sha1Hash(pass); byte[] b; if (Config.UserCache[user + "§custom"] == "true") { b = encoding.GetBytes("\u001B[36mAuthenticating against local hash...\u001B[0m\r\n"); status.Write(b, 0, b.Length); if (passhash != Config.UserCache[user + "§hash"]) { return -1; } int seclvlc; var prc = int.TryParse(Config.UserCache[user], out seclvlc); return prc ? seclvlc : 0; } b = encoding.GetBytes("\u001B[36mAuthenticating with minecraft.net\r\n"); status.Write(b, 0, b.Length); var olresult = ValidateOnline(user, pass); if (olresult == null) { b=encoding.GetBytes("\u001B[31mError connecting to minecraft.net\r\n"); status.Write(b, 0, b.Length); b = encoding.GetBytes("\u001B[36mAuthenticating against local cache...\u001B[0m\r\n"); status.Write(b, 0, b.Length); if (Config.UserCache[user + "§hash"] != "") { if (passhash == Config.UserCache[user + "§hash"]) { olresult = true; } else return -1; } else { b = encoding.GetBytes("\u001B[31mPassword not availible in cache\u001B[0m\r\n"); status.Write(b, 0, b.Length); return -1; } } if (olresult == false) return -1; Config.UserCache[user + "§hash"] = passhash; int seclvl; var pr = int.TryParse(Config.UserCache[user], out seclvl); return pr ? seclvl : 0; }
internal static void WriteStringInternalDynamic(this Stream stream, Encoding encoding, string value, char end) { byte[] data; data = encoding.GetBytes(value); stream.Write(data, 0, data.Length); data = encoding.GetBytes(end.ToString()); stream.Write(data, 0, data.Length); }
/// <summary> /// /// </summary> /// <param name="plainText"></param> /// <param name="key"></param> /// <param name="encoding"></param> /// <param name="encryptedType"></param> /// <returns></returns> public override string DoEncrypt(string plainText, string key, Encoding encoding, DataMode encryptedType) { byte[] keyByte = encoding.GetBytes(key); HMACMD5 hmacMD5 = new HMACMD5(keyByte); byte[] messageBytes = encoding.GetBytes(plainText); byte[] hashMessage = hmacMD5.ComputeHash(messageBytes); return BytesToString(hashMessage, encoding, encryptedType); }
private StreamingMultiPartParser(Stream bodyStream, Encoding encoding, string boundary, byte[] outerBoundary, Buffer buffer) { this.bodyStream = bodyStream; this.encoding = encoding; this.boundary = encoding.GetBytes("--" + boundary); this.outerBoundary = outerBoundary; this.dashes = encoding.GetBytes("--"); this.newLine = encoding.GetBytes("\r\n"); this.buffer = buffer; }
/// <summary>コンストラクタ</summary> public CheckCharCode(string startChar, string endChar, Encoding stringEncoding) { this.StartChar = startChar; this.EndChar = endChar; this.StringEncoding = stringEncoding; // 1文字のバイトデータを数値データ(long)に変換 this.StartCode = PubCmnFunction.GetLongFromByte(stringEncoding.GetBytes(startChar)); this.EndCode = PubCmnFunction.GetLongFromByte(stringEncoding.GetBytes(endChar)); }
/// <summary> /// Prepare a Multipart Parser with a specific encoding /// </summary> /// <param name="stream">The HTTP multipart request body</param> /// <param name="encoding">The encoding to use when parsing</param> public HTTPMultipartParser(Stream stream, Encoding encoding) { this.stream = stream; this.encoding = encoding; Fields = new Dictionary<string, MultipartData>(); CRbytes = encoding.GetBytes("\r"); LFbytes = encoding.GetBytes("\n"); CRLFbytes = encoding.GetBytes("\r\n"); finishBytes = encoding.GetBytes("--"); }
public void Init() { var random = new Random(); _protocolVersion = (uint) random.Next(0, int.MaxValue); _requestId = (uint) random.Next(0, int.MaxValue); _encoding = Encoding.Unicode; _oldPath = random.Next().ToString(CultureInfo.InvariantCulture); _oldPathBytes = _encoding.GetBytes(_oldPath); _newPath = random.Next().ToString(CultureInfo.InvariantCulture); _newPathBytes = _encoding.GetBytes(_newPath); }
public MakeRecordDictionary(IDictionary<string, byte[]> dictionary, string pathname, string firstElementMarker, string recordStartingTag, string identifierAttribute) { _dictionary = dictionary; _firstElementTag = firstElementMarker; // May be null, which is fine. _recordStartingTag = recordStartingTag; _elementSplitter = new FastXmlElementSplitter(pathname); _utf8 = Encoding.UTF8; _identifierWithDoubleQuote = _utf8.GetBytes(identifierAttribute + "=\""); _identifierWithSingleQuote = _utf8.GetBytes(identifierAttribute + "='"); }
public ResponseFilter(Stream baseStream, Encoding encoding, IResponseTransformer responseTransformer) { this.encoding = encoding; this.responseTransformer = responseTransformer; BaseStream = baseStream; StartStringUpper = encoding.GetBytes("<HEAD"); StartStringLower = encoding.GetBytes("<head"); StartCloseChar = encoding.GetBytes("> "); EndStringUpper = encoding.GetBytes("</HEAD>"); EndStringLower = encoding.GetBytes("</head>"); }
/// <summary> /// return byte given default value and using given encoding /// </summary> /// <param name="defaultValue"></param> /// <param name="encoding"></param> /// <returns></returns> private static byte GetByte(DefaultValue defaultValue, Encoding encoding) { switch (defaultValue) { case DefaultValue.Space: return encoding.GetBytes(" ")[0]; case DefaultValue.Zero: return encoding.GetBytes("0")[0]; default: //including DefaultValue.LowValue: return 0; } }
protected override void OnInit() { var random = new Random(); _protocolVersion = (uint) random.Next(0, int.MaxValue); _requestId = (uint) random.Next(0, int.MaxValue); _encoding = Encoding.Unicode; _newLinkPath = random.Next().ToString(CultureInfo.InvariantCulture); _newLinkPathBytes = _encoding.GetBytes(_newLinkPath); _existingPath = random.Next().ToString(CultureInfo.InvariantCulture); _existingPathBytes = _encoding.GetBytes(_existingPath); }
/// <summary> /// 返回加密后的 /// </summary> /// <param name="data"></param> /// <param name="key"></param> /// <param name="encoding">如果为空,则默认Utf-8</param> /// <returns> 解密后的字节流通过Base64转化 </returns> public static string EncryptBase64(string data, string key, Encoding encoding = null) { if (encoding == null) encoding = Encoding.UTF8; var bytes = encoding.GetBytes(data); var keyBytes = encoding.GetBytes(key); byte[] resultbytes = Encrypt(keyBytes, encoding, bytes); return Convert.ToBase64String(resultbytes); }
/// <summary> /// 返回加密后的 /// </summary> /// <param name="data"></param> /// <param name="key"></param> /// <param name="encoding">如果为空,则默认Utf-8</param> /// <returns></returns> public static string EncryptUtf8(string data, string key, Encoding encoding = null) { if (encoding == null) encoding = Encoding.UTF8; var bytes = encoding.GetBytes(data); var keyBytes = encoding.GetBytes(key); byte[] resultbytes = Encrypt(keyBytes, encoding, bytes); return Encoding.UTF8.GetString(resultbytes); }
private int PutParamInfo(byte[] buffer, int offset, int dataSize, ushort serverDataType, Encoding encoding) { encoding.GetBytes(serverDataType.ToString("X8")).CopyTo(buffer, offset); offset += 8; encoding.GetBytes(serverDataType.ToString("X2")).CopyTo(buffer, offset); offset += 2; encoding.GetBytes("01").CopyTo(buffer, offset); offset += 2; encoding.GetBytes(this.name.PadRight(20)).CopyTo(buffer, offset); offset += 20; return offset; }
/// AES encryption public static string AesEncoding(string data, string key, Encoding encoding) { var hashMd5 = new MD5CryptoServiceProvider(); byte[] keyArray = hashMd5.ComputeHash(encoding.GetBytes(key)); byte[] toEncryptArray = encoding.GetBytes(data); RijndaelManaged rijndaelManaged = new System.Security.Cryptography.RijndaelManaged(); rijndaelManaged.Key = keyArray; rijndaelManaged.Mode = System.Security.Cryptography.CipherMode.ECB; rijndaelManaged.Padding = System.Security.Cryptography.PaddingMode.PKCS7; ICryptoTransform cTransform = rijndaelManaged.CreateEncryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return Convert.ToBase64String(resultArray, 0, resultArray.Length); }
/// <summary> 3des加密字符串(指定编码类型) /// </summary> /// <param name="srcString">要加密的字符串</param> /// <param name="key">密钥</param> /// <param name="encoding">编码方式</param> /// <returns>加密后并经 base64 编码的字符串</returns> public static string Encrypt3DES(string srcString, string key, Encoding encoding) { TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider(); MD5CryptoServiceProvider hashMD5 = new MD5CryptoServiceProvider(); DES.Key = hashMD5.ComputeHash(encoding.GetBytes(key)); DES.Mode = CipherMode.ECB; ICryptoTransform DESEncrypt = DES.CreateEncryptor(); byte[] Buffer = encoding.GetBytes(srcString); return Convert.ToBase64String(DESEncrypt.TransformFinalBlock(Buffer, 0, Buffer.Length)); }
private static string Gethmacsha512(Encoding encoding, string apiSecret, string url) { // doing the encoding var keyByte = encoding.GetBytes(apiSecret); string result; using (var hmacsha512 = new HMACSHA512(keyByte)) { hmacsha512.ComputeHash(encoding.GetBytes(url)); result = ByteToString(hmacsha512.Hash); } return result; }
public ResponseFilter(Stream baseStream, Encoding encoding, IResponseTransformer responseTransformer) { this.encoding = encoding; this.responseTransformer = responseTransformer; BaseStream = baseStream; InitSearchArrays(); okWhenAdjacentToScriptStartUpper = new[] { encoding.GetBytes("<NOSCRIPT"), encoding.GetBytes("<!--") }; okWhenAdjacentToScriptStartLower = new[] { encoding.GetBytes("<noscript"), encoding.GetBytes("<!--") }; okWhenAdjacentToScriptEndUpper = new[] { encoding.GetBytes("</NOSCRIPT>"), encoding.GetBytes("-->") }; okWhenAdjacentToScriptEndLower = new[] { encoding.GetBytes("</noscript>"), encoding.GetBytes("-->") }; currentStartStringsToSkip = new bool[startStringUpper.Length]; startCloseChar = encoding.GetBytes("> "); whiteSpaceChar = encoding.GetBytes("\t\n\r "); }
public static byte[] GetBytes(string contents, Encoding enc) { byte[] results; if (!BitConverter.IsLittleEndian) { results = enc.GetBytes(contents); } else { results = enc.GetBytes(contents).Reverse().ToArray(); } return results; }
/// <summary> /// 发送请求数据 /// </summary> /// <param name="target">请求Url</param> /// <param name="method">GET/POST</param> /// <param name="encoding">编码</param> /// <param name="timeOut">请求超时(秒)</param> /// <param name="parameters">请求参数key=value</param> /// <returns></returns> public string SendRequest(string target, string method, System.Text.Encoding encoding, int timeOut, params string[] parameters) { HttpWebResponse response = null; HttpWebRequest request = null; Stream responseStream = null; string result = string.Empty; try { string str = ""; if ((parameters != null) && (parameters.Length >= 1)) { str = string.Join("&", parameters); } byte[] bytes = encoding.GetBytes(str); string requestUriString = target; request = (HttpWebRequest)WebRequest.Create(requestUriString); HttpRequestCachePolicy policy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore); request.CachePolicy = policy; request.Timeout = timeOut * 0x3e8; request.KeepAlive = false; request.Method = method.ToString().ToUpper(); bool flag = false; flag = request.Method.ToUpper() == "POST"; if (flag) { request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = bytes.Length; } else { if (target.Contains("?")) { target = target.Trim(new char[] { '&' }) + "&" + str; } else { target = target.Trim(new char[] { '?' }) + "?" + str; } } request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; SV1; .NET CLR 2.0.1124)"; request.Headers.Add("Cache-Control", "no-cache"); request.Accept = "*/*"; request.Credentials = CredentialCache.DefaultCredentials; if (flag) { Stream requestStream = request.GetRequestStream(); requestStream.Write(bytes, 0, bytes.Length); requestStream.Close(); } response = (HttpWebResponse)request.GetResponse(); responseStream = response.GetResponseStream(); List <byte> list = new List <byte>(); for (int i = responseStream.ReadByte(); i != -1; i = responseStream.ReadByte()) { list.Add((byte)i); } Stream stream2 = new MemoryStream(list.ToArray()); StreamReader sr = new StreamReader(stream2, encoding); result = sr.ReadToEnd(); sr.Close(); stream2.Close(); } catch (WebException ex) { } catch (Exception ex1) { } finally { if (request != null) { request.Abort(); } if (responseStream != null) { responseStream.Close(); } if (response != null) { response.Close(); } } return(result); }
/// <summary> /// 将字符串使用base64算法加密 /// </summary> /// <param name="SourceString">待加密的字符串</param> /// <param name="Ens">System.Text.Encoding 对象,如创建中文编码集对象: /// System.Text.Encoding.GetEncoding("gb2312")</param> /// <returns>编码后的文本字符串</returns> public static string EncodingString(string SourceString, System.Text.Encoding Ens) { return(Convert.ToBase64String(Ens.GetBytes(SourceString))); }
/// <summary> /// base64编码 加密 /// </summary> /// <param name="sourceString">需要加密字符串</param> /// <param name="encoding">编码格式</param> /// <returns></returns> public static string Encode(string sourceString, System.Text.Encoding encoding) { return(Convert.ToBase64String(encoding.GetBytes(sourceString))); }
private SocketResult Send(SocketClientConfig config, string content) { SocketLogMgt.SetLog(this, "============================================="); SocketLogMgt.SetLog(this, ": Send Data Begin."); try { Socket socket = Connect(config); if (socket == null) { return(SocketResult.Disconnect); // failed to connect to remote server } //string strSend = SocketHelper.PackMessageBlock(content); string strSend = content; if (SocketLogMgt.DumpData) { SocketLogMgt.SetLog(this, ": Data to be sent."); SocketLogMgt.SetLog(this, "------------------------"); SocketLogMgt.SetLog(this, strSend); SocketLogMgt.SetLog(this, "------------------------"); } Byte[] bytesSent = null; System.Text.Encoding encoder = GetEncoder(); if (encoder != null) { bytesSent = encoder.GetBytes(strSend); } if (bytesSent == null) { SocketLogMgt.SetLog(SocketLogType.Error, this, _socketID + "Encode data failed."); return(SocketResult.SendFailed); // failed to encoding outgoing message } _allDone.Reset(); SocketLogMgt.SetLog(this, _socketID + "Send data."); socket.BeginSend(bytesSent, 0, bytesSent.Length, 0, new AsyncCallback(OnDataSent), null); bool rec = true; string strReceived = null; StringBuilder sb = new StringBuilder(); Byte[] bytesReceived = new Byte[config.ReceiveResponseBufferSizeKB * 1024]; while (rec) { if (!socket.Connected) { SocketLogMgt.SetLog(SocketLogType.Warning, this, _socketID + "Connection closed."); break; } SocketLogMgt.SetLog(this, _socketID + "Receive data."); int bytes = socket.Receive(bytesReceived, bytesReceived.Length, 0); SocketLogMgt.SetLog(this, _socketID + "Receive succeeded. " + bytes.ToString() + " bytes."); string str = encoder.GetString(bytesReceived, 0, bytes); sb.Append(str); strReceived = sb.ToString(); //rec = !SocketHelper.FindBlockEnding(strReceived); rec = false; // This socket client assume that there is a completed HL7 message (without MLLP signs) in one Receive(); } _allDone.WaitOne(); // need not to set timeout here, we can depend on socket timeout of the Receive() method. if (SocketLogMgt.DumpData) { SocketLogMgt.SetLog(this, ": Data received."); SocketLogMgt.SetLog(this, "------------------------"); SocketLogMgt.SetLog(this, strReceived); SocketLogMgt.SetLog(this, "------------------------"); } //strReceived = SocketHelper.UnpackMessageBlock(strReceived); strReceived = SocketHelper.TrimMessageBlock(strReceived); return(new SocketResult(SocketResultType.Success, strReceived)); // send and receive success } catch (SocketException se) { SocketLogMgt.SetLastError(this, se); SocketResult ret = new SocketResult(se); ret.Type = SocketResultType.Unknown; return(ret); // meet exception during sending or receiving // (for example, it may be caused by the connection has expired [controled by the lower levels] // after some period of time without sending or receving), // and we need to recreate a new connection and try again, // please see SendData() for details. } catch (Exception err) { SocketLogMgt.SetLastError(this, err); return(new SocketResult(err)); } finally { SocketLogMgt.SetLog(this, ": Send Data End"); SocketLogMgt.SetLog(this, "=============================================\r\n"); } }
/// <summary> /// 字符串转换为Base64字符串 /// </summary> /// <param name="str">字符串</param> /// <returns></returns> public static string ToBase64(string str) { System.Text.Encoding asciiEncoding = System.Text.Encoding.ASCII; byte[] byteArray = asciiEncoding.GetBytes(str); return(Convert.ToBase64String(byteArray, 0, byteArray.Length)); }
/// <summary> /// Converts a plaintext string to a byte array. /// </summary> /// <returns> A byte array derived from a plaintext string </returns> private byte[] ConvertToByteArray(string str, System.Text.Encoding encoding) { return(encoding.GetBytes(str)); }
/// <summary> /// Encode the string read by the stringreader into the /// stringwriter. This implementation does not encode /// the characters where encoding is optional, and does /// not encode spaces or tabs (except at the end of a line). /// /// Line breaks are converted to the RFC line break (CRLF). // The last linebreak is not included, if any---although this /// may change in the future. /// </summary> /// <param name="stringreader">The incoming string reader</param> /// <param name="stringwriter">The outgoing stringwriter</param> /// <param name="charset">The outgoing charset for the string</param> /// <param name="forceRFC2047">If true, force the encoding of all the /// <param name="offset">These are the number of characters that /// will appear outside this string, e.g. the header name, etc.</param> /// characters (not just those that are given in RFC2027).</param> public void Encode(StringReader stringreader, StringWriter stringwriter, System.Text.Encoding charset, bool forceRFC2047, int offset) { if (offset > QPEncoder.MAX_CHARS_PER_LINE - 15) { throw new MailException("Invalid offset (header name is too long): " + offset); } String line = null; bool forceencoding = false; if (charset == null) { charset = Utils.Configuration.GetInstance().GetDefaultCharset(); } while ((line = stringreader.ReadLine()) != null) { int columnposition = 0; byte[] bytes = charset.GetBytes(line); // see Rule #3 (spaces and tabs at end of line are encoded) StringBuilder blankendchars = new StringBuilder(""); int endpos = bytes.Length - 1; while (endpos >= 0 && (bytes[endpos] == 0x20 || bytes[endpos] == 0x09)) { blankendchars.Insert(blankendchars.Length, EncodeByte(bytes[endpos])); endpos--; } for (int i = 0; i <= endpos; i++) { String towrite = ""; if (forceencoding || NeedsEncoding(bytes[i], forceRFC2047)) { columnposition += 3; towrite = EncodeByte(bytes[i]); } else { columnposition += 1; // this is a single byte, so multibyte chars won't // be affected by this. towrite = charset.GetString(new byte[] { bytes[i] }); } if (offset + columnposition > QPEncoder.MAX_CHARS_PER_LINE) { stringwriter.Write("=" + QPEncoder.END_OF_LINE); columnposition = 0; } stringwriter.Write(towrite); } if (blankendchars.Length > 0) { if (offset + columnposition + blankendchars.Length > QPEncoder.MAX_CHARS_PER_LINE) { stringwriter.Write("=" + QPEncoder.END_OF_LINE); } stringwriter.Write(blankendchars); } if (stringreader.Peek() >= 0) { stringwriter.Write("\r\n"); } } }
public static byte[] GetBytes(string str) { return(vEncoding.GetBytes(str)); }
/// <summary> /// Purpose : This function converts the string to byte array /// </summary> /// <param name="data"></param> /// <returns></returns> public static byte[] GetByteArrayFromString(string data) { System.Text.Encoding encoder = Encoding.GetEncoding("ISO-8859-1"); byte[] value = encoder.GetBytes(data); return(value); }
private async void MainWindow_Loaded(object sender, RoutedEventArgs e) { f.Navigate(sa); TcpClient tcp = new TcpClient(ipaddress, 2001); Console.WriteLine("サーバー({0}:{1})と接続しました({2}:{3})。", ((System.Net.IPEndPoint)tcp.Client.RemoteEndPoint).Address, ((System.Net.IPEndPoint)tcp.Client.RemoteEndPoint).Port, ((System.Net.IPEndPoint)tcp.Client.LocalEndPoint).Address, ((System.Net.IPEndPoint)tcp.Client.LocalEndPoint).Port); ns = tcp.GetStream(); //send name byte[] sendBytes = enc.GetBytes(name + '\n'); ns.Write(sendBytes, 0, sendBytes.Length); //サーバーから送られたデータを受信する await Task.Run(async() => { while (true) { string resMsg = await resGetAsync(); status_update(resMsg); if (resMsg.IndexOf("全員") > -1) { break; } await Task.Delay(100); } //ゲームスタート!! //Get namelist while (true) { string temp = await resGetAsync(); if (temp.IndexOf("namelist[") > -1) { Console.WriteLine(temp); int i = 0; MatchCollection mc = Regex.Matches(temp, @"\{(.+?)\}", RegexOptions.Singleline); foreach (Match m in mc) { string tem = m.ToString().Replace("{", "").Replace("}", "").Replace("\r\n", "").Replace("\n", ""); namelist[i++] = tem; } break; } await Task.Delay(100); } int cnt = 0; foreach (string s in namelist) { this.Dispatcher.Invoke(() => { if (s != name) { if (cnt == 0) { name1.Name = s; name1.Text = s + "[0]"; } else if (cnt == 1) { name2.Name = s; name2.Text = s + "[0]"; } else { name3.Name = s; name3.Text = s + "[0]"; } cnt++; } else { name_me.Name = name; name_me.Text = name + "[0]"; } }); } await this.Dispatcher.Invoke(async() => { sa.status.Text = "読み込んでいます"; for (int i = 1; i <= 13; i++) { clover[i - 1] = new BitmapImage(); clover[i - 1].BeginInit(); clover[i - 1].UriSource = new Uri(System.IO.Path.GetDirectoryName(Application.ResourceAssembly.Location) + @"\tramp\clover\" + i.ToString() + ".png"); clover[i - 1].EndInit(); } for (int i = 1; i <= 13; i++) { heart[i - 1] = new BitmapImage(); heart[i - 1].BeginInit(); heart[i - 1].UriSource = new Uri(System.IO.Path.GetDirectoryName(Application.ResourceAssembly.Location) + @"\tramp\heart\" + i.ToString() + ".png"); heart[i - 1].EndInit(); } for (int i = 1; i <= 13; i++) { spade[i - 1] = new BitmapImage(); spade[i - 1].BeginInit(); spade[i - 1].UriSource = new Uri(System.IO.Path.GetDirectoryName(Application.ResourceAssembly.Location) + @"\tramp\spade\" + i.ToString() + ".png"); spade[i - 1].EndInit(); } for (int i = 1; i <= 13; i++) { dia[i - 1] = new BitmapImage(); dia[i - 1].BeginInit(); dia[i - 1].UriSource = new Uri(System.IO.Path.GetDirectoryName(Application.ResourceAssembly.Location) + @"\tramp\dia\" + i.ToString() + ".png"); dia[i - 1].EndInit(); } joker.BeginInit(); joker.UriSource = new Uri(System.IO.Path.GetDirectoryName(Application.ResourceAssembly.Location) + @"\tramp\joker.png"); joker.EndInit(); back.BeginInit(); back.UriSource = new Uri(System.IO.Path.GetDirectoryName(Application.ResourceAssembly.Location) + @"\tramp\back.jpg"); back.EndInit(); await Task.Delay(1500); sa.status.Text = "ゲーム開始を待機しています"; sendMes("OKREADY"); //ゲーム開始を待機する string temp = await resGetAsync(); while (true) { if (temp.IndexOf("gamestart") > -1) { break; } await Task.Delay(500); } //カードを初期化 for (int i = 0; i < 14; i++) { mycardV[i] = -1; } //カード情報をゲット while (true) { if (temp.IndexOf("cardinfo") > -1) { mycard = temp; MatchCollection kmc = Regex.Matches(temp, @"\[(.+?)\]"); MatchCollection vmc = Regex.Matches(temp, @"\{(.+?)\}"); int mCnt = 0; int mmCnt = 0; foreach (Match m in kmc) { foreach (Match mm in vmc) { if (mCnt == mmCnt) { string ms = m.ToString().Replace("[", "").Replace("]", ""); string mms = mm.ToString().Replace("{", "").Replace("}", ""); Console.WriteLine(ms + mms); mycardK[mCnt] = ms; mycardV[mCnt] = int.Parse(mms); } mmCnt++; } mmCnt = 0; mCnt++; } mycardR = mCnt; break; } await Task.Delay(500); temp = await resGetAsync(); } { Image img = new Image(); img.Source = back; img.Width = 28; img.Height = 100; sp1.Children.Add(img); } { Image img = new Image(); img.Source = back; img.Width = 28; img.Height = 100; sp2.Children.Add(img); } { Image img = new Image(); img.Source = back; img.Width = 28; img.Height = 100; sp3.Children.Add(img); } status.Text = ""; }); while (true) { updateCard(); await Task.Delay(1000);//カードを更新してゲームを進行していきます } }); //閉じる ns.Close(); tcp.Close(); Console.WriteLine("切断しました。"); }
/// <summary> /// Dispatches a string back to the client as a file. /// </summary> public static async Task Dispatch(this HttpResponse response, string responseText, string fileName, string contentType = "Application/octet-stream", System.Text.Encoding encoding = null) { response.Clear(); if (encoding == null) { encoding = Encoding.UTF8; } var bytes = encoding == Encoding.UTF8 ? responseText.GetUtf8WithSignatureBytes() : encoding.GetBytes(responseText); await response.Dispatch(bytes, fileName, contentType); }
///<summary> ///Write to memory address. See https://github.com/erfg12/memory.dll/wiki/writeMemory() for more information. ///</summary> ///<param name="code">address, module + pointer + offset, module + offset OR label in .ini file.</param> ///<param name="type">byte, 2bytes, bytes, float, int, string, double or long.</param> ///<param name="write">value to write to address.</param> ///<param name="file">path and name of .ini file (OPTIONAL)</param> ///<param name="stringEncoding">System.Text.Encoding.UTF8 (DEFAULT). Other options: ascii, unicode, utf32, utf7</param> ///<param name="RemoveWriteProtection">If building a trainer on an emulator (Ex: RPCS3) you'll want to set this to false</param> public bool WriteMemory(string code, string type, string write, string file = "", System.Text.Encoding stringEncoding = null, bool RemoveWriteProtection = true) { byte[] memory = new byte[4]; int size = 4; UIntPtr theCode; theCode = GetCode(code, file); if (theCode == null || theCode == UIntPtr.Zero || theCode.ToUInt64() < 0x10000) { return(false); } if (type.ToLower() == "float") { write = Convert.ToString(float.Parse(write, CultureInfo.InvariantCulture)); memory = BitConverter.GetBytes(Convert.ToSingle(write)); size = 4; } else if (type.ToLower() == "int") { memory = BitConverter.GetBytes(Convert.ToInt32(write)); size = 4; } else if (type.ToLower() == "byte") { memory = new byte[1]; memory[0] = Convert.ToByte(write, 16); size = 1; } else if (type.ToLower() == "2bytes") { memory = new byte[2]; memory[0] = (byte)(Convert.ToInt32(write) % 256); memory[1] = (byte)(Convert.ToInt32(write) / 256); size = 2; } else if (type.ToLower() == "bytes") { if (write.Contains(",") || write.Contains(" ")) //check if it's a proper array { string[] stringBytes; if (write.Contains(",")) { stringBytes = write.Split(','); } else { stringBytes = write.Split(' '); } //Debug.WriteLine("write:" + write + " stringBytes:" + stringBytes); int c = stringBytes.Count(); memory = new byte[c]; for (int i = 0; i < c; i++) { memory[i] = Convert.ToByte(stringBytes[i], 16); } size = stringBytes.Count(); } else //wasnt array, only 1 byte { memory = new byte[1]; memory[0] = Convert.ToByte(write, 16); size = 1; } } else if (type.ToLower() == "double") { memory = BitConverter.GetBytes(Convert.ToDouble(write)); size = 8; } else if (type.ToLower() == "long") { memory = BitConverter.GetBytes(Convert.ToInt64(write)); size = 8; } else if (type.ToLower() == "string") { if (stringEncoding == null) { memory = System.Text.Encoding.UTF8.GetBytes(write); } else { memory = stringEncoding.GetBytes(write); } size = memory.Length; } //Debug.Write("DEBUG: Writing bytes [TYPE:" + type + " ADDR:" + theCode + "] " + String.Join(",", memory) + Environment.NewLine); MemoryProtection OldMemProt = 0x00; bool WriteProcMem = false; if (RemoveWriteProtection) { ChangeProtection(code, MemoryProtection.ExecuteReadWrite, out OldMemProt, file); // change protection } WriteProcMem = WriteProcessMemory(mProc.Handle, theCode, memory, (UIntPtr)size, IntPtr.Zero); if (RemoveWriteProtection) { ChangeProtection(code, OldMemProt, out _, file); // restore } return(WriteProcMem); }
/// <summary> /// Base64加密 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string Base64Encode(string str) { System.Text.Encoding encode = System.Text.Encoding.ASCII; byte[] bytedata = encode.GetBytes(str); return(Convert.ToBase64String(bytedata, 0, bytedata.Length)); }
public RespBuilder AppendRespBulkString(string value, System.Text.Encoding encoding) { byte[] encodedValue = encoding.GetBytes(value); return(AppendRespBulkString(encodedValue, 0, encodedValue.Length)); }
// Write a raw string to the output void WriteRawString(string data) { byte[] rawData = Encoding.GetBytes(data); ExportLog.Write(rawData, 0, rawData.Length); }
public static string ChangeEncoding(string Text, System.Text.Encoding FromEncoding, System.Text.Encoding ToEncoding) { return(ToEncoding.GetString(FromEncoding.GetBytes(Text))); }
/// <summary> /// URL전송용 텍스트 인코딩 /// </summary> /// <param name="EncType">EUC-KR, UTF-8</param> public static string encURL(string text, string EncType) { System.Text.Encoding enc = System.Text.Encoding.GetEncoding(EncType.ToUpper()); byte[] bytesData = enc.GetBytes(text); return(System.Web.HttpUtility.UrlEncode(bytesData, 0, bytesData.Length)); }
public SocketResult SendData(SocketClientConfig config, string content) { SocketResult result = SocketResult.Empty; try { SocketLogMgt.SetLog(this, "============================================="); SocketLogMgt.SetLog(this, ": Send Data Begin."); SocketLogMgt.SetLog(this, config); //string strSend = SocketHelper.PackMessageBlock(content); string strSend = content; if (SocketLogMgt.DumpData) { SocketLogMgt.SetLog(this, ": Data to be sent."); SocketLogMgt.SetLog(this, "------------------------"); SocketLogMgt.SetLog(this, strSend); SocketLogMgt.SetLog(this, "------------------------"); } Byte[] bytesSent = null; System.Text.Encoding encoder = SocketHelper.GetEncoder(config); if (encoder != null) { bytesSent = encoder.GetBytes(strSend); } if (bytesSent == null) { SocketLogMgt.SetLog(SocketLogType.Error, this, "Encode data failed."); return(SocketResult.SendFailed); } Byte[] bytesReceived = new Byte[config.ReceiveResponseBufferSizeKB * 1024]; SocketLogMgt.SetLog(this, ": Socket prepared."); SocketLogMgt.SetLog(this, "------------------------"); string strReceived = null; StringBuilder sb = new StringBuilder(); IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(config.IPAddress), config.Port); using (Socket socket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { int id = SocketHelper.GetNewSocketID(); string strID = "(" + id.ToString() + ") "; //socket.NoDelay = true; socket.SendTimeout = config.SendTimeout; socket.ReceiveTimeout = config.ReceiveTimeout; SocketLogMgt.SetLog(this, strID + "Socket created."); socket.Connect(ipe); if (socket.Connected) { SocketLogMgt.SetLog(this, strID + "Socket connected."); } else { SocketLogMgt.SetLog(SocketLogType.Warning, this, strID + "Connection failed."); return(SocketResult.Disconnect); } _allDone.Reset(); SocketLogMgt.SetLog(this, strID + "Send data."); socket.BeginSend(bytesSent, 0, bytesSent.Length, 0, new AsyncCallback(OnDataSent), new SocketWrapper(strID, socket)); bool rec = true; while (rec) { if (!socket.Connected) { SocketLogMgt.SetLog(SocketLogType.Warning, this, strID + "Connection closed."); break; } SocketLogMgt.SetLog(this, strID + "Receive data."); int bytes = socket.Receive(bytesReceived, bytesReceived.Length, 0); SocketLogMgt.SetLog(this, strID + "Receive succeeded. " + bytes.ToString() + " bytes."); string str = encoder.GetString(bytesReceived, 0, bytes); sb.Append(str); strReceived = sb.ToString(); //rec = !SocketHelper.FindBlockEnding(strReceived); rec = false; // This socket client assume that there is a completed HL7 message (without MLLP signs) in one Receive(); } _allDone.WaitOne(); // need not to set timeout here, we can depend on socket timeout of the Receive() method. socket.Shutdown(SocketShutdown.Both); socket.Close(); SocketLogMgt.SetLog(this, strID + "Socket disconnected."); } SocketLogMgt.SetLog(this, "------------------------"); if (SocketLogMgt.DumpData) { SocketLogMgt.SetLog(this, ": Data received."); SocketLogMgt.SetLog(this, "------------------------"); SocketLogMgt.SetLog(this, strReceived); SocketLogMgt.SetLog(this, "------------------------"); } //strReceived = SocketHelper.UnpackMessageBlock(strReceived); strReceived = SocketHelper.TrimMessageBlock(strReceived); result = new SocketResult(SocketResultType.Success, strReceived); } catch (Exception err) { SocketLogMgt.SetLastError(this, err); result = new SocketResult(err); } SocketLogMgt.SetLog(this, ": Send Data End"); SocketLogMgt.SetLog(this, "=============================================\r\n"); return(result); }
public virtual byte[] GetBytes(char[] chars, int index, int count) { CheckParams(chars, index, count); return(encoding.GetBytes(chars, index, count)); }
/// <summary> /// 装配器件信息 /// </summary> /// <param name="deviceInfo"></param> /// <returns></returns> //public List<byte[]> AssemblePackageBB(List<Model.DeviceInfo8036 > deviceInfo)//各控制器不同 commented at 2017-04-05 public byte[] AssemblePackageBB(Model.DeviceInfo8021 deviceInfo)//各控制器不同 { //List<byte[]> lstSendData = new List<byte[]>(); //foreach (Model.DeviceInfo8036 singleDevInfo in deviceInfo) //{ Model.DeviceInfo8021 singleDevInfo = deviceInfo; byte[] sendData = new byte[47]; sendData[0] = 0xAA; sendData[1] = 0x55; sendData[2] = 0xDA; sendData[3] = 0x00; //异或值校验 sendData[4] = 0x00; //累加和校验 //?? sendData[5] = 0x29; //数据长度 ?? 固定29? sendData[6] = 0xBB; //发送器件命令 //sendData[7] = Convert.ToByte(deviceInfo.Count); //器件总数 //sendData[7] = Convert.ToByte(0x2E); //器件总数 sendData[7] = Convert.ToByte(base.DownloadedDeviceInfoTotalAmountInCurrentLoop); //器件总数 sendData[8] = Convert.ToByte(singleDevInfo.Loop.Controller.MachineNumber); //控制器号 sendData[9] = Convert.ToByte(singleDevInfo.Loop.SimpleCode); //回路号 //回路的Code已经包含了机器号 2017-04-05 sendData[10] = Convert.ToByte(singleDevInfo.Code.Substring(singleDevInfo.Loop.Code.Length, 3)); //地编号 sendData[11] = Convert.ToByte(GetDevType(singleDevInfo.TypeCode) * 8 + (singleDevInfo.Disable == true?1:0) * 4); //器件状态(屏蔽);NT8001还有特性;根据这些值转换为“器件内部编码” if (singleDevInfo.TypeCode <= 17) { sendData[12] = Convert.ToByte(singleDevInfo.TypeCode); // 内部设备类型 } switch (singleDevInfo.TypeCode) { case 18: sendData[12] = Convert.ToByte(37); //设备类型 break; case 19: sendData[12] = Convert.ToByte(33); //设备类型 break; case 20: sendData[12] = Convert.ToByte(34); //设备类型 break; case 21: sendData[12] = Convert.ToByte(35); //设备类型 break; case 22: sendData[12] = Convert.ToByte(36); //设备类型 break; } sendData[13] = Convert.ToByte(singleDevInfo.TypeCode); // 外部设备类型 //电流报警值 float?tempValue = singleDevInfo.CurrentThreshold == null ? 0 : singleDevInfo.CurrentThreshold; sendData[14] = Convert.ToByte(tempValue / 256); sendData[15] = Convert.ToByte(tempValue % 256); //温度报警值 tempValue = singleDevInfo.TemperatureThreshold == null ? 0 : singleDevInfo.TemperatureThreshold; sendData[16] = Convert.ToByte(tempValue); //17~33为安装地点 //将地点信息逐字符取出,将每个字符转换为ANSI代码后,存入sendData数据中; int startIndex = 17; if (singleDevInfo.Location != null) { char[] charArrayLocation = singleDevInfo.Location.ToArray(); //采用Base64编码传递数据 System.Text.Encoding ascii = System.Text.Encoding.GetEncoding(54936); for (int j = 0; j < charArrayLocation.Length; j++) { Byte[] encodedBytes = ascii.GetBytes(charArrayLocation[j].ToString()); if (encodedBytes.Length == 1) { sendData[startIndex] = encodedBytes[0]; startIndex++; } else { sendData[startIndex] = encodedBytes[0]; startIndex++; sendData[startIndex] = encodedBytes[1]; startIndex++; } } } //补足位数 for (int j = startIndex; j < 42; j++) { sendData[j] = 0x00; } sendData[42] = 0x00;//固定值 //楼号 sendData[43] = Convert.ToByte(singleDevInfo.BuildingNo); //区号 sendData[44] = Convert.ToByte(singleDevInfo.ZoneNo); //层号 if (singleDevInfo.FloorNo < 0 && singleDevInfo.FloorNo > -10) { sendData[45] = Convert.ToByte(singleDevInfo.FloorNo + 256); } else { sendData[45] = Convert.ToByte(singleDevInfo.FloorNo); } //房间号 sendData[46] = Convert.ToByte(singleDevInfo.RoomNo); byte[] checkValue = base.m_ProtocolDriver.CheckValue(sendData, 6, 47); sendData[3] = checkValue[0]; sendData[4] = checkValue[1]; return(sendData); }
/// <summary> /// 从指定编码的String生成MD5, 返回原始的MD5字节数组 /// </summary> /// <param name="data"></param> /// <param name="encoding"></param> /// <returns></returns> public static byte[] ToBytes(string data, System.Text.Encoding encoding) { return(provider.ComputeHash( encoding.GetBytes( data))); }
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 static String Decode(String Text) { System.Text.Encoding UTF7 = System.Text.Encoding.UTF7; return(Convert.ToBase64String(UTF7.GetBytes(Text))); }
public static byte[] GetByteArrayFromString(string str) { System.Text.Encoding encoding = System.Text.Encoding.UTF8; return(encoding.GetBytes(str)); }
/// <summary> /// 把字符转换为指定编码的序列 /// </summary> /// <param name="value">字符值</param> /// <param name="encode">编码</param> /// <returns>序列</returns> public static byte[] ToBytes(this string value, System.Text.Encoding encode) { return(encode.GetBytes(value)); }
public static byte[] GetBytes(string stingMessage, System.Text.Encoding e) { return(e.GetBytes(stingMessage)); }
//执行http调用 public bool call() { StreamReader sr = null; HttpWebResponse wr = null; HttpWebRequest hp = null; try { string postData = null; if (this.method.ToUpper() == "POST") { string[] sArray = System.Text.RegularExpressions.Regex.Split(this.reqContent, "\\?"); hp = (HttpWebRequest)WebRequest.Create(sArray[0]); if (sArray.Length >= 2) { postData = sArray[1]; } } else { hp = (HttpWebRequest)WebRequest.Create(this.reqContent); } ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult); if (this.certFile != "") { hp.ClientCertificates.Add(new X509Certificate2(this.certFile, this.certPasswd)); } hp.Timeout = this.timeOut * 1000; System.Text.Encoding encoding = System.Text.Encoding.GetEncoding(this.charset); if (postData != null) { byte[] data = encoding.GetBytes(postData); hp.Method = "POST"; hp.ContentType = "application/x-www-form-urlencoded"; hp.ContentLength = data.Length; Stream ws = hp.GetRequestStream(); // 发送数据 ws.Write(data, 0, data.Length); ws.Close(); } wr = (HttpWebResponse)hp.GetResponse(); sr = new StreamReader(wr.GetResponseStream(), encoding); this.resContent = sr.ReadToEnd(); sr.Close(); wr.Close(); } catch (Exception exp) { this.errInfo += exp.Message; if (wr != null) { this.responseCode = Convert.ToInt32(wr.StatusCode); } return(false); } this.responseCode = Convert.ToInt32(wr.StatusCode); return(true); }
public static string Base64Encoding(string EncodingText) { System.Text.Encoding oEncoding = System.Text.Encoding.UTF8; byte[] arr = oEncoding.GetBytes(EncodingText); return(System.Convert.ToBase64String(arr)); }
//등록 자료 생성 public static string ConvertRegister(string path, string xmlZipcodeAreaPath, string xmlZipcodePath) { System.Text.Encoding _encoding = System.Text.Encoding.GetEncoding(strEncoding); //기본 인코딩 //FileInfo _fi = null; StreamReader _sr = null; //파일 읽기 스트림 StreamWriter _swError = null; StreamWriter _sw = null; byte[] _byteAry = null; string _strBankID = "", _strZipcode = "", _strAreaGroup = ""; //2013.06.26 태희철 _strValue : 영업점코드 : 2 = 영업점, 3 = 제3영업점, 4 = 강제영업점 string _strReturn = "", _strLine = "", _strValue = null; DataTable _dtable = null; DataSet _dsetZipcodeArea = null; //DataRow _dr = null; DataRow[] _drs = null; int _iCount = 0; string _strDong = null, _strVIP = null, _strSC = null, _strYe = null, strBank_code = "", _strChk_add = "", strWoori_Mem = ""; try { _dtable = new DataTable("CONVERT"); _dtable.Columns.Add("card_bank_ID"); _dtable.Columns.Add("card_zipcode"); _dtable.Columns.Add("data"); _dsetZipcodeArea = new DataSet(); _dsetZipcodeArea.ReadXml(xmlZipcodeAreaPath); //파일 읽기 Stream과 오류시 저장할 쓰기 Stream 생성 _sr = new StreamReader(path, _encoding); _swError = new StreamWriter(path + ".Error", false, _encoding); while ((_strLine = _sr.ReadLine()) != null) { _byteAry = _encoding.GetBytes(_strLine); _strBankID = _encoding.GetString(_byteAry, 8, 2); _strZipcode = _encoding.GetString(_byteAry, 139, 6); //2011-10-14 태희철 수정 //_strValue = _encoding.GetString(_byteAry, 540, 2); //영업점코드 : 2 = 영업점, 3 = 제3영업점, 4 = 강제영업점 _strValue = _encoding.GetString(_byteAry, 145, 1); _strDong = _encoding.GetString(_byteAry, 247, 1); //2012-05-15 태희철 추가 _strVIP = _encoding.GetString(_byteAry, 296, 1); //2012-05-15 태희철 추가 _strSC = _encoding.GetString(_byteAry, 297, 2); //2012-06-04 태희철 추가 Ye치과 구분 _strYe = _encoding.GetString(_byteAry, 245, 1); //은행구분코드 strBank_code = _encoding.GetString(_byteAry, 250, 3); //우리은행(롯데멤버십) : 837011 / 837711 strWoori_Mem = _encoding.GetString(_byteAry, 542, 6); //우리은행 통신사별지 _strChk_add = _encoding.GetString(_byteAry, 2765, 1); _drs = _dsetZipcodeArea.Tables[0].Select("zipcode=" + _strZipcode); _iCount++; // [1] 동의서 1~8은 동의서 | 299,1 의 1 or 2 는 긴급은 따로 분류 //if (_byteAry.Length != 1739) //if (_byteAry.Length != 1765) // if (_byteAry.Length != 2766) { _sw = new StreamWriter(path + "총byte오류_재발송", true, _encoding); _sw.WriteLine(_strLine); } else { switch (_strDong) { case "1": case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9": if (strBank_code == "020") { if (_strDong == "1") { _sw = new StreamWriter(path + "bcd35000_우리재발송(롯데멤버스)", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012404"); } else if (_strDong == "4") { _sw = new StreamWriter(path + "우리재발송(국기원)_동의_19000", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012402"); } else { if (_strChk_add == "1" || _strChk_add == "2" || _strChk_add == "3") { _sw = new StreamWriter(path + "우리재발송(통신)_20000", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012403"); } else { _sw = new StreamWriter(path + "우리재발송_동의_18000", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012401"); } } } else if (strBank_code == "031") { _sw = new StreamWriter(path + "대구재발송_동의_6500", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012201"); } else if (strBank_code == "039") { _sw = new StreamWriter(path + "경남재발송_동의_17000", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012301"); } else if (strBank_code == "050") { _sw = new StreamWriter(path + "바로재발송_동의_33000", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012501"); } else { _sw = new StreamWriter(path + "기타", true, _encoding); _sw.WriteLine(_strLine + "0A"); } break; default: if (strBank_code == "020") { if (_strYe == "1" || _strYe == "3") { _sw = new StreamWriter(path + "우리재발송_일반본인_12000", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0011111"); } else { _sw = new StreamWriter(path + "우리재발송_일반_8000", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0011108"); } } else if (strBank_code == "031") { if (_strYe == "1" || _strYe == "3") { _sw = new StreamWriter(path + "대구재발송_일반본인_34000", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0011402"); } else { _sw = new StreamWriter(path + "대구재발송_일반_6000", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0011401"); } } else if (strBank_code == "039") { if (_strYe == "1" || _strYe == "3") { _sw = new StreamWriter(path + "경남재발송_일반본인_11000", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0011110"); } else { _sw = new StreamWriter(path + "경남재발송_일반_7000", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0011107"); } } else if (strBank_code == "050") { _sw = new StreamWriter(path + "바로재발송_일반_32000", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0011114"); } else if (strBank_code == "042") { if (_strYe == "1" || _strYe == "3") { _sw = new StreamWriter(path + "토스재발송_본인_37000", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0011116"); } else { _sw = new StreamWriter(path + "토스재발송_일반_36000", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0011115"); } } else if (strBank_code == "079") { if (_strYe == "1" || _strYe == "3") { _sw = new StreamWriter(path + "차이재발송_본인_39000", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0011118"); } else { _sw = new StreamWriter(path + "차이재발송_일반_38000", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0011117"); } } else { _sw = new StreamWriter(path + "기타", true, _encoding); _sw.WriteLine(_strLine + "0A"); } break; } } _sw.Close(); } _drs = _dtable.Select("", ""); for (int i = 0; i < _drs.Length; i++) { _sw.WriteLine(_strLine); } _strReturn = "성공"; } catch (Exception ex) { _strReturn = string.Format("{0}번째 우편번호 오류", _iCount + 1); if (_swError != null) { _swError.WriteLine(ex.Message); } } finally { if (_sr != null) { _sr.Close(); } if (_sw != null) { _sw.Close(); } if (_swError != null) { _swError.Close(); } } return(_strReturn); }
public static void Main(string[] args) { //公钥 string PUBLICKKEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCQyamojHDMZHwghP/UV1Qu8MfHYPfMoBe+9kJOUMhh/oWUewEtLnv/hVIia2alTZWaUOu4fSQ0rQ9l35d7qw8pNEH9fLFocENt1OD8TxvwtG3URnWpWMBNB8XAx16+rBAbj+BsA6lQnGtEj0BD+jqLA9RJoJqt/BmK5lToXjXjiQIDAQAB"; //私钥 string PRIVATEKEY = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJDJqaiMcMxkfCCE/9RXVC7wx8dg98ygF772Qk5QyGH+hZR7AS0ue/+FUiJrZqVNlZpQ67h9JDStD2Xfl3urDyk0Qf18sWhwQ23U4PxPG/C0bdRGdalYwE0HxcDHXr6sEBuP4GwDqVCca0SPQEP6OosD1Emgmq38GYrmVOheNeOJAgMBAAECgYBc4jJH4Yi/ZrtGtWvVkgx8bJUNMAToLc/t/tc8nJBgZULWpS51CLwdiS7Oy+22oBYYQE9oNEfUzyzwosbwXCXFxysbBtnXlqLuMnbSjW7DFn8fpIkgu9OYI9ecEOABZ8PkrWohAVswjaim3rwa7cDNaT8YDFzb3KLcfM24x885gQJBAMKceEX6u2WTX2BSITeAW3QCcS2BzRgoHNvDLp4rV0UCHDJkygSJXk/fh+kmT+LDkiJ7kh7soIFpp2uiIjHFe7ECQQC+dcZ51u09xXRJEGx0FeuMrUgNXEqODopUQofIRo1YM6fCwzTcQ5kgX/2DPGOLr+vw2iezJDVaZhVAutBrC9NZAkEAsWo384QLByT9FDCLe6+WsAHx78yfjuAyvt4HR8a3PoAX+JEN4mjhA+wCWTjGJzKnrKv+oBaUlKYfLO6YQcuJYQJAEgtUd3yeU2jeoIF21PSysUxFdEaXJahJALyg4p+UipOyRCh8XJXm7wNJIGLbR4OuRc5VToqSp3Ledph8YHfpWQJAcfoU/lzoRG9XdX5v49dFULuFU5Wozq70bJDCxtXB6MKsL89vfJ17bx4Vq8eyDzQygh2qKkDF4aWzKGtvSIVp2g=="; //发送参数 string oldData = "{agentnum:\"101\",inPhone:\"\",payCode:\"100701\",outPhone:\"\",channelNum:\"100001\",outCard:\"\",settlementName:\"\",realFee:\"100\",inCard:\"\",amount:\"5000\",crpIdNo:\"\",inBankName:\"中国招商银行\",outCardExpire:\"\",outCardCvv2:\"\",appOrderId:\"10120180615140044\"}"; System.Text.Encoding encode = System.Text.Encoding.UTF8; byte[] bytedata = encode.GetBytes(oldData); //base64编码 string oldData_base64 = Convert.ToBase64String(bytedata, 0, bytedata.Length); Console.WriteLine("|" + oldData_base64 + "|"); /* * //base64解码 * byte[] bpath = Convert.FromBase64String(oldData_base64); * string oldData_decode = System.Text.UTF8Encoding.Default.GetString(bpath); * Console.WriteLine("|"+oldData_decode+"|"); */ //---------------------------- //私钥加密 var sign_base64 = RSASignJavaBouncyCastle(oldData_base64, PRIVATEKEY, "MD5withRSA", "UTF-8"); Console.WriteLine("|" + sign_base64 + "|"); //---------------------------- byte[] byteReqData = encode.GetBytes(oldData_base64); //公钥加密 string reqData_base64 = EncryptWithPublicKey(PUBLICKKEY, byteReqData, "RSA/ECB/PKCS1Padding"); Console.WriteLine("|" + reqData_base64 + "|"); //----------------------------发送前要将数据里点替换为空将+替换为%2b string postData = "reqParam={\"serviceCode\":\"A0350\",\"request\":{\"sign\":\"4SSSUjZ/dq/1dC1D2H8X5xPu0m0IGdnxOWZolQg3OchvN6qD7agaYGtmFfEGZQkhaQucRJ8AvhJvRtnftJKo7i+PxlZfCBmRWDwAd/zvDrj51oTaST2BXt5javscVuerWzPLucbAQ/+epBpAHgLIH974n8p/Et2KeHUz82Q3HKg=\",\"data\":\"WbaBAtwvriZVq+grdmR1CrfB8Rmefmp1Z3cdKXaPEPMaQA7C+tsBDmIrs3Cim3K8onXXi5YE/qN7KHkBGi47kJe3absKremFlYAQJ1o13ePnM6f20qrs/RN3vORF0neIRaZ63oFKUUJ8JrIUID0/J1ncGHyv7uoL141Sjb6kyg+54ESe39PL+lmqsUU9q83tejDiQg+2H52/ZGw6iTKrUgJcQJucCXgu6RUdsOdAFfz90tmQkaWLC4YzMgY8+WosP3jUh8y/jhKm1oeZFcgnV++2wcsaqW7NF9mJufPfze0Gk0ShhmicUAcg++dSbozsfFWL0XaKkGrZ+n/rbmdv82vWD1nN5bJRqhxlSow8lADRndWQIDrvPK/klvEzpa43YypYvPg3kytV0i49FRuePOyihkH833GI+ZzVUTSfpI5wISq6gLaUArxVAEkfA7ItRAkgqygYmuiXOjZff5n6Lx92dRv5GzoSC/HzV9SLJ4ptjAfUvuRy8rJ58TTT51bw\",\"account\":\"15546873642\"}}"; postData = postData.Replace(".", ""); postData = postData.Replace("+", "%2b"); //----------------------------验证签名 //{sign=El8yLAqi8r7iNoD65OHGuMGp9fezdRzU9miKiCF/gPWPleNwBSd+2EVFxsxOPaQ5QjyuvylMTlCkj+ZHO2LBLUBeYx4iOaK3KVDGKWkGjM5plvhCCrs83dWN1nm4Fmb7MNZy1/m6eFn9hSo/g8i8VzeBQdDBcUPzHLu72FwmsWI=, respCode=0000, url=https://cashier.sandpay.com.cn/fastPay/quickPay/index?charset=UTF-8&signType=0&data={"body":{"body":"电器","frontUrl":"http://www.baidu.com","currencyCode":"156","orderCode":"180621092454978","extend":"","subject":"电器批发","userId":"2If65nxeY5","totalAmount":"000000005000","orderTime":"20180621092454","notifyUrl":"http://47.106.111.38:8001/QRCodeSys/ShandeQuickBackUrl.action","clearCycle":"0"},"head":{"channelType":"07","reqTime":"20180621092454","plMid":"","method":"sandPay.fastPay.quickPay.index","mid":"11957405","accessType":"1","productId":"00000016","version":"1.0"}}&sign=dwy8qserk6TTJNioqf9tDbACVeKbFxmI%2FT%2FdijXmirkRnmA77JYKlNY0euESBLUPvaQttLKhGPiAweCnPHgF4N5TSq5XFgmn7lp2NVwlJQ43j%2BU%2BOIlqwix%2BNQ6ZRYKpgNOMRUMGjqKGsVS7IEDdTJWJDNk6oAv3uNhkZH6rmmapilMvudglltTpOCCjGWe1jYI6Jqqhk3FOF0fOBLYCN5vedJ5rEwyfAfaAXTeJGEt1FIVACqtBw6S77RkXL2mmOAz9J6JGUDeU59yPj1RdwX0CHML4HjQtLOCr83O14%2FSLaox%2BpOsn5yS3OnxLVrlVj%2BQc%2FRNJVrYttlJBFysHzw%3D%3D&extend=, respInfo=一键快捷链接获取成功} string respSign = "El8yLAqi8r7iNoD65OHGuMGp9fezdRzU9miKiCF/gPWPleNwBSd+2EVFxsxOPaQ5QjyuvylMTlCkj+ZHO2LBLUBeYx4iOaK3KVDGKWkGjM5plvhCCrs83dWN1nm4Fmb7MNZy1/m6eFn9hSo/g8i8VzeBQdDBcUPzHLu72FwmsWI="; Console.WriteLine("|" + respSign + "|"); string respMap = "{respCode=0000, url=https://cashier.sandpay.com.cn/fastPay/quickPay/index?charset=UTF-8&signType=0&data={\"body\":{\"body\":\"电器\",\"frontUrl\":\"http://www.baidu.com\",\"currencyCode\":\"156\",\"orderCode\":\"180621092454978\",\"extend\":\"\",\"subject\":\"电器批发\",\"userId\":\"2If65nxeY5\",\"totalAmount\":\"000000005000\",\"orderTime\":\"20180621092454\",\"notifyUrl\":\"http://47.106.111.38:8001/QRCodeSys/ShandeQuickBackUrl.action\",\"clearCycle\":\"0\"},\"head\":{\"channelType\":\"07\",\"reqTime\":\"20180621092454\",\"plMid\":\"\",\"method\":\"sandPay.fastPay.quickPay.index\",\"mid\":\"11957405\",\"accessType\":\"1\",\"productId\":\"00000016\",\"version\":\"1.0\"}}&sign=dwy8qserk6TTJNioqf9tDbACVeKbFxmI%2FT%2FdijXmirkRnmA77JYKlNY0euESBLUPvaQttLKhGPiAweCnPHgF4N5TSq5XFgmn7lp2NVwlJQ43j%2BU%2BOIlqwix%2BNQ6ZRYKpgNOMRUMGjqKGsVS7IEDdTJWJDNk6oAv3uNhkZH6rmmapilMvudglltTpOCCjGWe1jYI6Jqqhk3FOF0fOBLYCN5vedJ5rEwyfAfaAXTeJGEt1FIVACqtBw6S77RkXL2mmOAz9J6JGUDeU59yPj1RdwX0CHML4HjQtLOCr83O14%2FSLaox%2BpOsn5yS3OnxLVrlVj%2BQc%2FRNJVrYttlJBFysHzw%3D%3D&extend=, respInfo=一键快捷链接获取成功}"; byte[] bytedataresp = encode.GetBytes(respMap); string respMap_base64 = Convert.ToBase64String(bytedataresp, 0, bytedataresp.Length); bool flag = RSASignVerifyJavaBouncyCastle(PUBLICKKEY, respSign, respMap_base64); Console.WriteLine("|" + flag + "|"); /* * 未测试第一种方式 * var request = (HttpWebRequest)WebRequest.Create("http://www.leadnt.com/recepticle.aspx"); * * var postData = "thing1=hello"; * postData += "&thing2=world"; * var data = Encoding.ASCII.GetBytes(postData); * * request.Method = "POST"; * request.ContentType = "application/x-www-form-urlencoded"; * request.ContentLength = data.Length; * * using (var stream = request.GetRequestStream()) * { * stream.Write(data, 0, data.Length); * } * * var response = (HttpWebResponse)request.GetResponse(); * * var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); * * 未测试第二种方式 * using (var client = new HttpClient()) * { * var values = new List<KeyValuePair<string, string>>(); * values.Add(new KeyValuePair<string, string>("thing1", "hello")); * values.Add(new KeyValuePair<string, string>("thing2 ", "world")); * * var content = new FormUrlEncodedContent(values); * * var response = await client.PostAsync("http://www.mydomain.com/recepticle.aspx", content); * * var responseString = await response.Content.ReadAsStringAsync(); * } * * */ Console.Write("Press any key to continue . . . "); Console.ReadKey(true); }
public RedisWriter(int size, Encoding encoding) { _chunks = new byte[size][]; _encoding = encoding; _bulkBytes = _encoding.GetBytes(new[] { Bulk }); _multiBulkBytes = _encoding.GetBytes(new[] { MultiBulk }); _eolBytes = _encoding.GetBytes(RedisConnection.EOL); }