GetBytes() private method

private GetBytes ( char chars, int charCount, byte bytes, int byteCount ) : int
chars char
charCount int
bytes byte
byteCount int
return int
Example #1
0
 public bool DecryptFileString(string aPublicKey, string aIV, string aFileName)
 {
     ASCIIEncoding encoding = new ASCIIEncoding();
     byte[] bytes = encoding.GetBytes(aPublicKey);
     byte[] buffer2 = encoding.GetBytes(aIV);
     return this.DecryptFile(bytes, buffer2, aFileName);
 }
        public void TestMethodSendPrivateMessage()
        {
            ASCIIEncoding encoding = new ASCIIEncoding();

            DSACryptoServiceProvider mycryptoC = new DSACryptoServiceProvider();
            DSAParameters publickeyC = mycryptoC.ExportParameters(false);

            DSACryptoServiceProvider mycryptoW = new DSACryptoServiceProvider();
            DSAParameters publickeyW = mycryptoW.ExportParameters(false);

            byte[] hashC = mycryptoC.SignData(encoding.GetBytes("Cuddy"));
            byte[] hashW = mycryptoW.SignData(encoding.GetBytes("Wilson"));

            ServiceReference1.ServeurChatSoapClient a = new ServiceReference1.ServeurChatSoapClient();

            a.Register("Cuddy", "iluvhouse", hashC, publickeyC.Counter, publickeyC.G, publickeyC.J, publickeyC.P, publickeyC.Q, publickeyC.Seed, publickeyC.X, publickeyC.Y);
            a.Register("Wilson", "ihatehouse", hashW, publickeyW.Counter, publickeyW.G, publickeyW.J, publickeyW.P, publickeyW.Q, publickeyW.Seed, publickeyW.X, publickeyW.Y);

            string message = "je suis jalouse de Cameron";
            byte[] messagesigned = mycryptoC.SignData(encoding.GetBytes(message));

            Assert.AreEqual(true,a.SendPrivateMessage("Cuddy", "Wilson", message, messagesigned));
            Assert.AreEqual(false, a.SendPrivateMessage("Cuddy", "Foreman", message, messagesigned));

            File.Delete("C:\\Program Files\\Common Files\\microsoft shared\\DevServer\\10.0\\Message_serialization.xml");
            File.Delete("C:\\Program Files\\Common Files\\microsoft shared\\DevServer\\10.0\\User_serialization.xml");
        }
        //1 先sha1加密成36位,
        //2 移除前后2位,使之变成一个32位数(看起来像一个MD5的加密值)
        //3 再将结果MD5一次
        public static string EncryptPwd(string pwd)
        {
            if (string.IsNullOrWhiteSpace(pwd))
                throw new ArgumentNullException(pwd, "密码不能为空");

            //建立SHA1对象
            SHA1 sha = new SHA1CryptoServiceProvider();
            //将mystr转换成byte[]
            ASCIIEncoding enc = new ASCIIEncoding();
            byte[] dataToHash = enc.GetBytes(pwd);
            //Hash运算
            byte[] dataHashed = sha.ComputeHash(dataToHash);
            string hash = BitConverter.ToString(dataHashed).Replace("-", "");

            //移除前后2位
            hash = hash.Substring(2).Substring(0, hash.Length - 2);

            //md5加密
            dataToHash = enc.GetBytes(hash);

            MD5 md5 = new MD5CryptoServiceProvider();
            dataHashed = md5.ComputeHash(dataToHash);
            hash = BitConverter.ToString(dataHashed).Replace("-", "");
            return hash;
        }
Example #4
0
        static void Main(string[] args)
        {
            int _arg1 = 9;
            char[] _arg2 = new char[8]{'a','s','d','f','a','s','d','\0'};
            int _arg3 = 1;
            int _arg4 = 2;
            char[] _arg5 = new char[32]{
                '0','0','0','0','0','0','0','0',
                '0','0','0','0','0','0','0','0',
                '0','0','0','0','0','0','0','0',
                '0','0','0','0','0','0','0','0'
            };
            char[] _arg6 = new char[32]{
                '0','0','0','0','0','0','0','0',
                '0','0','0','0','0','0','0','0',
                '0','0','0','0','0','0','0','0',
                '0','0','0','0','0','0','0','0'
            };
            char[] _arg7 = new char[9]{
                't','u','r','n','r','i','g','h','t'
            };

            byte[] arg1 = new byte[4];
            byte[] arg2 = new byte[8];
            byte[] arg3 = new byte[4];
            byte[] arg4 = new byte[4];
            byte[] arg5 = new byte[32];
            byte[] arg6 = new byte[32];
            byte[] arg7 = new byte[9];

            // encode
            ASCIIEncoding encoding = new ASCIIEncoding();

            arg1 = BitConverter.GetBytes(_arg1);
            arg2 = encoding.GetBytes(_arg2);
            arg3 = BitConverter.GetBytes(_arg3);
            arg4 = BitConverter.GetBytes(_arg4);
            arg5 = encoding.GetBytes(_arg5);
            arg6 = encoding.GetBytes(_arg6);
            arg7 = encoding.GetBytes(_arg7);

            int offset = 0;
            Buffer.BlockCopy(arg1, 0, rawdata, offset, arg1.Length); offset += arg1.Length;
            Buffer.BlockCopy(arg2, 0, rawdata, offset, arg2.Length); offset += arg2.Length;
            Buffer.BlockCopy(arg3, 0, rawdata, offset, arg3.Length); offset += arg3.Length;
            Buffer.BlockCopy(arg4, 0, rawdata, offset, arg4.Length); offset += arg4.Length;
            Buffer.BlockCopy(arg5, 0, rawdata, offset, arg5.Length); offset += arg5.Length;
            Buffer.BlockCopy(arg6, 0, rawdata, offset, arg6.Length); offset += arg6.Length;
            Buffer.BlockCopy(arg7, 0, rawdata, offset, arg7.Length); offset += arg7.Length;
            // 이 시점에서 rawdata를 전송받았다고 생각합시다.

            // decode
            offset = 0;
            int streamSize = BitConverter.ToInt32(rawdata, offset);
            Console.WriteLine(streamSize); offset += 4;
            Console.WriteLine(Encoding.Default.GetString(rawdata, offset, 8)); offset += 8;
            Console.WriteLine(BitConverter.ToInt32(rawdata, offset)); offset += 4;
            Console.WriteLine(BitConverter.ToInt32(rawdata, offset)); offset += 4 + 64;
            Console.WriteLine(Encoding.Default.GetString(rawdata, offset, streamSize));
        }
Example #5
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="pData"></param>
        /// <returns></returns>
        public bool sendContribution(String pData)
        {
            bool lRetVal = false;
              HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create("http://buglist.io/c/contribute.php");
              ASCIIEncoding encoding = new ASCIIEncoding();
              String lUserAgent = String.Format("Mozilla/4.0 (compatible; MSIE 10.0; Windows NT 6.4; .NET CLR 4.1234)");

              try
              {
            byte[] data = encoding.GetBytes(pData);
            String lEncodedData = String.Format("data={0}", System.Web.HttpUtility.UrlEncode(data));

            httpWReq.Method = "POST";
            httpWReq.ContentType = "application/x-www-form-urlencoded";
            httpWReq.ContentLength = lEncodedData.Length;
            httpWReq.UserAgent = lUserAgent;

            using (Stream stream = httpWReq.GetRequestStream())
            {
              stream.Write(encoding.GetBytes(lEncodedData), 0, lEncodedData.Length);
            }

            HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
            String responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
            LogConsole.Main.LogConsole.pushMsg(String.Format("Contribution sent ({0}) : {1}", getMethod(), String.Format("{0} ...", lEncodedData.Substring(0, 30))));

            lRetVal = true;
              }
              catch (Exception lEx)
              {
            LogConsole.Main.LogConsole.pushMsg("Error sending contribution message : " + lEx.Message);
              }

              return (lRetVal);
        }
        public void TestMethodReceivePrivateMessage()
        {
            ASCIIEncoding encoding = new ASCIIEncoding();

            DSACryptoServiceProvider mycryptoC = new DSACryptoServiceProvider();
            DSAParameters publickeyC = mycryptoC.ExportParameters(false);

            DSACryptoServiceProvider mycryptoW = new DSACryptoServiceProvider();
            DSAParameters publickeyW = mycryptoW.ExportParameters(false);

            byte[] hashC = mycryptoC.SignData(encoding.GetBytes("Cuddy"));
            byte[] hashW = mycryptoW.SignData(encoding.GetBytes("Wilson"));

            ServiceReference1.ServeurChatSoapClient a = new ServiceReference1.ServeurChatSoapClient();

            a.Register("Cuddy", "iluvhouse", hashC, publickeyC.Counter, publickeyC.G, publickeyC.J, publickeyC.P, publickeyC.Q, publickeyC.Seed, publickeyC.X, publickeyC.Y);
            a.Register("Wilson", "ihatehouse", hashW, publickeyW.Counter, publickeyW.G, publickeyW.J, publickeyW.P, publickeyW.Q, publickeyW.Seed, publickeyW.X, publickeyW.Y);

            string message = "je suis jalouse de Cameron";
            byte[] messagesigned = mycryptoC.SignData(encoding.GetBytes(message));

            a.SendPrivateMessage("Cuddy", "Wilson", message, messagesigned);
            UnitTest.ServiceReference1.Message[] b = a.ReceivePrivateMessage("Wilson", hashW);

            Assert.AreEqual("Cuddy", b[0].Auteur); //j'avoue les test sont moisi... mais je voulais juste verifier si le retour par une classe implemente dans le webservice etait possible
            Assert.AreEqual("je suis jalouse de Cameron", b[0].Text);

            File.Delete("C:\\Program Files\\Common Files\\microsoft shared\\DevServer\\10.0\\Message_serialization.xml");
            File.Delete("C:\\Program Files\\Common Files\\microsoft shared\\DevServer\\10.0\\User_serialization.xml");
        }
Example #7
0
        public static string Encode(string key, string value)
        {
            var encoding = new ASCIIEncoding();
            var hmacsha1 = new HMACSHA1(encoding.GetBytes(key));
            var hashValue = hmacsha1.ComputeHash(encoding.GetBytes(value));

            return CryptographyHelper.ByteToString(hashValue);
        }
Example #8
0
 public void Print(string driverName, string name, string userID, string userPicture, bool admin, out string msg)
 {
     int error;
     ZBRGraphics graphics = null;
     ASCIIEncoding ascii;
     msg = "";
     try {
         int fontStyle = BOLD;
         graphics = new ZBRGraphics();
         ascii = new ASCIIEncoding();
         //Initialize Graphics
         if (graphics.InitGraphics(ascii.GetBytes(driverName), out error) == 0) {
             msg = "InitGraphics method error code: " + error.ToString();
             return;
         }
         //DrawImage(location of image, X coordinate, Y coordinate, length, width, out error)
         if (admin == false){ //Does the user have admin? No
             if (graphics.DrawImage(ascii.GetBytes(Application.StartupPath + "\\Student.png"), 350, 30, 400, 50, out error) == 0) {
                 msg = "DrawImage method error code: " + error.ToString();
                 return;
             }
         } else { //They do have admin
             if (graphics.DrawImage(ascii.GetBytes(Application.StartupPath + "\\Admin.png"), 350, 30, 400, 50, out error) == 0) {
                 msg = "DrawImage method error code: " + error.ToString();
                 return;
             }
         }
         //DrawImage(location of image, X coordinate, Y coordinate, length, width, out error)
         if (graphics.DrawImage(ascii.GetBytes(userPicture), 30, 30, 200, 150, out error) == 0) {
             msg = "DrawImage method error code: " + error.ToString();
             return;
         }
         //DrawText(X Coordinate, Y Coordinate, String, Font type, font size, fontStyle, color, out error)
         if (graphics.DrawText(35, 575, ascii.GetBytes(name), ascii.GetBytes("Arial"), 12, fontStyle, 0xFF0000, out error) == 0){
             msg = "DrawText method error code: " + error.ToString();
             return;
         }
         //DrawBarcode(X Coordinate, Y Coordinate, rotation, barcode type, width ratio, multiplier, height, text under, barcode data, out error)
         if (graphics.DrawBarcode(35, 500, 0, 0, 3, 6, 90, 0, ascii.GetBytes(userID), out error) == 0){
             msg = "DrawBarcode method error code: " + error.ToString();
             return;
         }
         if (graphics.PrintGraphics(out error) == 0) {
             msg = "PrintGraphics Error: " + error.ToString();
             return;
         }
     } catch (Exception e) {
         MessageBox.Show(e.ToString());
     } finally {
         ascii = null;
         if (graphics != null) {
             if (graphics.CloseGraphics(out error) == 0) {
                 msg = "CloseGraphics method error code: " + error.ToString();
             }
             graphics = null;
         }
     }
 }
Example #9
0
        internal byte[] OutputAsBytes()
        {
            // Experimental

            MemoryStream ms = new MemoryStream();
            BinaryWriter bw = new BinaryWriter(ms, new ASCIIEncoding());

            bw.Write((int)0);
            bw.Write(RequestId);
            bw.Write((int)ServerDataSent);
            bw.Write(String1);
            bw.Write(String2);

            // End

            byte[] packetsize;
            byte[] req_id;
            byte[] serverdata;
            byte[] bstring1;
            byte[] bstring2;

            ASCIIEncoding Ascii = new ASCIIEncoding();

            bstring1 = Ascii.GetBytes(String1);
            bstring2 = Ascii.GetBytes(String2);

            serverdata = BitConverter.GetBytes((int)ServerDataSent);
            req_id = BitConverter.GetBytes(RequestId);

            // Compose into one packet.
            byte[] FinalPacket = new byte[4 + 4 + 4 + bstring1.Length + 1 + bstring2.Length + 1];
            packetsize = BitConverter.GetBytes(FinalPacket.Length - 4);

            int BPtr = 0;
            packetsize.CopyTo(FinalPacket, BPtr);
            BPtr += 4;

            req_id.CopyTo(FinalPacket, BPtr);
            BPtr += 4;

            serverdata.CopyTo(FinalPacket, BPtr);
            BPtr += 4;

            bstring1.CopyTo(FinalPacket, BPtr);
            BPtr += bstring1.Length;

            FinalPacket[BPtr] = (byte)0;
            BPtr++;

            bstring2.CopyTo(FinalPacket, BPtr);
            BPtr += bstring2.Length;

            FinalPacket[BPtr] = (byte)0;
            BPtr++;

            return FinalPacket;
        }
Example #10
0
        public static void ReceiveCallback(IAsyncResult AsyncCall)
        {
            allDone.Set();
            var DatajsonGuest = new ArduinoSP.DictionaryJson();
            {
                DatajsonGuest.temperDS18b20 = Form1.mas[2];
                DatajsonGuest.pressureBMP085 = Form1.mas[3];
                DatajsonGuest.temperBMP085 = Form1.mas[4];
                DatajsonGuest.humidityDHT22 = Form1.mas[5];
                DatajsonGuest.temperDHT22 = Form1.mas[6];
            }
            var jsondat = JsonConvert.SerializeObject(DatajsonGuest);
            //SocketAsyncEventArgs e = new SocketAsyncEventArgs();

            int i = 0;

            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();

            Socket listener = (Socket)AsyncCall.AsyncState;
            Socket client = listener.EndAccept(AsyncCall);

               try{

               while (true)
               {

                   i = client.Receive(cldata);
                   Byte[] message = encoding.GetBytes(jsondat);
                   if (i > 0)
                   {

                       data = Encoding.UTF8.GetString(cldata, 0, i);

                       if (data == "END")
                       {
                           Byte[] messagуe = encoding.GetBytes("ClientDisconnekt");
                           client.Send(messagуe);
                           client.Close();
                           break;

                       }
                       client.Send(message);
                   }
               }

            }

            catch (SocketException){
              }
             catch (Exception) { }

            // client.Close();

            // После того как завершили соединение, говорим ОС что мы готовы принять новое
             //   listener.BeginAccept(new AsyncCallback(ReceiveCallback), listener);
        }
Example #11
0
 internal String Sign(String feedId)
 {
     Encoding encoding = new ASCIIEncoding();
     var hashedSecret = (new SHA1Managed()).ComputeHash(encoding.GetBytes(_apiSecret));
     var hmac = new HMACSHA1(hashedSecret);
     return Convert.ToBase64String(hmac.ComputeHash(encoding.GetBytes(feedId)))
             .Replace('+', '-')
             .Replace('/', '_')
             .Trim('=');
 }
Example #12
0
 public void BuildKey(string newkey)
 {
     int start = 0;
     ASCIIEncoding asciiencoding = new ASCIIEncoding();
     //Convert the first 8 to chars to bytes and the last 
     //8 chars to bytes ignore the middle
     asciiencoding.GetBytes(newkey, start, key.Length, key, 0);
     start = newkey.Length - iv.Length;
     asciiencoding.GetBytes(newkey, start, iv.Length, iv, 0);
 }
 public string GetLatestLCLOLVersion()
 {
     if (File.Exists(Path.Combine(Client.ExecutingDirectory, "LC_LOL.Version")))
     {
         return File.ReadAllText(Path.Combine(Client.ExecutingDirectory, "LC_LOL.Version")).Split( new []{Environment.NewLine}, StringSplitOptions.None)[0];
     }
     var encoding = new ASCIIEncoding();
     File.Create(Path.Combine(Client.ExecutingDirectory, "LC_LOL.Version")).Write(encoding.GetBytes("0.0.0.0"), 0, encoding.GetBytes("0.0.0.0").Length);
     return "0.0.0.0";
 }
 public static string GenId(this string userAgent)
 {
     var hmac = HashLib.HashFactory.HMAC.CreateHMAC(HashLib.HashFactory.Crypto.CreateSHA224());
     ASCIIEncoding encoder = new ASCIIEncoding();
     var key = Guid.NewGuid().ToString();
     Byte[] code = encoder.GetBytes(key);
     hmac.Key = code;
     Byte[] hashMe = encoder.GetBytes(userAgent);
     Byte[] hmBytes = hmac.ComputeBytes(hashMe).GetBytes();
     return ToHexString(hmBytes);
 }
 public static string CalculateSignature(this string message, string secret)
 {
     ASCIIEncoding encoding = new ASCIIEncoding();
     byte[] keyByte = encoding.GetBytes(secret);
     HMACSHA1 hmacsha1 = new HMACSHA1(keyByte);
     byte[] messageBytes = encoding.GetBytes(message);
     byte[] hashMessage = hmacsha1.ComputeHash(messageBytes);
     string hexaHash = "";
     foreach (byte b in hashMessage) { hexaHash += String.Format("{0:x2}", b); }
     return hexaHash;
 }
        public TokenGenerator(String ResourceLocation, String Secret, UInt16 Generator)
        {
            ASCIIEncoding AsciiEncoder = new ASCIIEncoding();

            this.Generator = Generator;
            this.key = AsciiEncoder.GetBytes(Secret);
            this.message = AsciiEncoder.GetBytes(ResourceLocation);

            this.HMACSHA1Generator = new HMACSHA1(this.key);
            this.mac = this.HMACSHA1Generator.ComputeHash(this.message);
        }
        public String getInvoice()
        {
            TimeSpan t = DateTime.UtcNow - new DateTime(1970, 1, 1);
            int secondsSinceEpoch = (int)t.TotalSeconds;

            String json = "{\"nonce\": " + secondsSinceEpoch + ", \"method\": \"invoice\"}";

            //Encode the json version of the parameters above
            var convertedParam = Convert.ToBase64String(Encoding.UTF8.GetBytes(json));

            //Encrypt the parameters with sha256 using the secret as the key
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            byte[] keyByte = encoding.GetBytes(secret);
            HMACSHA256 hmacsha256 = new HMACSHA256(keyByte);
            byte[] messageBytes = encoding.GetBytes(convertedParam);
            byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);

            //Create the signature, a hex output of the encrypted hash above
            StringBuilder stringBuilder = new StringBuilder();
            foreach (byte b in hashmessage)
            {
                stringBuilder.AppendFormat("{0:X2}", b);
            }
            string signature = stringBuilder.ToString().ToLower();

            String url = baseUrl + "/api/invoice";
            WebRequest theRequest = WebRequest.Create(url);
            theRequest.Method = "POST";

            theRequest.ContentType = "text/x-json";
            theRequest.ContentLength = json.Length;
            theRequest.Headers["X-DIGITALX-KEY"] = key;
            theRequest.Headers["X-DIGITALX-PARAMS"] = convertedParam;
            theRequest.Headers["X-DIGITALX-SIGNATURE"] = signature;
            Stream requestStream = theRequest.GetRequestStream();

            requestStream.Write(Encoding.ASCII.GetBytes(json), 0, json.Length);
            requestStream.Close();

            HttpWebResponse response = (HttpWebResponse)theRequest.GetResponse();

            Stream responseStream = response.GetResponseStream();

            StreamReader myStreamReader = new StreamReader(responseStream, Encoding.Default);

            string pageContent = myStreamReader.ReadToEnd();

            myStreamReader.Close();
            responseStream.Close();

            response.Close();

            return pageContent;
        }
Example #18
0
        //generate hmac code
        public String HMAC(String data, String key)
        {
            ASCIIEncoding encoding = new ASCIIEncoding();

            //using hmach sha1 for hashing
            HMACSHA1 hmach_sha1 = new HMACSHA1(encoding.GetBytes(key));

            byte[] encrypted = hmach_sha1.ComputeHash(encoding.GetBytes(data));

            return ByteToString(encrypted);
        }
Example #19
0
 /// <summary>
 /// Compute HMACSHA256 hash based on message and secret
 /// </summary>
 /// <param name="message">Message</param>
 /// <param name="secret">Secret key</param>
 /// <returns>Base64 hash string</returns>
 private string HashHMAC(string message, string secret)
 {
     secret = secret ?? "";
     var encoding = new System.Text.ASCIIEncoding();
     byte[] keyByte = encoding.GetBytes(secret);
     byte[] messageBytes = encoding.GetBytes(message);
     using (var hmacsha256 = new HMACSHA256(keyByte))
     {
         byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
         return Convert.ToBase64String(hashmessage);
     }
 }
        /// <summary>
        /// Encodes a string into a hash using HMACSHA256
        /// </summary>
        /// <param name="stringToSign"></param>
        /// <param name="secretKey"></param>
        /// <returns></returns>
        public string EncodeStringToHMACSHA256(string stringToSign, string secretKey)
        {
            var encoding = new ASCIIEncoding();

            var keyByte = encoding.GetBytes(secretKey);
            var hmacsha256 = new HMACSHA256(keyByte);
            var messageBytes = encoding.GetBytes(stringToSign);
            var hashmessage = hmacsha256.ComputeHash(messageBytes);
            var signature = Convert.ToBase64String(hashmessage);

            return signature;
        }
Example #21
0
 public void Record(string FilePath)
 {
     //Create the stream first
     STR = new FileStream(FilePath, FileMode.Create);
     ASCIIEncoding ASCII = new ASCIIEncoding();
     //1 Write the header "RIFF"
     STR.Write(ASCII.GetBytes("RIFF"), 0, 4);
     //2 Write Chunck Size (0 for now)
     STR.WriteByte(0x00);
     STR.WriteByte(0x00);
     STR.WriteByte(0x00);
     STR.WriteByte(0x00);
     //3 Write WAVE
     STR.Write(ASCII.GetBytes("WAVE"), 0, 4);
     //4 Write "fmt "
     STR.Write(ASCII.GetBytes("fmt "), 0, 4);
     //5 Write Chunck Size (16 for PCM)
     STR.WriteByte(0x10);
     STR.WriteByte(0x00);
     STR.WriteByte(0x00);
     STR.WriteByte(0x00);
     //6 Write audio format (1 = PCM)
     STR.WriteByte(0x01);
     STR.WriteByte(0x00);
     //7 Number of channels (Mono = 1)
     STR.WriteByte(0x01);
     STR.WriteByte(0x00);
     //8 Sample Rate (44100)
     STR.WriteByte(0x44);
     STR.WriteByte(0xAC);
     STR.WriteByte(0x00);
     STR.WriteByte(0x00);
     //9 Byte Rate (88200)
     STR.WriteByte(0x88);
     STR.WriteByte(0x58);
     STR.WriteByte(0x01);
     STR.WriteByte(0x00);
     //10 Block Align (2)
     STR.WriteByte(0x02);
     STR.WriteByte(0x00);
     //11 Bits Per Sample (16)
     STR.WriteByte(0x10);
     STR.WriteByte(0x00);
     //12 Write "data"
     STR.Write(ASCII.GetBytes("data"), 0, 4);
     //13 Write Chunck Size (0 for now)
     STR.WriteByte(0x00);
     STR.WriteByte(0x00);
     STR.WriteByte(0x00);
     STR.WriteByte(0x00);
     //Confirm
     IsRecording = true;
 }
Example #22
0
        private void Code()
        {
            try
            {
                TcpClient tcpclnt = new TcpClient();
                Console.WriteLine("Connecting.....");

                tcpclnt.Connect("127.0.0.1", 8001);
                // use the ipaddress as in the server program

                Console.WriteLine("Connected");
                Console.WriteLine("Enter the strings to be transmitted: ");
                Console.WriteLine("Simply hit Enter to close the Socket.");

                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("===============================================================");
                Console.ForegroundColor = ConsoleColor.White;

                using (Stream stm = tcpclnt.GetStream())
                {
                    ASCIIEncoding asen = new ASCIIEncoding();

                    string str;
                    while (!string.IsNullOrWhiteSpace((str = Console.ReadLine())))
                    {
                        byte[] ba = asen.GetBytes(str);
                        Console.WriteLine(string.Format("Sending - {0}", str));
                        stm.Write(ba, 0, ba.Length);

                        byte[] bb = new byte[100];
                        int k = stm.Read(bb, 0, 100);

                        StringBuilder builder = new StringBuilder();
                        for (int i = 0; i < k; i++)
                            builder.Append(Convert.ToChar(bb[i]));

                        Console.WriteLine(builder.ToString());

                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.WriteLine("===============================================================");
                        Console.ForegroundColor = ConsoleColor.White;
                    }

                    stm.Write(asen.GetBytes("END"), 0, 3);
                    tcpclnt.Close();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error..... " + e.StackTrace);
            }
        }
Example #23
0
        public void TestMethodCHangeNick()
        {
            DSACryptoServiceProvider mycrypto = new DSACryptoServiceProvider();
            DSAParameters Publickey = mycrypto.ExportParameters(false);
            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] hash = mycrypto.SignData(encoding.GetBytes("Cuddy"));
            ServiceReference1.ServeurChatSoapClient a = new ServiceReference1.ServeurChatSoapClient();

            a.Register("Cuddy", "passbidon", hash, Publickey.Counter, Publickey.G, Publickey.J, Publickey.P, Publickey.Q, Publickey.Seed, Publickey.X, Publickey.Y);
            Assert.AreEqual(true, a.ChangeNick("Cuddy", "MissC", mycrypto.SignData(encoding.GetBytes("MissC"))));
            hash = mycrypto.SignData(encoding.GetBytes("MissC"));
            Assert.AreEqual(true, a.LogIn("MissC", "passbidon", hash, Publickey.Counter, Publickey.G, Publickey.J, Publickey.P, Publickey.Q, Publickey.Seed, Publickey.X, Publickey.Y));
        }
 private static string _CreateSignature(string message, string secret)
 {
     // don't allow null secrets
     secret = secret ?? "";
     var encoding = new System.Text.ASCIIEncoding();
     byte[] keyByte = encoding.GetBytes(secret);
     byte[] messageBytes = encoding.GetBytes(message);
     using (var hmacsha256 = new System.Security.Cryptography.HMACSHA256(keyByte))
     {
         byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
         return Convert.ToBase64String(hashmessage);
     }
 }
Example #25
0
        /// <summary>
        /// Hashes a <paramref name="password"/> with <paramref name="salt"/>.
        /// </summary>
        /// <param name="password">The password.</param>
        /// <param name="salt">The password salt.</param>
        /// <returns>The hashed password.</returns>
        public static string HashPassword(string password, string salt)
        {
            if (salt.Length == 0 || password.Length == 0)
            {
                return string.Empty;
            }

            Encoding en = new ASCIIEncoding();
            const int iterations = 768;
            const int keylength = 64;
            byte[] h = PasswordBasedKeyDerivationFunction2.GetBytes(en.GetBytes(password), en.GetBytes(salt), iterations, keylength);
            return Convert.ToBase64String(h);
        }
        private static string Sign(string str, string key)
        {
            var encoding = new ASCIIEncoding();

            byte[] signature;

            using (var crypto = new HMACSHA256(encoding.GetBytes(key)))
            {
                signature = crypto.ComputeHash(encoding.GetBytes(str));
            }

            return Base64Encode(signature);
        }
Example #27
0
 public SCdevicestate_class()
 {
     string sTemp;
     ASCIIEncoding encoding = new ASCIIEncoding();
     _type = CommandType.SCdevicestate;
     _data = new SCdevicestate();
     _data.stx = 0x02;
     sTemp = "sRN ";
     _data.type = encoding.GetBytes(sTemp);
     sTemp = "SCdevicestate";
     _data.cmd = encoding.GetBytes(sTemp);
     _data.etx = 0x03;
 }
Example #28
0
 public Client()
 {
     serverImage = new WriteableBitmap(TRANSMIT_WIDTH, TRANSMIT_HEIGHT, DPI_X, DPI_Y, PixelFormats.Bgra32, null);
     ASCIIEncoding enc = new ASCIIEncoding();
     COMPLETE_MESSAGE = enc.GetBytes("rcomplete");
     HELLO_MESSAGE = enc.GetBytes("hello");
     encoder = new ASCIIEncoding();
     backgroundImageData = new byte[TRANSMIT_IMAGE_SIZE];
     serverMessage = new byte[65535];
     xS = new byte[4];
     xE = new byte[4];
     yS = new byte[4];
     yE = new byte[4];
 }
Example #29
0
        public string ComputeHash(string message, string key)
        {
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            byte[] keyByte = encoding.GetBytes(key);

            HMACMD5 hmacmd5 = new HMACMD5(keyByte);
            HMACSHA1 hmacsha1 = new HMACSHA1(keyByte);

            byte[] messageBytes = encoding.GetBytes(message);

            byte[] hashmessage = hmacsha1.ComputeHash(messageBytes);
            string hmac = ByteToString(hashmessage);
            return hmac;
        }
        public List<byte> GetOutput()
        {
            var encoding = new ASCIIEncoding();
            var list = new List<byte>(encoding.GetBytes(XREF_MARKER));

            list.AddRange(encoding.GetBytes("0 " + Entries.Count + "\n"));

            foreach (var entry in Entries)
            {
                list.AddRange(encoding.GetBytes(entry.GetOutput()));
            }

            return list;
        }
    IEnumerator sendTestResults_IEnumerator(JSONObject scores)
    {
        //Debug.Log("sendTestResults: " + System.Text.Encoding.UTF8.GetBytes(scores.ToString()).ToString());

        scores.SetField("test_id", testToDo.GetField("id"));
        scores.SetField("timestamp", System.DateTime.Now.ToString());

        string url = server_url + "sendTestResults";

        HttpWebRequest http = (HttpWebRequest)WebRequest.Create(url);

        http.Accept      = "application/json";
        http.ContentType = "application/json";
        http.Method      = "POST";

        string parsedContent = scores.ToString();

        System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
        byte[] bytes = encoding.GetBytes(parsedContent);

        Stream newStream = http.GetRequestStream();

        newStream.Write(bytes, 0, bytes.Length);
        newStream.Close();

        var response = http.GetResponse();

        var stream  = response.GetResponseStream();
        var sr      = new StreamReader(stream);
        var content = sr.ReadToEnd();


        yield return(response);

        /*
         *
         * WWW www;
         *
         * Hashtable postHeader = new Hashtable();
         * postHeader.Add("Content-Type", "application/json");
         *
         * WWWForm lvl1 = new WWWForm();
         * lvl1.AddField("success", (int) scores.GetField("lvl1").GetField("success").n);
         * WWWForm form = new WWWForm();//(WWWForm) scores;//new WWWForm();
         *
         * //www = new WWW(url, System.Text.Encoding.UTF8.GetBytes(scores.ToString()));
         * www = new WWW(url, form);
         * yield return www;
         *
         * Debug.Log("REST sendTestResults: " + www.text);
         */

        sentToServer = true;
        //testToDo = new JSONObject(www.text);
    }
Example #32
0
    public static bool DecryptFile(string Filename, string Target)
    {
        if (!File.Exists(Filename))
        {
            _exception = new CryptographicException(ERR_NO_FILE);
            return(false);
        }

        //Make sure the target file can be written
        try {
            FileStream fs = File.Create(Target);
            fs.Close();
            //fs.Dispose()  ' Works with VB 2005 only
            File.Delete(Target);
        }
        catch (Exception ex) {
            _exception = new CryptographicException(ERR_FILE_WRITE);
            return(false);
        }

        byte[] inStream   = null;
        byte[] clearBytes = null;

        try {
            StreamReader objReader = null;
            FileStream   objFS     = null;
            System.Text.ASCIIEncoding objEncoding = new System.Text.ASCIIEncoding();
            objFS     = new FileStream(Filename, FileMode.Open);
            objReader = new StreamReader(objFS);
            inStream  = objEncoding.GetBytes(objReader.ReadToEnd());
        }
        // The following is the VB 2005 equivalent
        //inStream = File.ReadAllBytes(Filename)
        catch (Exception ex) {
            _exception = new CryptographicException(ERR_FILE_READ);
            return(false);
        }

        try {
            clearBytes = _Decrypt(inStream);
        }
        catch (Exception ex) {
            _exception = new CryptographicException(ex.Message, ex.InnerException);
            return(false);
        }

        //Create the decrypted file
        FileStream outStream = File.Create(Target);

        outStream.Write(clearBytes, 0, clearBytes.Length);
        outStream.Close();
        //outStream.Dispose() ' Works with VB 2005 only

        return(true);
    }
    public static LpmsVrInterface factory(string sensorId = "")
    {
        System.Text.ASCIIEncoding str = new System.Text.ASCIIEncoding();
        IntPtr sfs = lpStartSensorFusion(str.GetBytes(sensorId));

        if (sfs == IntPtr.Zero)
        {
            return(null);
        }
        return(new LpmsVrInterface(sfs));
    }
Example #34
0
    /// <summary>
    /// This function is used for encryption.
    /// </summary>
    /// <param name="strCode">The code.</param>
    /// <returns>string</returns>
    public static string Sha1Hash(string strCode)
    {
        string rehash = "";

        System.Security.Cryptography.SHA1 hash    = System.Security.Cryptography.SHA1.Create();
        System.Text.ASCIIEncoding         encoder = new System.Text.ASCIIEncoding();
        byte[] combined = encoder.GetBytes(strCode);
        hash.ComputeHash(combined);
        rehash = Convert.ToBase64String(hash.Hash);
        return(rehash);
    }
Example #35
0
    /// <summary>
    /// Generate the SHA256 hash from a passed string value
    /// </summary>
    public static string ComputeHash(string stringValue)
    {
        SHA256Managed shaM = new SHA256Managed();

        System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
        string correctPasswordHash    = BitConverter.ToString(shaM.ComputeHash(enc.GetBytes(stringValue)));

        // hash value cleanup
        correctPasswordHash = correctPasswordHash.Replace("-", string.Empty).ToLower();

        return(correctPasswordHash);
    }
Example #36
0
 public void start_server()
 {
     try
     {
         while (true)
         {
             System.Text.ASCIIEncoding encode = new System.Text.ASCIIEncoding();
             byte[] sendData = encode.GetBytes(Network.player.ipAddress.ToString());
             server.Send(sendData, sendData.Length, ip_broadcast, System.Convert.ToInt32(port));
             Thread.Sleep(100);
         }
     } catch {}
 }
Example #37
0
 //字符转ASCII码
 public static int Asc(string character)
 {
     if (character.Length == 1)
     {
         System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
         int intAsciiCode = (int)asciiEncoding.GetBytes(character)[0];
         return(intAsciiCode);
     }
     else
     {
         throw new Exception("Character is not valid. ");
     }
 }
Example #38
0
    public void writeString(string value)
    {
        short length = (short)value.Length;

        writeInt(length);
        System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
        byte[] bytes = encoding.GetBytes(value);
        for (short i = 0; i < length; i++)
        {
            mSendBuffer[mSendByteCounter + i] = bytes[i];
        }
        mSendByteCounter += length;
    }
 static public int GetBytes__String(IntPtr l)
 {
     try {
         System.Text.ASCIIEncoding self = (System.Text.ASCIIEncoding)checkSelf(l);
         System.String             a1;
         checkType(l, 2, out a1);
         var ret = self.GetBytes(a1);
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Example #40
0
    private static void TestReadingObjects(string xml)
    {
        System.Xml.Serialization.XmlSerializer xmlSerializer =
            new System.Xml.Serialization.XmlSerializer(typeof(Root));


        System.IO.Stream          stream   = new MemoryStream();
        System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
        Byte[] bytes = encoding.GetBytes(xml);
        stream.Write(bytes, 0, bytes.Length);
        stream.Position = 0;
        Root r = (Root)xmlSerializer.Deserialize(stream);

        Console.WriteLine(string.Format("Element 1 = {0}", r.Element1));

        Console.WriteLine(string.Format("Element 2 = {0}", r.Element2 == null ? "Null" : r.Element2));
    }
Example #41
0
    protected void Button7_Click(object sender, EventArgs e)
    {
        string userProvidedText = logtxt.Text;

        byte[] userProvidedTextAsBytes = null;

        if (!string.IsNullOrEmpty(userProvidedText))
        {
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            userProvidedTextAsBytes = encoding.GetBytes(userProvidedText);
        }

        Response.AppendHeader("Content-Disposition", "attachment; filename=ppmp_temp.csv");
        Response.ContentType = "text/HTML";
        Response.BinaryWrite(userProvidedTextAsBytes);
        Response.End();
    }
Example #42
0
 protected void btnSubmit_Click(object sender, EventArgs e)
 {
     try
     {
         if (ddlOfficerMailId.SelectedIndex != 0)
         {
             string str = "";
             System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
             byte[] data = encoding.GetBytes(str);
             objEmailmaster.EmailSenderId    = Convert.ToInt32(Session["StudentId"]);
             objEmailmaster.EMailBodyMsg     = txtbody.Text;
             objEmailmaster.EmailSubjectText = txtsubject.Text;
             objEmailmaster.EmailReciptedId  = Convert.ToInt32(ddlOfficerMailId.SelectedValue);
             if (Session["FileName"] != null && Session["FileContent"] != null)
             {
                 objEmailmaster.EmailAttachFileName    = Convert.ToString(Session["FileName"]);
                 objEmailmaster.EmailAttachFileContent = (byte[])Session["FileContent"];
             }
             else
             {
                 objEmailmaster.EmailAttachFileName    = "No FIle";
                 objEmailmaster.EmailAttachFileContent = data;
             }
             int i = objEmailmaster.InsertEmailMaster();
             if (i > 0)
             {
                 ClearData();
                 lblMsg.Text = "Your message has been sent.";
             }
             else
             {
                 lblMsg.Text = "Message Failed..";
             }
         }
         else
         {
             Page.RegisterClientScriptBlock("Student", "<script>Alert('Select To EmailId')</script>");
         }
     }
     catch (Exception ex)
     {
         lblMsg.Text = ex.Message;
     }
 }
 static public int GetBytes__A_Char__Int32__Int32(IntPtr l)
 {
     try {
         System.Text.ASCIIEncoding self = (System.Text.ASCIIEncoding)checkSelf(l);
         System.Char[]             a1;
         checkArray(l, 2, out a1);
         System.Int32 a2;
         checkType(l, 3, out a2);
         System.Int32 a3;
         checkType(l, 4, out a3);
         var ret = self.GetBytes(a1, a2, a3);
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            string str = "";
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            byte[] data = encoding.GetBytes(str);

            objEmailmaster.EmailSenderId    = Convert.ToInt32(Session["VolunteerId"]);
            objEmailmaster.EMailBodyMsg     = txtbody.Text;
            objEmailmaster.EmailSubjectText = txtsubject.Text;
            objEmailmaster.EmailReciptedId  = Convert.ToInt32(ddlto.SelectedValue);
            if (Session["FileName"] != null && Session["FileContent"] != null)
            {
                objEmailmaster.EmailAttachFileName    = Convert.ToString(Session["FileName"]);
                objEmailmaster.EmailAttachFileContent = (byte[])Session["FileContent"];
            }
            else
            {
                objEmailmaster.EmailAttachFileName    = "No FIle";
                objEmailmaster.EmailAttachFileContent = data;
            }

            mainPanel.Enabled = false;
            System.Threading.Thread.Sleep(2000);
            mainPanel.Enabled = true;
            int i = objEmailmaster.InsertEmailMaster();
            if (i > 0)
            {
                ClearData();
                lblMsg.Text = "Sending Email Sucessfully..";
            }
            else
            {
                lblMsg.Text = "Sending Failed..";
            }
        }
        catch (Exception ex)
        {
            lblMsg.Text = ex.Message;
        }
    }
Example #45
0
    public static void Main()
    {
        string baseIP = "192.168.1.";
        int    classD = 1;

        Console.WriteLine("Pinging 255 destinations of D-class in {0}*", baseIP);

        CreatePingers(255);

        PingOptions po = new PingOptions(ttl, true);

        System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
        byte[] data = enc.GetBytes("abababababababababababababababab");

        SpinWait wait = new SpinWait();
        int      cnt  = 1;

        Stopwatch watch = Stopwatch.StartNew();

        foreach (Ping p in pingers)
        {
            lock (@lock) {
                instances += 1;
            }

            p.SendAsync(string.Concat(baseIP, cnt.ToString()), timeOut, data, po);
            cnt += 1;
        }

        while (instances > 0)
        {
            wait.SpinOnce();
        }

        watch.Stop();

        DestroyPingers();

        Console.WriteLine("Finished in {0}. Found {1} active IP-addresses.", watch.Elapsed.ToString(), result);
        Console.ReadKey();
    }
Example #46
0
    protected string CutString(object obj)
    {
        string inputString = obj.ToString().Trim();

        System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();
        int    tempLen    = 0;
        int    len        = 82;
        string tempString = "";

        byte[] s = ascii.GetBytes(inputString);
        for (int i = 0; i < s.Length; i++)
        {
            if ((int)s[i] == 63)
            {
                tempLen += 2;
            }
            else
            {
                tempLen += 1;
            }
            try
            {
                tempString += inputString.Substring(i, 1);
            }
            catch
            {
                break;
            }
            if (tempLen > len)
            {
                break;
            }
        }
        //如果截过则加上个省略号
        byte[] mybyte = System.Text.Encoding.Default.GetBytes(inputString);
        if (mybyte.Length > len)
        {
            tempString += "…";
        }
        return(tempString);
    }
Example #47
0
    public static void ContainerMethod(TypeBuilder myDynamicType)
    {
        // <Snippet1>

        MethodBuilder myMethod = myDynamicType.DefineMethod("MyMethod",
                                                            MethodAttributes.Public,
                                                            typeof(int),
                                                            new Type[] { typeof(string) });

        // A 128-bit key in hex form, represented as a byte array.
        byte[] keyVal = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                          0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0xFF, 0xFF };

        System.Text.ASCIIEncoding encoder = new System.Text.ASCIIEncoding();
        byte[] symFullName = encoder.GetBytes("My Dynamic Method");

        myMethod.SetSymCustomAttribute("SymID", keyVal);
        myMethod.SetSymCustomAttribute("SymFullName", symFullName);

        // </Snippet1>
    }
Example #48
0
    public string CutString(string str, int len)
    {
        if (len == -1)
        {
            return(str);
        }
        int    tempLen    = 0;
        string tempString = "";

        System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();
        byte[] s = ascii.GetBytes(str);
        for (int i = 0; i < s.Length; i++)
        {
            if ((int)s[i] == 63)
            {
                tempLen += 2;
            }
            else
            {
                tempLen += 1;
            }

            if (i < str.Length)
            {
                tempString += str.Substring(i, 1);
            }

            if (tempLen >= len)
            {
                break;
            }
        }
        byte[] mybyte = System.Text.Encoding.Default.GetBytes(str);
        if (mybyte.Length > len)
        {
            tempString += "…";
        }

        return(tempString);
    }
Example #49
0
    public static int GetLength(string str)
    {
        if (str.Length == 0)
        {
            return(0);
        }
        System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();
        int tempLen = 0; byte[] s = ascii.GetBytes(str);

        for (int i = 0; i < s.Length; i++)
        {
            if ((int)s[i] == 63)
            {
                tempLen += 2;
            }
            else
            {
                tempLen += 1;
            }
        }
        return(tempLen);
    }
Example #50
0
    public void PortName_FileName()
    {
        string fileName = "PortNameEqualToFileName.txt";

        System.IO.FileStream      testFile  = System.IO.File.Open(fileName, System.IO.FileMode.Create);
        System.Text.ASCIIEncoding asciiEncd = new System.Text.ASCIIEncoding();
        string testStr = "Hello World";

        testFile.Write(asciiEncd.GetBytes(testStr), 0, asciiEncd.GetByteCount(testStr));

        testFile.Close();
        Debug.WriteLine("Verifying setting PortName={0}", fileName);

        VerifyException(fileName, ThrowAt.Open, typeof(ArgumentException), typeof(InvalidOperationException));

        Debug.WriteLine("Verifying setting PortName={0}", Environment.CurrentDirectory + fileName);

        VerifyException(Environment.CurrentDirectory + fileName, ThrowAt.Open, typeof(ArgumentException),
                        typeof(InvalidOperationException));

        System.IO.File.Delete(fileName);
    }
Example #51
0
        /// <summary>
        /// 检查输入框的内容是否合法;如果合法,就组包发给嵌入式设备;
        /// </summary>
        /// <returns></returns>
        private int PacketAndSend()
        {
            // id
            string id = "00 00 00 00 ";

            if (tbx_new_id.Text.Length != 11)
            {
                MessageBox.Show("ID错误!");
                return(-1);
            }
            id = tbx_new_id.Text + " ";

            // hardware revision
            string hwRevision = "00 00 00 00 ";

            if (tbx_new_hwRevision.Text.Length != 11)
            {
                MessageBox.Show("硬件版本错误");
                return(-2);
            }
            hwRevision = tbx_new_hwRevision.Text + " ";

            // customer
            string customer = "00 00 ";

            if (tbx_new_customer.Text.Length != 5)
            {
                MessageBox.Show("客户码错误");
                return(-3);
            }
            customer = tbx_new_customer.Text + " ";

            // debug
            string debug = "00 00 ";

            if (tbx_new_debug.Text.Length != 5)
            {
                MessageBox.Show("Debug错误!");
                return(-4);
            }
            debug = tbx_new_debug.Text + " ";

            // category
            string category = "00 ";

            if (tbx_new_category.Text.Length != 2)
            {
                MessageBox.Show("Category错误!");
                return(-5);
            }
            category = tbx_new_category.Text + " ";

            // interval
            string interval = "00 00 ";

            if (tbx_new_interval.Text == "" || tbx_new_interval.Text.Length > 5)
            {
                MessageBox.Show("时间间隔错误!");
                return(-6);
            }
            UInt16 intervalI = Convert.ToUInt16(tbx_new_interval.Text);

            interval = (intervalI / 256).ToString("X2") + " " + (intervalI % 256).ToString("X2") + " ";

            // pattern
            string pattern = "00 ";

            if (tbx_new_pattern.Text.Length != 2)
            {
                MessageBox.Show("工作模式错误!");
                return(-7);
            }
            pattern = tbx_new_pattern.Text + " ";

            // bps
            string bps = cbx_new_bps.SelectedIndex.ToString("X2") + " ";

            // channel
            string channel = cbx_new_channel.SelectedIndex.ToString("X2") + " ";

            // carousel
            string carousel = "00 00 ";

            if (tbx_new_carousel.Text == "" || tbx_new_carousel.Text.Length > 5)
            {
                MessageBox.Show("轮播间隔错误!");
                return(-8);
            }
            UInt16 carouselI = Convert.ToUInt16(tbx_new_carousel.Text);

            carousel = (carouselI / 256).ToString("X2") + " " + (carouselI % 256).ToString("X2") + " ";

            // alert
            string alert = "00 00 ";

            if (tbx_new_alert.Text == "" || tbx_new_alert.Text.Length > 5)
            {
                MessageBox.Show("轮播间隔错误!");
                return(-9);
            }
            UInt16 alertI = Convert.ToUInt16(tbx_new_alert.Text);

            alert = (alertI / 256).ToString("X2") + " " + (alertI % 256).ToString("X2") + " ";

            // transPolicy
            string transPolicy = cbx_new_transPolicy.SelectedIndex.ToString("X2") + " ";

            // timeSrc
            string timeSrc = cbx_new_timeSrc.SelectedIndex.ToString("X2") + " ";

            // Server Domain
            string ServerDomain = "";

            tbx_new_serverDomain.Text = tbx_new_serverDomain.Text.Trim();       // 去除域名中的空格
            if (tbx_new_serverDomain.Text == "")
            {
                MessageBox.Show("服务器域名错误!");
                return(-10);
            }

            byte SDL = (byte)tbx_new_serverDomain.Text.Length;

            for (int iCount = 0; iCount < SDL; iCount++)
            {
                string b = tbx_new_serverDomain.Text.Substring(iCount, 1);

                System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
                int intAsciiCode = (int)asciiEncoding.GetBytes(b)[0];

                ServerDomain += intAsciiCode.ToString("X2") + " ";
            }

            // Server Port
            string ServerPort = "00 00 ";

            if (tbx_new_serverPort.Text == "" || tbx_new_serverPort.Text.Length > 5)
            {
                MessageBox.Show("服务器端口错误!");
                return(-11);
            }
            UInt16 ServerPortI = Convert.ToUInt16(tbx_new_serverPort.Text);

            ServerPort = (ServerPortI / 256).ToString("X2") + " " + (ServerPortI % 256).ToString("X2") + " ";

            //发送指令
            string sendStr = "CB 4C " + id + hwRevision + customer + debug + category + interval + pattern + bps + channel + carousel + alert + transPolicy + timeSrc + SDL.ToString("X2") + " " + ServerDomain + ServerPort + "BC";

            try
            {
                Send(sendStr);
            }
            catch
            {
                MessageBox.Show("指令发送失败!");
                return(-12);
            }

            return(0);
        }
Example #52
0
 public OSCPacket GetOSCPacket(string bytes)
 {
     System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
     return(GetOSCPacket(encoding.GetBytes(bytes)));
 }
Example #53
0
        // this is the ELV MAX! Cube monitoring script
        public void Run()
        {
            while (running)
            {
                TcpClient     client;
                NetworkStream stream;
                Dictionary <String, IMAXDevice> currentHouse = new Dictionary <string, IMAXDevice>();

                #region Update House
                try
                {
                    // now fill that with the initial handshake data...

                    #region Initial connect and retrieving everything we get from the cube
                    // network connect and first initialization
                    client = new TcpClient();
                    client.Connect(Hostname, Port);
                    stream = client.GetStream();

                    // the read buffer (chosen quite big)
                    byte[]        myReadBuffer = new byte[4096 * 8];
                    List <String> Messages     = new List <string>();

                    // to build the complete message
                    StringBuilder myCompleteMessage = new StringBuilder();
                    int           numberOfBytesRead = 0;

                    MAXEncodeDecode DecoderEncoder = new MAXEncodeDecode();
                    keepRunning = true;

                    // Incoming message may be larger than the buffer size.
                    do
                    {
                        myCompleteMessage  = new StringBuilder();
                        stream.ReadTimeout = 1000;
                        try
                        {
                            numberOfBytesRead = stream.Read(myReadBuffer, 0, myReadBuffer.Length);
                            myCompleteMessage.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead));

                            Messages.Add(myCompleteMessage.ToString());
                        }
                        catch (Exception)
                        {
                            previousHouse = null;
                            // everything to start
                            theHouse = new House();

                            keepRunning = false;
                        }
                    }while(keepRunning);
                    #endregion

                    #region preprocess
                    List <String> PreProcessedMessages = new List <string>();
                    foreach (String _Message in Messages)
                    {
                        if (_Message.Remove(_Message.Length - 2).Contains("\r\n"))
                        {
                            String[] PMessages = _Message.Remove(_Message.Length - 2).Split(new char[1] {
                                '\n'
                            }, StringSplitOptions.RemoveEmptyEntries);
                            foreach (String pmessage in PMessages)
                            {
                                PreProcessedMessages.Add(pmessage.Replace("\r", "") + "\r\n");
                            }
                        }
                        else
                        {
                            PreProcessedMessages.Add(_Message);
                        }
                    }
                    #endregion

                    #region process
                    // Analyze and Output Messages, feed them to the decoder
                    foreach (String _Message in PreProcessedMessages)
                    {
                        //IMAXMessage Message = DecoderEncoder.ProcessMessage(_Message.ToString(), theHouse);
                        //							if (Message != null)
                        //							{
                        //								ConsoleOutputLogger.WriteLine(_Message.ToString());
                        //								ConsoleOutputLogger.WriteLine(Message.ToString());
                        //								ConsoleOutputLogger.WriteLine("");
                        //							}

                        DecoderEncoder.ProcessMessage(_Message.ToString(), theHouse);
                    }
                    #endregion

                    while (running)
                    {
                        connected = true;
                        // when we are here, we got a filled "theHouse" which does contain first hand L message information
                        previousHouse = theHouse.GetAllDevicesInADictionary();

                        #region send L: request and get all the feedback
                        System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
                        byte[] args_data_buffer       = enc.GetBytes("l:\r\n");
                        Messages    = new List <string>();
                        keepRunning = true;
                        // Incoming message may be larger than the buffer size.
                        stream.Write(args_data_buffer, 0, args_data_buffer.Length);
                        do
                        {
                            myCompleteMessage  = new StringBuilder();
                            stream.ReadTimeout = 1000;
                            try
                            {
                                numberOfBytesRead = stream.Read(myReadBuffer, 0, myReadBuffer.Length);
                                myCompleteMessage.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead));

                                Messages.Add(myCompleteMessage.ToString());
                            }
                            catch (Exception)
                            {
                                keepRunning = false;
                            }
                        }while(keepRunning);
                        #endregion

                        #region preprocess
                        PreProcessedMessages = new List <string>();
                        foreach (String _Message in Messages)
                        {
                            if (_Message.Remove(_Message.Length - 2).Contains("\r\n"))
                            {
                                String[] PMessages = _Message.Remove(_Message.Length - 2).Split(new char[1] {
                                    '\n'
                                }, StringSplitOptions.RemoveEmptyEntries);
                                foreach (String pmessage in PMessages)
                                {
                                    PreProcessedMessages.Add(pmessage.Replace("\r", "") + "\r\n");
                                }
                            }
                            else
                            {
                                PreProcessedMessages.Add(_Message);
                            }
                        }
                        #endregion

                        #region process
                        // Analyze and Output Messages, feed them to the decoder
                        foreach (String _Message in PreProcessedMessages)
                        {
                            //IMAXMessage Message = DecoderEncoder.ProcessMessage(_Message.ToString(), theHouse);
                            //							if (Message != null)
                            //							{
                            //								ConsoleOutputLogger.WriteLine(_Message.ToString());
                            //								ConsoleOutputLogger.WriteLine(Message.ToString());
                            //								ConsoleOutputLogger.WriteLine("");
                            //							}
                            currentHouse = new Dictionary <string, IMAXDevice>();
                            DecoderEncoder.ProcessLMessage(_Message.ToString(), theHouse, currentHouse);
                        }
                        #endregion

                        #region Diff the house
                        if (previousHouse != null)
                        {
                            // only if we already got two houses in here...
                            List <IDeviceDiffSet> differences = DiffHouse.CalculateDifferences(previousHouse, currentHouse);
                            if (differences.Count != 0)
                            {
                                #region enqueue the difference-sets into the data queue
                                foreach (IDeviceDiffSet _difference in differences)
                                {
                                    iQueue.Enqueue(_difference);
                                }
                                #endregion
                            }
                        }
                        #endregion
                        theHouse.UpdateDevices(currentHouse);

                        // update appropriate devices and in given intervals output non updated
                        TimeSpan _lastUpdate = DateTime.Now - LastReStoring;

                        // auto-update every n ... minutes
                        if (_lastUpdate.TotalSeconds > ELVMAXSensorReStoringSec)
                        {
                            LastReStoring = DateTime.Now;

                            foreach (IMAXDevice _device in currentHouse.Values)
                            {
                                #region Heating Thermostat
                                if (_device.Type == DeviceTypes.HeatingThermostat)
                                {
                                    HeatingThermostat     _heating   = (HeatingThermostat)_device;
                                    HeatingThermostatDiff _queueable = new HeatingThermostatDiff(_device.Name, _device.AssociatedRoom.RoomID, _device.AssociatedRoom.RoomName);

                                    if (_heating.LowBattery)
                                    {
                                        _queueable.LowBattery = BatteryStatus.lowbattery;
                                    }
                                    else
                                    {
                                        _queueable.LowBattery = BatteryStatus.ok;
                                    }

                                    _queueable.Mode        = _heating.Mode;
                                    _queueable.Temperature = _heating.Temperature;

                                    if (_queueable.Temperature != 0)
                                    {
                                        iQueue.Enqueue(_queueable);
                                    }
                                }
                                #endregion

                                #region ShutterContact
                                if (_device.Type == DeviceTypes.ShutterContact)
                                {
                                    ShutterContact     _shutter   = (ShutterContact)_device;
                                    ShutterContactDiff _queueable = new ShutterContactDiff(_device.Name, _device.AssociatedRoom.RoomID, _device.AssociatedRoom.RoomName);

                                    if (_shutter.LowBattery)
                                    {
                                        _queueable.LowBattery = BatteryStatus.lowbattery;
                                    }
                                    else
                                    {
                                        _queueable.LowBattery = BatteryStatus.ok;
                                    }

                                    _queueable.ShutterState = _shutter.ShutterState;
                                    iQueue.Enqueue(_queueable);
                                }
                                #endregion
                            }
                        }
                        Thread.Sleep(MAXUpdateTime);
                    }
                }
                catch (Exception)
                {
                    connected = false;
                    Thread.Sleep(ELVMAXReconnectTimeMsec);
                    //stream.Close();
                    //client.Close();
                }
                #endregion
            }
        }
Example #54
0
        public async Task Run(string tag, string value, UiLambdaSet uiLambda = null)
        {
            ServicePointManager.ServerCertificateValidationCallback =
                new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);

            // Initializes the variables to pass to the MessageBox.Show method.
            string caption = "Connect with " + tag + ".dat";
            string message = "";

            bool withOpenidFile = false;

            if (value != "")
            {
                dataServer = value;
                authServer = "";
                certPfx    = "";
                certPfxPW  = "";
                value      = "";
            }
            else
            {
                // read openx.dat
                try
                {
                    using (StreamReader sr = new StreamReader(tag + ".dat"))
                    {
                        authServer = sr.ReadLine();
                        dataServer = sr.ReadLine();
                        certPfx    = sr.ReadLine();
                        certPfxPW  = sr.ReadLine();
                        outputDir  = sr.ReadLine();
                    }
                }
                catch (Exception ex)
                {
                    AdminShellNS.LogInternally.That.Error(ex, $"The file {tag}.dat can not be read.");
                    return;
                }
                withOpenidFile = true;
            }

            message =
                "authServer: " + authServer + "\n" +
                "dataServer: " + dataServer + "\n" +
                "certPfx: " + certPfx + "\n" +
                "certPfxPW: " + certPfxPW + "\n" +
                "outputDir: " + outputDir + "\n" +
                "\nConinue?";

            // Displays the MessageBox.
            var result = UiLambdaSet.MesssageBoxShow(uiLambda, message, "", caption, AnyUiMessageBoxButton.YesNo);

            if (result != AnyUiMessageBoxResult.Yes)
            {
                // Closes the parent form.
                return;
            }

            UiLambdaSet.MesssageBoxShow(uiLambda, "", "Access Aasx Server at " + dataServer,
                                        "Data Server", AnyUiMessageBoxButton.OK);

            var handler = new HttpClientHandler();

            handler.DefaultProxyCredentials = CredentialCache.DefaultCredentials;
            handler.AllowAutoRedirect       = false;
            var client = new HttpClient(handler)
            {
                BaseAddress = new Uri(dataServer)
            };

            if (token != "")
            {
                client.SetBearerToken(token);
            }

            string operation     = "";
            string lastOperation = "";

            if (withOpenidFile)
            {
                operation     = "authenticate";
                lastOperation = "/server/listaas/";
            }
            else
            {
                operation = "/server/listaas/";
            }

            while (operation != "" && operation != "error")
            {
                UiLambdaSet.MesssageBoxShow(uiLambda, "", "operation: " + operation + value + "\ntoken: " + token,
                                            "Operation", AnyUiMessageBoxButton.OK);

                switch (operation)
                {
                case "/server/listaas/":
                case "/server/getaasx2/":
                    try
                    {
                        HttpResponseMessage response2 = null;
                        switch (operation)
                        {
                        case "/server/listaas/":
                            response2 = await client.GetAsync(operation);

                            break;

                        case "/server/getaasx2/":
                            response2 = await client.GetAsync(operation + value);

                            break;
                        }

                        if (response2.StatusCode == System.Net.HttpStatusCode.TemporaryRedirect)
                        {
                            string   redirectUrl = response2.Headers.Location.ToString();
                            string[] splitResult = redirectUrl.Split(new string[] { "?" },
                                                                     StringSplitOptions.RemoveEmptyEntries);
                            Console.WriteLine("Redirect to:" + splitResult[0]);
                            authServer = splitResult[0];
                            UiLambdaSet.MesssageBoxShow(
                                uiLambda, authServer, "", "Redirect to", AnyUiMessageBoxButton.OK);
                            lastOperation = operation;
                            operation     = "authenticate";
                            continue;
                        }
                        if (!response2.IsSuccessStatusCode)
                        {
                            lastOperation = operation;
                            operation     = "error";
                            continue;
                        }
                        String urlContents = await response2.Content.ReadAsStringAsync();

                        switch (operation)
                        {
                        case "/server/listaas/":
                            UiLambdaSet.MesssageBoxShow(uiLambda,
                                                        "", "SelectFromListFlyoutItem missing", "SelectFromListFlyoutItem missing",
                                                        AnyUiMessageBoxButton.OK);
                            return;

                        case "/server/getaasx2/":
                            try
                            {
                                var parsed3 = JObject.Parse(urlContents);

                                string fileName = parsed3.SelectToken("fileName").Value <string>();
                                string fileData = parsed3.SelectToken("fileData").Value <string>();

                                var enc         = new System.Text.ASCIIEncoding();
                                var fileString4 = Jose.JWT.Decode(fileData, enc.GetBytes(secretString),
                                                                  JwsAlgorithm.HS256);
                                var parsed4 = JObject.Parse(fileString4);

                                string binaryBase64_4 = parsed4.SelectToken("file").Value <string>();
                                Byte[] fileBytes4     = Convert.FromBase64String(binaryBase64_4);

                                Console.WriteLine("Writing file: " + outputDir + "\\" + "download.aasx");
                                File.WriteAllBytes(outputDir + "\\" + "download.aasx", fileBytes4);
                            }
                            catch (Exception ex)
                            {
                                AdminShellNS.LogInternally.That.Error(ex, $"Failed at operation: {operation}");
                                lastOperation = operation;
                                operation     = "error";
                            }
                            operation = "";
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        AdminShellNS.LogInternally.That.Error(ex, $"Failed at operation: {operation}");
                        lastOperation = operation;
                        operation     = "error";
                    }
                    break;

                case "authenticate":
                    try
                    {
                        X509SigningCredentials x509Credential = null;
                        if (withOpenidFile)
                        {
                            x509Credential = new X509SigningCredentials(new X509Certificate2(certPfx, certPfxPW));
                        }

                        var response = await RequestTokenAsync(x509Credential, uiLambda);

                        token = response.AccessToken;
                        client.SetBearerToken(token);

                        response.Show();
                        UiLambdaSet.MesssageBoxShow(uiLambda, response.AccessToken, "",
                                                    "Access Token", AnyUiMessageBoxButton.OK);

                        operation     = lastOperation;
                        lastOperation = "";
                    }
                    catch (Exception ex)
                    {
                        AdminShellNS.LogInternally.That.Error(ex, $"Failed at operation: {operation}");
                        lastOperation = operation;
                        operation     = "error";
                    }
                    break;

                case "error":
                    UiLambdaSet.MesssageBoxShow(uiLambda, "", $"Can not perform: {lastOperation}",
                                                "Error", AnyUiMessageBoxButton.OK);
                    break;
                }
            }
        }
Example #55
0
 ///<summary>
 ///Convert string to Base64 string
 ///<param name="target">String variable</param>
 ///</summary>
 public static string ToBase64String(this string target)
 {
     System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
     byte[] bytes = encoding.GetBytes(target);
     return(System.Convert.ToBase64String(bytes, 0, bytes.Length));
 }
Example #56
0
    protected void ButLogin_Click(object sender, EventArgs e)
    {
        try
        {
            int?   userId;
            string connectionString            = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["CustomerRecoveryConnectionString"].ConnectionString;
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectionString);
            string name = builder.InitialCatalog;
            CRBusinessLogicLayer.IsValidUser(txtUserName.Text, txtPassword.Text, out userId);
            if (userId == null)
            {
                txtUserName.Text = "";
                txtPassword.Text = "";
                LbError.Text     = "Invalid  User Name/Password.";
                LbError.Visible  = true;
            }
            else
            {
                var    ds                        = CRBusinessLogicLayer.GetSequerityQuestion((int)userId);
                string SessionuserID             = name + "_" + "userid";
                var    UserType                  = ds.Tables[0].Rows[0]["UserRole"].ToString();
                var    CityID                    = ds.Tables[0].Rows[0]["City"].ToString();
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, txtUserName.Text, DateTime.Now, DateTime.Now.AddDays(7), true, String.Format("{0}|{1}|{2}", txtUserName.Text, userId, UserType));
                string hash                      = FormsAuthentication.Encrypt(ticket);
                FormsAuthentication.SetAuthCookie(txtUserName.Text, true);
                Response.AppendCookie(new HttpCookie(SessionuserID, userId.ToString()));
                Response.AppendCookie(new HttpCookie("UserName", txtUserName.Text));
                Response.AppendCookie(new HttpCookie("UserRole", UserType));
                System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
                Byte[] bytes = encoding.GetBytes(txtPassword.Text);
                string pwd   = CRBusinessLogicLayer.PassEncrypt(bytes);
                Response.AppendCookie(new HttpCookie("Pass", pwd));
                Response.AppendCookie(new HttpCookie("CityID", CityID));
                Response.AppendCookie(new HttpCookie("USERID", userId.ToString()));
                Response.AppendCookie(new HttpCookie("udata", hash));

                string url = string.Empty;
                ds = CRBusinessLogicLayer.GetUserAccessURL((int)userId);
                if (ds.Tables[0].Rows.Count == 1)
                {
                    url = ds.Tables[0].Rows[0]["ScreenURL"].ToString();
                }
                else if (url == string.Empty)
                {
                    Response.Redirect(
                        Convert.ToInt16(UserType) == 2
                            ? "~/DailyTransactions/NPADetails.aspx"
                            : "~/Masters/Farmer.aspx", false);
                }
                if (url != string.Empty)
                {
                    Response.Redirect(url, false);
                }
            }
        }
        catch (Exception ex)
        {
            LbError.Text    = ex.Message;
            LbError.Visible = true;
        }
    }
Example #57
0
 public static byte[] stringToByteArray(string input)
 {
     System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
     return(encoding.GetBytes(input));
 }
Example #58
0
 static private byte[] StringToByteArray(string str)
 {
     System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
     return(enc.GetBytes(str));
 }
Example #59
0
    public static bool EncryptFile(string Filename, string Target)
    {
        if (!File.Exists(Filename))
        {
            _exception = new CryptographicException(ERR_NO_FILE);
            return(false);
        }

        //Make sure the target file can be written
        try {
            FileStream fs = File.Create(Target);
            fs.Close();
            //fs.Dispose()  ' Works with VB 2005 only
            File.Delete(Target);
        }
        catch (Exception ex) {
            _exception = new CryptographicException(ERR_FILE_WRITE);
            return(false);
        }

        byte[] inStream    = null;
        byte[] cipherBytes = null;

        try {
            StreamReader objReader = null;
            FileStream   objFS     = null;
            System.Text.ASCIIEncoding objEncoding = new System.Text.ASCIIEncoding();
            objFS     = new FileStream(Filename, FileMode.Open);
            objReader = new StreamReader(objFS);
            inStream  = objEncoding.GetBytes(objReader.ReadToEnd());
        }
        // The following is the VB 2005 equivalent
        //inStream = File.ReadAllBytes(Filename)
        catch (Exception ex) {
            _exception = new CryptographicException(ERR_FILE_READ);
            return(false);
        }

        try {
            cipherBytes = _Encrypt(inStream);
        }
        catch (CryptographicException ex) {
            _exception = ex;
            return(false);
        }

        string encodedString = string.Empty;

        if (_encodingType == EncodingType.BASE_64)
        {
            encodedString = System.Convert.ToBase64String(cipherBytes);
        }
        else
        {
            encodedString = BytesToHex(cipherBytes);
        }

        byte[] encodedBytes = Encoding.UTF8.GetBytes(encodedString);

        //Create the encrypted file
        FileStream outStream = File.Create(Target);

        outStream.Write(encodedBytes, 0, encodedBytes.Length);
        outStream.Close();
        //outStream.Dispose()  ' Works with VB 2005 only

        return(true);
    }
Example #60
0
 public static byte[] StrToByteArray(string str)
 {
     System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
     return(encoding.GetBytes(str));
 }