public static string SHA1(string content, Encoding encode)
 {
     try
     {
         SHA1   sha1      = new SHA1CryptoServiceProvider();
         byte[] bytes_in  = encode.GetBytes(content);
         byte[] bytes_out = sha1.ComputeHash(bytes_in);
         sha1.Dispose();
         string result = BitConverter.ToString(bytes_out);
         result = result.Replace("-", "");
         return(result);
     }
     catch
     {
         return(null);
     }
 }
Exemple #2
0
 protected string EncryptToSHA1(string str)
 {
     try
     {
         SHA1   sha1      = new SHA1CryptoServiceProvider();
         byte[] bytes_in  = Encoding.UTF8.GetBytes(str);
         byte[] bytes_out = sha1.ComputeHash(bytes_in);
         sha1.Dispose();
         string result = BitConverter.ToString(bytes_out);
         result = result.Replace("-", "");
         return(result.ToLower());
     }
     catch (Exception ex)
     {
         throw new Exception("SHA1 Encrypt Error" + ex.Message);
     }
 }
Exemple #3
0
        /// <summary>
        /// Get signature for the chunk.
        /// </summary>
        /// <param name="array">The data of the chunk.</param>
        /// <returns>The signature instance.</returns>
        private SignatureObject GetSignature(byte[] array)
        {
            if (this.FileContent.Length <= 250 * 1024 * 1024)
            {
                SHA1   sha  = new SHA1CryptoServiceProvider();
                byte[] temp = sha.ComputeHash(array);
                sha.Dispose();

                SignatureObject signature = new SignatureObject();
                signature.SignatureData = new BinaryItem(temp);
                return(signature);
            }
            else
            {
                throw new NotImplementedException("When the file size is larger than 250MB, the signature method is not implemented.");
            }
        }
Exemple #4
0
 /// <summary>
 /// SHA1加密
 /// </summary>
 /// <param name="content">待加密的字符串</param>
 /// <param name="encode">编码方式</param>
 /// <returns></returns>
 public static String Sha1Sign(String content, Encoding encode)
 {
     try
     {
         SHA1   sha1      = new SHA1CryptoServiceProvider(); //创建SHA1对象
         byte[] bytes_in  = encode.GetBytes(content);        //将待加密字符串转为byte类型
         byte[] bytes_out = sha1.ComputeHash(bytes_in);      //Hash运算
         sha1.Dispose();                                     //释放当前实例使用的所有资源
         String result = BitConverter.ToString(bytes_out);   //将运算结果转为string类型
         result = result.Replace("-", "").ToUpper();
         return(result);
     }
     catch (Exception ex)
     {
         return(ex.Message);
     }
 }
Exemple #5
0
 private string Sha1Encrypt(string source)
 {
     try
     {
         var    sha1 = new SHA1CryptoServiceProvider();
         byte[] byt1 = System.Text.Encoding.UTF8.GetBytes(source);
         byte[] byt2 = sha1.ComputeHash(byt1);
         sha1.Dispose();
         string result = BitConverter.ToString(byt2);
         result = result.Replace("-", "");
         return(result);
     }
     catch
     {
         return("");
     }
 }
        /// <summary>
        /// SHA1加密
        /// </summary>
        /// <param name="content"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static string SHA1Encrypt(string content, string encoding = "utf-8")
        {
            SHA1 sha1 = new SHA1CryptoServiceProvider();

            //SHA1 sha1 = System.Security.Cryptography.SHA1.Create();
            byte[] bytesIn  = System.Text.Encoding.GetEncoding(encoding).GetBytes(content);
            byte[] bytesOut = sha1.ComputeHash(bytesIn);

#if NET35
            sha1.Clear();
#else
            sha1.Dispose();
#endif
            string result = BitConverter.ToString(bytesOut);
            result = result.Replace("-", "");
            return(result);
        }
Exemple #7
0
        public string GetFileChecksum()
        {
            if (string.IsNullOrWhiteSpace(FilePath))
            {
                throw new ArgumentException("检验器校验目标文件路径为空");
            }
            FileStream file = new FileStream(FilePath, FileMode.Open);
            SHA1       sha1 = new SHA1CryptoServiceProvider(); //创建SHA1对象

            byte[] sha1Bytes = sha1.ComputeHash(file);         //Hash运算
            sha1.Dispose();                                    //释放当前实例使用的所有资源
            file.Dispose();
            string result = BitConverter.ToString(sha1Bytes);  //将运算结果转为string类型

            result = result.Replace("-", "");
            return(result);
        }
Exemple #8
0
 /// <summary>
 /// SHA1 加密,返回大写字符串
 /// </summary>
 /// <param name="content">需要加密字符串</param>
 /// <param name="encode">指定加密编码</param>
 /// <returns>返回40位大写字符串</returns>
 private static string SHA1(string content, Encoding encode)
 {
     try
     {
         SHA1 sha1 = new SHA1CryptoServiceProvider();
         byte[] bytes_in = encode.GetBytes(content);
         byte[] bytes_out = sha1.ComputeHash(bytes_in);
         sha1.Dispose();
         string result = BitConverter.ToString(bytes_out);
         result = result.Replace("-", "");
         return result;
     }
     catch (Exception ex)
     {
         throw new Exception("SHA1加密出错:" + ex.Message);
     }
 }
Exemple #9
0
        public static string Base64SHA1(string content)
        {
            try {
                SHA1   sha1      = new SHA1CryptoServiceProvider();
                byte[] bytes_in  = Encoding.UTF8.GetBytes(content);
                byte[] bytes_out = sha1.ComputeHash(bytes_in);
                sha1.Dispose();
                string result = Convert.ToBase64String(bytes_out);

                //string result1 = BitConverter.ToString(bytes_out);
                //result1 = result1.Replace("-", "");
                //result1 = Convert.ToBase64String(Encoding.UTF8.GetBytes(result1));

                return(result);
            } catch (Exception ex) {
                throw new Exception("SHA1加密出错:" + ex.Message);
            }
        }
Exemple #10
0
        public Encryption(byte[] key = null)
        {
            if (key == null)
            {
                key = new byte[8];
                Random generator = new Random();
                generator.NextBytes(key);
                generator = null;
            }
            Key = key;
            SHA1 digest = new SHA1CryptoServiceProvider();

            key = digest.ComputeHash(key);
            digest.Dispose();
            Log.Info("[ENCRYPTION-KEY]", DumpData(key));
            encryption = new ARC4(key);
            decryption = new ARC4(key);
        }
        /// <summary>
        /// 加密字符串
        /// </summary>
        /// <param name="content">要加密的字符串</param>
        /// <param name="encode">字符串编码</param>
        /// <returns>加密后的字符串</returns>
        public static string Encrypt(string content, Encoding encode)
        {
            try
            {
                SHA1 sha1     = new SHA1CryptoServiceProvider();
                var  bytesIn  = encode.GetBytes(content);
                var  bytesOut = sha1.ComputeHash(bytesIn);
                sha1.Dispose();

                var result = BitConverter.ToString(bytesOut);
                result = result.Replace("-", "");
                return(result);
            }
            catch (Exception ex)
            {
                throw new Exception("SHA1加密失败:" + ex.Message);
            }
        }
Exemple #12
0
 public static string SHA1Hash(string content)
 {
     try
     {
         using (var sha1 = new SHA1CryptoServiceProvider())
         {
             var bytes_in  = Encoding.UTF8.GetBytes(content);
             var bytes_out = sha1.ComputeHash(bytes_in);
             sha1.Dispose();
             var result = BitConverter.ToString(bytes_out);
             result = result.Replace("-", "");
             return(result);
         }
     }
     catch (Exception ex)
     {
         throw new Exception("SHA1加密出错:" + ex.Message);
     }
 }
Exemple #13
0
        public static String getSha1(String str)
           
        {
                   //建立SHA1对象
                   SHA1 sha = new SHA1CryptoServiceProvider();
                   //将mystr转换成byte[]
                   ASCIIEncoding enc        = new ASCIIEncoding();
                   byte[]        dataToHash = enc.GetBytes(str);
                   //Hash运算
                   byte[] dataHashed = sha.ComputeHash(dataToHash);

            sha.Dispose();
                   //将运算结果转换成string
                   string hash = BitConverter.ToString(dataHashed).Replace("-", "");

                       return(hash);

               
        }
Exemple #14
0
        /// <summary>
        /// SHA1 加密
        /// </summary>
        public static string Sha1(string dataStr, Encoding encoding)
        {
            if (string.IsNullOrEmpty(dataStr))
            {
                return(string.Empty);
            }

            SHA1 sha1 = new SHA1CryptoServiceProvider();

            byte[]        hashStr = sha1.ComputeHash(encoding.GetBytes(dataStr));
            StringBuilder sb      = new StringBuilder();

            foreach (byte btStr in hashStr)
            {
                sb.AppendFormat("{0:X2}", btStr);
            }
            sha1.Dispose();
            return(sb.ToString());
        }
Exemple #15
0
        public Encryption(byte[] key = null)
        {
            if (key == null)
            {
                key = new byte[8];
                Random generator = new Random();
                generator.NextBytes(key);
                generator = null;
            }
            Key = key;
            SHA1 digest = new SHA1CryptoServiceProvider();

            key = digest.ComputeHash(key);
            digest.Dispose();
            Console.Write("New key:");
            for (int i = 0; i < 20; i++)
            {
                Console.Write(" " + key[i]);
            }
            Console.WriteLine();
            encryption = new ARC4(key);
            decryption = new ARC4(key);
        }
Exemple #16
0
 public static string SHA1(string content, Encoding encode = null)
 {
     if (encode == null)
     {
         encode = Encoding.UTF8;
     }
     try
     {
         var    sha1      = new SHA1CryptoServiceProvider();
         byte[] bytes_in  = encode.GetBytes(content);
         byte[] bytes_out = sha1.ComputeHash(bytes_in);
         sha1.Dispose();
         var enText = new StringBuilder();
         foreach (byte iByte in bytes_out)
         {
             enText.AppendFormat("{0:x2}", iByte);
         }
         return(enText.ToString().ToUpper());
     }
     catch (Exception ex)
     {
         throw new Exception("SHA1加密出错:" + ex.Message);
     }
 }
        private void convert_button_Click(object sender, EventArgs e)
        {
            if (chip_selection_comboBox.SelectedItem.ToString().Length == 0)
            {
                MessageBox.Show("请选择芯片类型", "芯片类型未选择!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (Hex_StartAddr_textBox.TextLength == 0)
            {
                MessageBox.Show("未给定Hex文件起始地址", "请设置Hex文件起始地址!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            else if ((UInt64.Parse(Hex_StartAddr_textBox.Text, System.Globalization.NumberStyles.HexNumber) > 0xffffffff) ||
                     (UInt64.Parse(Hex_StartAddr_textBox.Text, System.Globalization.NumberStyles.HexNumber) < 0x0A0000))
            {
                MessageBox.Show("hex地址越界", "请设置Hex起始地址范围0x0A0000~0xFFFFFFFF!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                Hex_StartAddr_textBox.Text = "0";
                return;
            }

            if (targetfile_full_name_textBox.TextLength == 0)
            {
                MessageBox.Show("请设定转换程序完整名称", "转换后的程序名不能为空!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            else if (targetfile_full_name_textBox.TextLength >= HEADER_FILE_FULL_NAME_SIZE)
            {
                MessageBox.Show("设定转换程序名称过长", "转换后的程序名长度不能超过86字节!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                targetfile_full_name_textBox.Text = "";
                return;
            }
            else
            {
                if (targetfile_full_name_textBox.Text.Substring(targetfile_full_name_textBox.Text.Length - 1, 1) == "/")
                {
                    MessageBox.Show("是文件全名不是文件路径", "文件名格式错误!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    targetfile_full_name_textBox.Text = "";
                    return;
                }
            }

            if (orgfile_select_comboBox.Text.Length == 0)
            {
                MessageBox.Show("请选择要转换的文件", "文件名不能为空!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (!File.Exists(orgfile_select_comboBox.Text))
            {
                MessageBox.Show("文件不存在", "请选择要转换的文件!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            FileStream fs = new FileStream(orgfile_select_comboBox.Text, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

            file_size_textBox.Text = fs.Length.ToString();

            crc_cal  crc_check  = new crc_cal();
            Sha1_cal sha1_check = new Sha1_cal();

            byte[] org_file_content = new byte[fs.Length + CUSTOMIZED_HEADER_SIZE + sha1_check.SHA1HashSize];
            org_file_content[HEADER_CHIP_TYPE_START]      = (byte)chip_selection_comboBox.SelectedIndex;
            org_file_content[HEADER_FILE_TYPE_START]      = (byte)((UInt16.Parse(file_type_comboBox.SelectedItem.ToString()) & 0xff00) >> 8);
            org_file_content[HEADER_FILE_TYPE_START + 1]  = (byte)(UInt16.Parse(file_type_comboBox.SelectedItem.ToString()) & 0xff);
            org_file_content[HEADER_FILE_BYTES_START]     = (byte)((fs.Length & 0xFF000000) >> 24);
            org_file_content[HEADER_FILE_BYTES_START + 1] = (byte)((fs.Length & 0xFF0000) >> 16);
            org_file_content[HEADER_FILE_BYTES_START + 2] = (byte)((fs.Length & 0xFF00) >> 8);
            org_file_content[HEADER_FILE_BYTES_START + 3] = (byte)(fs.Length & 0xFF);

            UInt32 i = 0;

            /* fill header file full name with char ‘\0' */
            for (i = 0; i < HEADER_FILE_FULL_NAME_SIZE; i++)
            {
                org_file_content[HEADER_FILE_FULL_NAME_START + i] = (byte)('\0');
            }

            byte[] targetfile_full_name_array = System.Text.Encoding.Default.GetBytes(targetfile_full_name_textBox.Text);

            /* copy target file full name to specified address */
            for (i = 0; i < targetfile_full_name_array.Length; i++)
            {
                org_file_content[HEADER_FILE_FULL_NAME_START + i] = targetfile_full_name_array[i];
            }

            UInt16 crc16_ret = 0;

            /* calculate CRC16 result for customized header */
            crc16_ret = crc_check.crc16(0, org_file_content, CUSTOMIZED_HEADER_SIZE - 2);
            org_file_content[HEADER_CRC16_START]     = (byte)((crc16_ret & 0xff00) >> 8); // high byte of crc16
            org_file_content[HEADER_CRC16_START + 1] = (byte)(crc16_ret & 0x00ff);        // low byte of crc16

            byte[] org_file_array = new byte[fs.Length];
            fs.Seek(0, SeekOrigin.Begin);
            fs.Read(org_file_array, 0, (int)fs.Length);  // read all bytes of original file to be converted

            /* copy file data */
            for (i = 0; i < org_file_array.Length; i++)
            {
                org_file_content[FILE_CONTENT_START + i] = org_file_array[i];
            }

            /* calculate sha1 */
            //sha1_check.SHA1Reset();
            //sha1_check.SHA1Input(org_file_content, (uint)(fs.Length + CUSTOMIZED_HEADER_SIZE));
            //byte[] sha1_check_result = new byte[sha1_check.SHA1HashSize];
            //sha1_check.SHA1Result(ref sha1_check_result);

            SHA1 sha1 = new SHA1CryptoServiceProvider();                                                         //创建SHA1对象

            byte[] bytes_out = sha1.ComputeHash(org_file_content, 0, (int)(fs.Length + CUSTOMIZED_HEADER_SIZE)); //Hash运算
            sha1.Dispose();                                                                                      //释放当前实例使用的所有资源
            String result = BitConverter.ToString(bytes_out);                                                    //将运算结果转为string类型


            /* copy 20 bytes of sha1 result to the file end */
            for (i = 0; i < sha1_check.SHA1HashSize; i++)
            {
                org_file_content[FILE_CONTENT_START + org_file_array.Length + i] = bytes_out[i];
            }

            string[] strArray = orgfile_select_comboBox.Text.Split('\\'); //'\\'为'\'的转义字符

            /* convert bytes to S19 or hex file according to specified format */
            string hex_file_name = System.IO.Directory.GetCurrentDirectory();

            if ((comboBox_target_file_opt.SelectedItem.ToString() == "s19") || (comboBox_target_file_opt.SelectedItem.ToString() == "S19"))
            {
                BinToS19 bin_2_s19 = new BinToS19();
                bin_2_s19.BinFile2S19File(UInt32.Parse(Hex_StartAddr_textBox.Text, System.Globalization.NumberStyles.HexNumber), org_file_content, strArray[strArray.Length - 1] + ".s19");
            }
            else if ((comboBox_target_file_opt.SelectedItem.ToString() == "hex") || (comboBox_target_file_opt.SelectedItem.ToString() == "Hex"))
            {
                BinToHex bin_2_hex = new BinToHex();
                bin_2_hex.BinFile2HexFile(UInt32.Parse(Hex_StartAddr_textBox.Text, System.Globalization.NumberStyles.HexNumber), org_file_content, strArray[strArray.Length - 1] + ".hex");
            }

            fs.Close();
            fs.Dispose();

            StringBuilder strB = new StringBuilder();

            for (i = 0; i < 96; i++)
            {
                strB.Append(org_file_content[i].ToString("X2"));
            }

            disp_richTextBox.Text = result; // strB.ToString();
        }
Exemple #18
0
        public static byte[] LogonProof(IPacketReader packet)
        {
            byte[] A   = packet.ReadBytes(32);
            byte[] kM1 = packet.ReadBytes(20);
            byte[] rA  = A.Reverse().ToArray();
            byte[] AB  = A.Concat(B.GetBytes(32).Reverse()).ToArray();

            if (new BigInteger(A) % new BigInteger(N) == 0)
            {
                return(new byte[1]);
            }

            SHA1 sha = new SHA1CryptoServiceProvider();

            byte[] rU = sha.ComputeHash(AB).Reverse().ToArray();

            //SS_Hash
            BigInteger s = V.ModPow(new BigInteger(rU), new BigInteger(RN));

            s *= new BigInteger(rA);
            s  = s.ModPow(new BigInteger(RB), new BigInteger(RN));

            byte[] S1 = new byte[16];
            byte[] S2 = new byte[16];
            byte[] S  = s.GetBytes(32);
            byte[] rS = S.Reverse().ToArray();
            for (int t = 0; t < 16; t++)
            {
                S1[t] = rS[t * 2];
                S2[t] = rS[(t * 2) + 1];
            }

            byte[] hashS1 = sha.ComputeHash(S1);
            byte[] hashS2 = sha.ComputeHash(S2);
            SS_Hash = new byte[hashS1.Length + hashS2.Length];
            for (int t = 0; t < hashS1.Length; t++)
            {
                SS_Hash[t * 2]       = hashS1[t];
                SS_Hash[(t * 2) + 1] = hashS2[t];
            }

            //calc M1
            byte[] M1;
            byte[] NHash   = sha.ComputeHash(N);
            byte[] GHash   = sha.ComputeHash(G.GetBytes());
            byte[] NG_Hash = new byte[20];
            for (int t = 0; t < 20; t++)
            {
                NG_Hash[t] = (byte)(NHash[t] ^ GHash[t]);
            }

            IEnumerable <byte> tmp = NG_Hash.Concat(sha.ComputeHash(BUsername));

            tmp = tmp.Concat(Salt);
            tmp = tmp.Concat(A);
            tmp = tmp.Concat(B.GetBytes(32).Reverse());
            tmp = tmp.Concat(SS_Hash);
            M1  = sha.ComputeHash(tmp.ToArray());

            //calc M2
            byte[] M2;
            tmp = A.Concat(M1);
            tmp = tmp.Concat(SS_Hash);
            M2  = sha.ComputeHash(tmp.ToArray());

            sha.Dispose();

            IEnumerable <byte> result = new byte[] { 1, 0 };

            result = result.Concat(M2);
            result = result.Concat(new byte[4]);
            return(result.ToArray());
        }
Exemple #19
0
        private void Run()
        {
            this.LoadConfig();
            this.currentConfigCancelSource = new CancellationTokenSource();

            ServiceProxy coreService;

            try
            {
                coreService = new ServiceProxy()
                {
                    CanSendCallbacks = false
                };
                ServiceHost host = new ServiceHost(coreService);
                host.Open();
                coreService.SettingsUpdatedEvent += CoreService_SettingsUpdatedEvent;
            }
            catch (Exception ex)
            {
                Trace.TraceError(ex.ToString());
                throw;
            }

            do
            {
                if (this.settings != null)
                {
                    coreService.Settings         = this.settings;
                    coreService.CanSendCallbacks = true;
                    Trace.TraceInformation(this.settings.ToString());
                    this.currentConfigCancelSource = new CancellationTokenSource();
                    WlanClient client = new WlanClient();
                    WlanClient.WlanInterface wlanIface = client.Interfaces.SingleOrDefault(p => p.InterfaceGuid.Equals(this.settings.WlanInterfaceId));
                    if (wlanIface == null)
                    {
                        throw new ArgumentException("The provided wlan interface id does not exist.");
                    }

                    byte[]        otpKey      = Base32.Base32Encoder.Decode(this.settings.SecretKeyBase32);
                    OtpSharp.Totp otpProvider = new OtpSharp.Totp(otpKey, this.settings.StepSeconds, totpSize: this.settings.TotpDigitCount);

                    WLANProfile defaultProfile = WLANProfile.Default(this.settings.ESSID);
                    if (wlanIface.GetProfiles().Any(p => p.profileName.Equals(this.settings.ESSID)))
                    {
                        wlanIface.DeleteProfile(this.settings.ESSID);
                    }

                    XmlSerializer xmlSer      = new XmlSerializer(typeof(WLANProfile));
                    string        textProfile = String.Empty;
                    using (StringWriter writer = new StringWriter())
                    {
                        xmlSer.Serialize(writer, defaultProfile);
                        textProfile = writer.ToString();
                    }

                    DateTime currentDate;
                    DateTime nextChange;
                    nextChange = currentDate = DateTime.UtcNow;

                    SHA1CryptoServiceProvider sha1Provider = new SHA1CryptoServiceProvider();
                    string pskhash = BitConverter.ToString(sha1Provider.ComputeHash(Encoding.ASCII.GetBytes(this.settings.PSHK))).Replace("-", "").ToLower();

                    do
                    {
                        try
                        {
                            double sleepSeconds = 0.1;
                            if (currentDate >= nextChange)
                            {
                                try
                                {
                                    //Generate key
                                    string otp      = otpProvider.ComputeTotp(currentDate);
                                    string totphash = BitConverter.ToString(sha1Provider.ComputeHash(Encoding.ASCII.GetBytes(otp))).Replace("-", "").ToLower();
                                    string newKey   = BitConverter.ToString(sha1Provider.ComputeHash(Encoding.ASCII.GetBytes(totphash + pskhash))).Replace("-", "").ToLower();
                                    Trace.TraceInformation(otp + " - " + newKey);
                                    //if (wlanIface.CurrentConnection.profileName.Equals(networkName, StringComparison.OrdinalIgnoreCase))
                                    {
                                        string newProf = profileRegex.Replace(textProfile, $"<protected>false</protected><keyMaterial>{newKey}</keyMaterial>");
                                        wlanIface.SetProfile(Wlan.WlanProfileFlags.AllUser, newProf, true);
                                        if (this.settings.AutoConnect)
                                        {
                                            //wlanIface.Connect(Wlan.WlanConnectionMode.Profile, Wlan.Dot11BssType.Any, defaultProfile.Name);
                                            wlanIface.Connect(Wlan.WlanConnectionMode.Profile, Wlan.Dot11BssType.Any, defaultProfile.Name);
                                        }
                                    }

                                    int desync = (int)DateTime.UtcNow.TimeOfDay.TotalSeconds % this.settings.StepSeconds;
                                    nextChange = DateTime.UtcNow.AddSeconds(this.settings.StepSeconds - desync);

                                    Task.Factory.StartNew(() => coreService.UpdateValues(newKey, nextChange));
                                    sleepSeconds = this.settings.StepSeconds - desync - 1;
                                    Trace.TraceInformation("Next change: " + nextChange.ToString("T"));
                                }
                                catch (Exception e)
                                {
                                    Trace.TraceError(e.ToString());
                                }
                            }

                            //Task.Delay(TimeSpan.FromSeconds(sleepSeconds), this.currentConfigCancelSource.Token).Wait();
                            this.currentConfigCancelSource.Token.WaitHandle.WaitOne(TimeSpan.FromSeconds(sleepSeconds));
                            currentDate = DateTime.UtcNow;
                        }
                        catch (AggregateException)
                        { }
                    } while (!this.currentConfigCancelSource.IsCancellationRequested);
                    sha1Provider.Dispose();
                }
                else
                {
                    coreService.CanSendCallbacks = false;
                    Trace.TraceInformation("Waiting for a valid settings");
                    //Task.Delay(TimeSpan.FromSeconds(10), this.currentConfigCancelSource.Token).Wait();
                    this.currentConfigCancelSource.Token.WaitHandle.WaitOne(TimeSpan.FromSeconds(60));
                }
            } while (!this.serviceCancelSource.IsCancellationRequested);
        }
 public void Dispose()
 {
     _hashProvider.Dispose();
 }
        /// <summary>
        /// 爬取课程表
        /// 注意打不开新版树维教务系统网站时会抛出异常,需要增加判断,树维教务系统:http://219.216.96.4/eams/loginExt.action
        /// 注意返回的Course未合并相同Name的项
        /// </summary>
        /// <param name="username">树维教务系统用户名</param>
        /// <param name="password">树维教务系统密码</param>
        /// <returns></returns>
        public async Task <List <Course> > LoginAndGetCoursesAsync(string Username, string Password)
        {
            string Url1 = "http://219.216.96.4/eams/loginExt.action";                       // 第一次请求和第二次请求
            string Url2 = "http://219.216.96.4/eams/courseTableForStd.action";              // 第三次请求
            string Url3 = "http://219.216.96.4/eams/courseTableForStd!courseTable.action";  // 第四次请求
            string Url4 = "http://219.216.96.4/eams/logout.action";                         // 第五次请求

            var        Handler = new HttpClientHandler();
            HttpClient Client  = new HttpClient(Handler);

            Client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:66.0) Gecko/20100101 Firefox/66.0");

            // 第一次请求
            HttpResponseMessage Response = await Client.GetAsync(Url1);

            // 获取响应关键内容
            string Content = await Response.Content.ReadAsStringAsync();

            Content = Content.Substring(Content.IndexOf("CryptoJS.SHA1("), 80);
            Content = Content.Substring(15, 37);

            // 密码使用SHA1进行哈希
            Password = Content + Password;
            SHA1 Sha1 = new SHA1CryptoServiceProvider();

            byte[] BytesIn  = Encoding.UTF8.GetBytes(Password);
            byte[] BytesOut = Sha1.ComputeHash(BytesIn);
            Sha1.Dispose();
            Password = BitConverter.ToString(BytesOut);
            Password = Password.Replace("-", "").ToLower();

            // 第二次请求
            var Values = new Dictionary <string, string>
            {
                { "username", Username },
                { "password", Password },
                { "session_locale", "zh_CN" }
            };
            var FormContent = new FormUrlEncodedContent(Values);

            // 发送请求
            Thread.Sleep(1000);
            Response = await Client.PostAsync(Url1, FormContent);

            Content = await Response.Content.ReadAsStringAsync();

            if (!Content.Contains("personal-name"))
            {
                System.Diagnostics.Debug.WriteLine("error");
                return(null);
            }

            // 第三次请求
            Thread.Sleep(1000);
            Response = await Client.GetAsync(Url2);

            Content = await Response.Content.ReadAsStringAsync();

            if (!Content.Contains("addInput(form,\"ids\""))
            {
                System.Diagnostics.Debug.WriteLine("error");
                return(null);
            }
            Content = Content.Substring(Content.IndexOf("if(jQuery(\"#courseTableType\").val()==\"std\"){"), 180);
            string ids = Content.Substring(Content.IndexOf("bg.form.addInput(form") + 29, Content.IndexOf("\");") - Content.IndexOf("bg.form.addInput(form") - 29);

            // 第四次请求
            Values = new Dictionary <string, string>
            {
                { "ignoreHead", "1" },
                { "showPrintAndExport", "1" },
                { "setting.kind", "std" },
                { "startWeek", "" },
                { "semester.id", "30" },
                { "ids", ids }
            };
            FormContent = new FormUrlEncodedContent(Values);

            // 发送请求
            Thread.Sleep(1000);
            Response = await Client.PostAsync(Url3, FormContent);

            Content = await Response.Content.ReadAsStringAsync();

            if (!Content.Contains("课表格式说明"))
            {
                System.Diagnostics.Debug.WriteLine("error");
                return(null);
            }

            // 第五次请求
            Thread.Sleep(1000);
            await Client.GetAsync(Url4);

            // 解析得到的课程表数据
            string Pattern = @"var actTeachers = \[(?:{id:(\d+),name:""([^""]+)"",lab:(?:false|true)},?)+\];(?:\s|\S)+?TaskActivity\(actTeacherId.join\(','\),actTeacherName.join\(','\),""(.*)"",""(.*)\(.*\)"",""(.*)"",""(.*)"",""(.*)"",null,null,assistantName,"""",""""\);(\s*index =(\d+)\*unitCount\+(\d+);\s*.*\s)+";

            // 查看正则匹配结果
            List <Course> AllCourses = new List <Course>();

            foreach (Match match in Regex.Matches(Content, Pattern))
            {
                // 教师名字
                Group  TempGroup   = match.Groups[2];
                String TeacherName = "";
                foreach (Capture TempCapture in TempGroup.Captures)
                {
                    if (TeacherName == "")
                    {
                        TeacherName = TempCapture.Value;
                    }
                    else
                    {
                        TeacherName = TeacherName + ", " + TempCapture.Value;
                    }
                }

                // 课程名称
                String CourseName = match.Groups[4].Captures[0].Value;

                // 教室地点
                String Location = match.Groups[6].Captures[0].Value;

                // 教学周
                String Week = match.Groups[7].Captures[0].Value;

                // 周几上课
                int.TryParse(match.Groups[9].Captures[0].Value, out int WeekDay);

                // 开始于第几节
                int BeginTime = 13;
                // 结束于第几节
                int EndTime = -1;

                foreach (Capture capture in match.Groups[10].Captures)
                {
                    int.TryParse(capture.Value, out int TempInt);
                    if (TempInt < BeginTime)
                    {
                        BeginTime = TempInt;
                    }
                    if (TempInt > EndTime)
                    {
                        EndTime = TempInt;
                    }
                }
                Course TempCourse = new Course
                {
                    Name    = CourseName,
                    Teacher = TeacherName
                };
                TempCourse.AddLocTime(Location, Week, WeekDay + 1, BeginTime + 1, EndTime + 1);
                AllCourses.Add(TempCourse);
                System.Diagnostics.Debug.WriteLine(CourseName + TeacherName);
            }

            return(AllCourses);
        }
Exemple #22
0
        public static byte[] LogonProof(IPacketReader packet)
        {
            byte[] A   = packet.ReadBytes(32);
            byte[] kM1 = packet.ReadBytes(20);
            byte[] rA  = A.Reverse().ToArray();
            byte[] AB  = A.Concat(B.GetBytes(32).Reverse()).ToArray();

            if (new BigInteger(A) % new BigInteger(N) == 0)
            {
                return(new byte[1]);
            }

            SHA1 sha1 = new SHA1CryptoServiceProvider();

            byte[] rU = sha1.ComputeHash(AB).Reverse().ToArray();

            // SS_Hash
            BigInteger s = V.ModPow(new BigInteger(rU), new BigInteger(RN));

            s *= new BigInteger(rA);
            s  = s.ModPow(new BigInteger(RB), new BigInteger(RN));

            byte[] S1 = new byte[16];
            byte[] S2 = new byte[16];
            byte[] S  = s.GetBytes(32);
            byte[] rS = S.Reverse().ToArray();
            for (int t = 0; t < 16; t++)
            {
                S1[t] = rS[t * 2];
                S2[t] = rS[(t * 2) + 1];
            }

            byte[] hashS1  = sha1.ComputeHash(S1);
            byte[] hashS2  = sha1.ComputeHash(S2);
            byte[] ss_hash = new byte[hashS1.Length + hashS2.Length];
            for (int t = 0; t < hashS1.Length; t++)
            {
                ss_hash[t * 2]       = hashS1[t];
                ss_hash[(t * 2) + 1] = hashS2[t];
            }

            // calc M1
            byte[] M1;
            byte[] NHash   = sha1.ComputeHash(N);
            byte[] GHash   = sha1.ComputeHash(G.GetBytes());
            byte[] NG_Hash = new byte[20];

            for (int t = 0; t < 20; t++)
            {
                NG_Hash[t] = (byte)(NHash[t] ^ GHash[t]);
            }

            var tmp = NG_Hash.Concat(sha1.ComputeHash(BUsername))
                      .Concat(Salt)
                      .Concat(A)
                      .Concat(B.GetBytes(32).Reverse())
                      .Concat(ss_hash);

            M1 = sha1.ComputeHash(tmp.ToArray());

            // calc M2
            byte[] M2;
            tmp = A.Concat(M1).Concat(ss_hash);
            M2  = sha1.ComputeHash(tmp.ToArray());
            sha1.Dispose();

            // instantiate coders/cryptors
            PacketCrypt = new PacketCrypt(ss_hash, ClientBuild);

            // additional information, always zeroed
            int extradata = 0;

            if (ClientBuild < 6178 || ClientBuild == 6180)
            {
                extradata = 04; // uint unk
            }
            else if (ClientBuild < 8089)
            {
                extradata = 06; // uint unk, ushort unkFlags
            }
            else
            {
                extradata = 10; // uint account flag, uint surveyId, ushort unkFlags
            }
            byte[] result = new byte[22 + extradata];
            result[0] = 1;
            Array.Copy(M2, 0, result, 2, M2.Length);
            return(result);
        }
Exemple #23
0
        /// <summary>
        /// Convert the ushort array to a byte arraay, compressing with the requested algorithm if required
        /// </summary>
        /// <param name="data"></param>
        /// <returns>Uncompressed or compressed byte array</returns>
        private byte[] PrepareArray(ushort[] data)
        {
            byte[] outArray;

            /*
             * Convert the ushort[] into a byte[]
             * From here onwards we deal in byte arrays only
             */
            byte[] byteArray = new byte[data.Length * ShuffleItemSize];
            Buffer.BlockCopy(data, 0, byteArray, 0, data.Length * ShuffleItemSize);

            /*
             * Compress the data block as configured.
             */
            using (MyStopWatch.Measure($"XISF Compression = {CompressionType}")) {
                if (CompressionType == XISFCompressionTypeEnum.LZ4)
                {
                    if (ByteShuffling)
                    {
                        CompressionName = "lz4+sh";
                        byteArray       = Shuffle(byteArray, ShuffleItemSize);
                    }
                    else
                    {
                        CompressionName = "lz4";
                    }

                    byte[] tmpArray       = new byte[LZ4Codec.MaximumOutputSize(byteArray.Length)];
                    int    compressedSize = LZ4Codec.Encode(byteArray, 0, byteArray.Length, tmpArray, 0, tmpArray.Length, LZ4Level.L00_FAST);

                    outArray = new byte[compressedSize];
                    Array.Copy(tmpArray, outArray, outArray.Length);
                    tmpArray = null;
                }
                else if (CompressionType == XISFCompressionTypeEnum.LZ4HC)
                {
                    if (ByteShuffling)
                    {
                        CompressionName = "lz4hc+sh";
                        byteArray       = Shuffle(byteArray, ShuffleItemSize);
                    }
                    else
                    {
                        CompressionName = "lz4hc";
                    }

                    byte[] tmpArray       = new byte[LZ4Codec.MaximumOutputSize(byteArray.Length)];
                    int    compressedSize = LZ4Codec.Encode(byteArray, 0, byteArray.Length, tmpArray, 0, tmpArray.Length, LZ4Level.L06_HC);

                    outArray = new byte[compressedSize];
                    Array.Copy(tmpArray, outArray, outArray.Length);
                    tmpArray = null;
                }
                else if (CompressionType == XISFCompressionTypeEnum.ZLIB)
                {
                    if (ByteShuffling)
                    {
                        CompressionName = "zlib+sh";
                        byteArray       = Shuffle(byteArray, ShuffleItemSize);
                    }
                    else
                    {
                        CompressionName = "zlib";
                    }

                    outArray = ZlibStream.CompressBuffer(byteArray);
                }
                else
                {
                    outArray = new byte[byteArray.Length];
                    Array.Copy(byteArray, outArray, outArray.Length);
                    CompressionName = null;
                }
            }

            // Revert to the original data array in case the compression is bigger than uncompressed
            if (outArray.Length > byteArray.Length)
            {
                if (ByteShuffling)
                {
                    //As the original array is shuffled it needs to be unshuffled again - this scenario should be highly unlikely anyways
                    outArray = Unshuffle(byteArray, ShuffleItemSize);
                }
                else
                {
                    outArray = byteArray;
                }
                CompressionType = XISFCompressionTypeEnum.NONE;

                Logger.Debug("XISF output array is larger after compression. Image will be prepared uncompressed instead.");
            }

            if (CompressionType != XISFCompressionTypeEnum.NONE)
            {
                double percentChanged = (1 - ((double)outArray.Length / (double)byteArray.Length)) * 100;
                Logger.Debug($"XISF: {CompressionType} compressed {byteArray.Length} bytes to {outArray.Length} bytes ({percentChanged.ToString("#.##")}%)");
            }

            /*
             * Checksum the data block as configured.
             * If the data block is compressed, we always checksum the compressed form, not the uncompressed form.
             */
            using (MyStopWatch.Measure($"XISF Checksum = {ChecksumType}")) {
                SHA3Managed sha3;

                switch (ChecksumType)
                {
                case XISFChecksumTypeEnum.SHA1:
                    SHA1 sha1 = new SHA1CryptoServiceProvider();
                    Checksum     = GetStringFromHash(sha1.ComputeHash(outArray));
                    ChecksumName = "sha-1";
                    sha1.Dispose();
                    break;

                case XISFChecksumTypeEnum.SHA256:
                    SHA256 sha256 = new SHA256CryptoServiceProvider();
                    Checksum     = GetStringFromHash(sha256.ComputeHash(outArray));
                    ChecksumName = "sha-256";
                    sha256.Dispose();
                    break;

                case XISFChecksumTypeEnum.SHA512:
                    SHA512 sha512 = new SHA512CryptoServiceProvider();
                    Checksum     = GetStringFromHash(sha512.ComputeHash(outArray));
                    ChecksumName = "sha-512";
                    sha512.Dispose();
                    break;

                case XISFChecksumTypeEnum.SHA3_256:
                    sha3         = new SHA3Managed(256);
                    Checksum     = GetStringFromHash(sha3.ComputeHash(outArray));
                    ChecksumName = "sha3-256";
                    sha3.Dispose();
                    break;

                case XISFChecksumTypeEnum.SHA3_512:
                    sha3         = new SHA3Managed(512);
                    Checksum     = GetStringFromHash(sha3.ComputeHash(outArray));
                    ChecksumName = "sha3-512";
                    sha3.Dispose();
                    break;

                case XISFChecksumTypeEnum.NONE:
                default:
                    Checksum     = null;
                    ChecksumName = null;
                    break;
                }
            }

            return(outArray);
        }
Exemple #24
0
        public override void ChannelRead(IChannelHandlerContext context, object message)
        {
            while (true)
            {
                if (_isWebSocket)
                {
                    IByteBuffer buffer;
                    _lastReadBuffer?.ResetReaderIndex();
                    if (_lastReadBuffer != null && _lastReadBuffer.ReadableBytes != 0)
                    {
                        buffer = ByteBufferUtil.DefaultAllocator.HeapBuffer(
                            _lastReadBuffer.ReadableBytes + ((IByteBuffer)message).ReadableBytes);
                        buffer.WriteBytes(_lastReadBuffer);
                        buffer.WriteBytes((IByteBuffer)message);
                        _lastReadBuffer = buffer;
                    }
                    else
                    {
                        buffer          = (IByteBuffer)message;
                        _lastReadBuffer = buffer;
                    }

                    if (buffer.ReadableBytes < 2)
                    {
                        return;
                    }

                    IByteBuffer bufferCopy = ByteBufferUtil.DefaultAllocator.HeapBuffer(buffer.Capacity);
                    buffer.ReadBytes(bufferCopy, 2);
                    if ((bufferCopy.GetByte(0) & 8) == 8)
                    {
                        //操作码位8表示断开连接
                        context.CloseAsync();

                        return;
                    }

                    byte[] maskKey = { 0, 0, 0, 0 };
                    bool   masked  = false;
                    byte   lenMark = bufferCopy.GetByte(1);
                    if (lenMark >= 128)
                    {
                        masked   = true;
                        lenMark -= 128;
                    }

                    int offset = 0;
                    int len    = 0;
                    if (lenMark <= 125)
                    {
                        offset = 2;
                        len    = lenMark;
                    }
                    else if (lenMark == 126)
                    {
                        offset = 4;

                        if (buffer.ReadableBytes < 2)
                        {
                            return;
                        }

                        buffer.ReadBytes(bufferCopy, 2);
                        len = bufferCopy.GetUnsignedShort(2);
                    }
                    else if (lenMark == 127)
                    {
                        offset = 10;

                        if (buffer.ReadableBytes < 8)
                        {
                            return;
                        }

                        buffer.ReadBytes(bufferCopy, 8);
                        len = (int)bufferCopy.GetLong(2);
                    }

                    if (masked)
                    {
                        if (buffer.ReadableBytes < 4)
                        {
                            return;
                        }

                        buffer.ReadBytes(bufferCopy, 4);
                        for (int i = 0; i < 4; i++)
                        {
                            maskKey[i] = bufferCopy.GetByte(offset + i);
                        }

                        offset += 4;
                    }

                    if (buffer.ReadableBytes < len)
                    {
                        return;
                    }

                    buffer.ReadBytes(bufferCopy, len);
                    IByteBuffer output = ByteBufferUtil.DefaultAllocator.HeapBuffer(len);
                    for (int i = 0; i < len; i++)
                    {
                        output.WriteByte(bufferCopy.GetByte(offset + i) ^ maskKey[i % 4]);
                    }

                    _lastReadBuffer.MarkReaderIndex();
                    base.ChannelRead(context, output);

                    if (_lastReadBuffer.ReadableBytes <= 0)
                    {
                        return;
                    }

                    _lastReadBuffer = null;
                    message         = buffer;

                    continue;
                }

                try
                {
                    var         buffer     = (IByteBuffer)message;
                    IByteBuffer bufferCopy = buffer.Copy();
                    var         bytes      = new byte[bufferCopy.ReadableBytes];
                    bufferCopy.ReadBytes(bytes);
                    string       data = Encoding.ASCII.GetString(bytes);
                    const string requestWebSocketMark = "Sec-WebSocket-Key:";
                    int          index = data.IndexOf(requestWebSocketMark, StringComparison.Ordinal);
                    if (index < 0)
                    {
                        throw new Exception();
                    }

                    data = data.Substring(index + requestWebSocketMark.Length + 1);
                    var key = new StringBuilder();
                    foreach (char t in data)
                    {
                        if (IsBase64Char(t))
                        {
                            key.Append(t);
                        }
                        else
                        {
                            break;
                        }
                    }

                    key.Append("258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
                    SHA1 sha1 = new SHA1CryptoServiceProvider();
                    data = Convert.ToBase64String(sha1.ComputeHash(Encoding.UTF8.GetBytes(key.ToString())));
                    sha1.Dispose();
                    StringBuilder ret = new StringBuilder();
                    ret.Append("HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ");
                    ret.Append(data);
                    ret.Append("\r\nUpgrade: websocket\r\n\r\n");
                    IByteBuffer output = ByteBufferUtil.DefaultAllocator.HeapBuffer();
                    output.WriteBytes(Encoding.UTF8.GetBytes(ret.ToString()));
                    context.WriteAndFlushAsync(output);

                    _isWebSocket = true;
                }
                catch
                {
                    base.ChannelRead(context, message);
                }
                finally
                {
                    if (_isWebSocket)
                    {
                        context.Channel.Pipeline.Remove <LengthFieldBasedFrameDecoder>();
                        context.Channel.Pipeline.Remove <LengthFieldPrepender>();
                    }
                    else
                    {
                        context.Channel.Pipeline.Remove(this);
                    }
                }

                break;
            }
        }