示例#1
0
 protected override void btnEncrypt_Click(object sender, EventArgs e)
 {
     using (var saveKeyFile = new OpenFileDialog { Filter = Resources.resOPKey})
     {
         if (saveKeyFile.ShowDialog() != DialogResult.OK) return;
         using (var saveEncFile = new SaveFileDialog { Filter = Resources.resOPTxt })
         {
             if (saveEncFile.ShowDialog() != DialogResult.OK) return;
             DESEncryption = new DES(rtbInput.Text, tbKey.Text);
             DESEncryption.Encrypt(saveEncFile.FileName, saveKeyFile.FileName, rtbInput.Text);
         }
     }
 }
        private void Form1_Load(object sender, EventArgs e)
        {
            // Set From value
            if (currentUser == "Alice")
            {
                textFrom.SelectedIndex = 0;
                textTo.SelectedIndex   = 1;
            }
            else if (currentUser == "Bob")
            {
                textFrom.SelectedIndex = 1;
                textTo.SelectedIndex   = 0;
            }

            // Generate Alice's keys (two pairs of private and public - 4 keys total)
            RSACryptoServiceProvider AliceKey     = new RSACryptoServiceProvider();
            RSAParameters            AlicePublic  = AliceKey.ExportParameters(false);
            RSAParameters            AlicePrivate = AliceKey.ExportParameters(true);

            RSACryptoServiceProvider AliceKey2     = new RSACryptoServiceProvider();
            RSAParameters            AlicePublic2  = AliceKey2.ExportParameters(false);
            RSAParameters            AlicePrivate2 = AliceKey2.ExportParameters(true);

            Console.WriteLine("Alice Key  : " + AliceKey.ToXmlString(true));
            Console.WriteLine("Alice Key 2: " + AliceKey2.ToXmlString(true));

            // Generate Bob's symmetric key using DES
            // See public variable "des"

            // Use random generator to choose Alice's public key A or B
            // With chosen key (A or B) encrypt Bob's DES key
            byte[] encryptedDESKey      = { };
            byte[] encryptedDESDummyKey = { };
            var    keyChosen            = new Random().Next(0, 1);

            switch (keyChosen)
            {
            case 0:
                AliceKey.ImportParameters(AlicePublic);
                encryptedDESKey = AliceKey.Encrypt(des.Key, false);
                AliceKey2.ImportParameters(AlicePublic2);
                encryptedDESDummyKey = AliceKey2.Encrypt(DES.Create().Key, false);
                break;

            case 1:
                AliceKey2.ImportParameters(AlicePublic2);
                encryptedDESKey = AliceKey2.Encrypt(des.Key, false);
                AliceKey.ImportParameters(AlicePublic);
                encryptedDESDummyKey = AliceKey.Encrypt(DES.Create().Key, false);
                break;
            }
            Console.WriteLine("Encrypted DES Key: " + Convert.ToBase64String(encryptedDESKey));


            // Decrypt Bob's encrypted DES key with Alice's public keys A and B - two separate messages
            // *** Encrypted data MUST be decrypted with the matching private key - otherwise, error is thrown.
            //     Instead of decrypting one encrypted DES key with both private keys, there will be the original
            //     encrypted DES key and a dummy encrypted DES key.
            switch (keyChosen)
            {
            case 0:
                AliceKey.ImportParameters(AlicePrivate);
                decryptedDESKey1 = AliceKey.Decrypt(encryptedDESKey, false);
                AliceKey2.ImportParameters(AlicePrivate2);
                decryptedDESKey2 = AliceKey2.Decrypt(encryptedDESDummyKey, false);
                break;

            case 1:
                AliceKey2.ImportParameters(AlicePrivate2);
                decryptedDESKey1 = AliceKey2.Decrypt(encryptedDESKey, false);
                AliceKey.ImportParameters(AlicePrivate);
                decryptedDESKey2 = AliceKey.Decrypt(encryptedDESDummyKey, false);
                break;
            }
            Console.WriteLine("Decrypted Key 1: " + Convert.ToBase64String(decryptedDESKey1));
            Console.WriteLine("Decrypted Key 2: " + Convert.ToBase64String(decryptedDESKey2));
            Console.WriteLine("Writing to File:");



            // With the decrypted keys from previous step, encrypt both the real and bogus messages with DES keys
            Console.WriteLine("True DES Key: " + Convert.ToBase64String(des.Key));
            //Save DES key to Keys.txt
            string dir  = Directory.GetParent(Directory.GetParent(Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory)).FullName).FullName + "\\Rec";
            string path = dir + @"\Keys.txt";

            System.IO.StreamWriter sw = new System.IO.StreamWriter(path);
            //StreamWriter sw = new StreamWriter("Test.txt");
            sw.WriteLine(Convert.ToBase64String(des.Key));
            sw.Close();

            // Email bob with encrypted messages
            // See below

            // Clear Alice's keys
            AliceKey.Clear();
            AliceKey2.Clear();
        }
示例#3
0
 public clsDES(string key)
 {
     this.mydes = new DESCryptoServiceProvider();
     this.Key   = key;
     this.IV    = "{[(<'*((*#$&@!Uptime*~CMSWrite~*emitpU!@&$#*))*'>)]}";
 }
示例#4
0
        /// <summary>
        /// 保存(新增、修改)
        /// </summary>
        /// <returns></returns>
        public ActionResult Save()
        {
            string AccountID = Request.Form["AccountID"]; //账套
            string UserCode  = Request.Form["UserCode"];  //用户编号
            string UserName  = Request.Form["UserName"];  //用户名
            string Pwd       = Request.Form["Pwd"];       //密码

            if (!string.IsNullOrWhiteSpace(Pwd))
            {
                DES des = new DES();
                Pwd = des.Encrypt(Pwd);
            }
            string   Employee   = Request.Form["Employee"];                      //员工编号
            string   Position   = Request.Form["Position"];                      //岗位
            string   Department = Request.Form["Department"];                    //部门
            string   Phone      = Request.Form["Phone"];                         //电话
            DateTime BeginDate  = Convert.ToDateTime(Request.Form["BeginDate"]); //生效日期
            DateTime EndDate    = Convert.ToDateTime(Request.Form["EndDate"]);   //失效日期
            string   IsAdmin    = Request.Form["IsAdmin"];                       //管理员
            string   IsEnable   = Request.Form["IsEnable"];                      //生效

            string actionType = Request.Form["actiontype"];                      //新增或者修改状态

            UserInfo userInfo = new UserInfo();

            userInfo.AccountID  = AccountID;
            userInfo.UserCode   = UserCode;
            userInfo.UserName   = UserName;
            userInfo.Pwd        = Pwd;
            userInfo.Employee   = Employee;
            userInfo.Phone      = Phone;
            userInfo.Department = Department;
            userInfo.Position   = Position;
            userInfo.BeginDate  = BeginDate;
            userInfo.EndDate    = EndDate;
            userInfo.IsAdmin    = Convert.ToInt32(IsAdmin);
            userInfo.IsEnable   = Convert.ToInt32(IsEnable);

            bool   sucesss = false;
            string message = "";

            if (actionType == "add")
            {
                if (UserInfoBLL.CheckObjIsExist(userInfo))
                {
                    sucesss = false;
                    message = "该用户已经存在,不能重复录入!";
                }
                else
                {
                    if (UserInfoBLL.Add(userInfo))
                    {
                        sucesss = true;
                    }
                }
            }
            else
            {
                int KeyID = Convert.ToInt32(Request.Form["KeyID"]);//主键
                userInfo.KeyID = KeyID;
                if (UserInfoBLL.Update(userInfo))
                {
                    sucesss = true;
                }
            }

            return(Content(new JsonMessage {
                Success = sucesss, Message = message
            }.ToString()));
        }
示例#5
0
 /// <summary>
 /// 解码Uid
 /// </summary>
 /// <param name="encodeUid"></param>
 /// <returns></returns>
 private string DecodeUid(string encodeUid)
 {
     return(DES.Decode(encodeUid.Replace(' ', '+'), config.Passwordkey));
 }
示例#6
0
        public void ProcessRequest(HttpContext context)
        {
            StringBuilder log        = new StringBuilder();
            string        screenName = "";

            try
            {
                string query = "";

                UriBuilder urlBuilder = new UriBuilder("https://api.twitter.com/" + context.Server.UrlDecode(context.Request.QueryString["query"]));
                // Adds query strings to the url.
                // some headers may not be copied because they can't be used with clients other than twitter
                foreach (var queryString in context.Request.QueryString.AllKeys)
                {
                    switch (queryString)
                    {
                    case "u":
                    case "p":
                    case "query":
                    case "earned":
                    case "pc":
                        break;

                    default:
                        query += string.Format("&{0}={1}", queryString, context.Request.QueryString[queryString]);
                        break;
                    }
                }
                if (query.Length > 1)
                {
                    query = query.Substring(1);
                }
                urlBuilder.Query = query;
                log.AppendLine(query);
                log.AppendLine("URL: " + urlBuilder.Uri.ToString());
                OAuthTokens tokens = new OAuthTokens();
                tokens.ConsumerKey    = ConfigurationManager.AppSettings["TwitterConsumerKey"];
                tokens.ConsumerSecret = ConfigurationManager.AppSettings["TwitterConsumerSecret"];

                JToken accessToken;
                String userFileName = context.Server.MapPath("/App_Data/Users/" + context.Request.QueryString["u"] + "." + context.Request.QueryString["p"]);
                if (File.Exists(userFileName))
                {
                    using (StreamReader str = new StreamReader(userFileName))
                    {
                        accessToken = JObject.Parse(str.ReadToEnd());
                        ;
                    }
                    tokens.AccessToken       = (string)accessToken.SelectToken("AccessToken");
                    tokens.AccessTokenSecret = (string)accessToken.SelectToken("AccessSecret");
                    screenName = (string)accessToken.SelectToken("ScreenName");
                    log.AppendLine("User FOUND!");
                }
                else
                {
                    log.AppendLine("User NOT FOUND");
                    context.Response.StatusCode = 404;
                    return;
                }
                //check if the request is xAuth, if it is, simulates the xAuth result for fooling Twitter for iPhone.
                if (context.Request.QueryString["query"].Contains("oauth/access_token"))
                {
                    string xAuthResponse = string.Format("oauth_token={0}&oauth_token_secret={1}&user_id={2}&screen_name={3}&x_auth_expires=0",
                                                         (string)accessToken.SelectToken("AccessToken"),
                                                         (string)accessToken.SelectToken("AccessSecret"),
                                                         (string)accessToken.SelectToken("UserId"),
                                                         (string)accessToken.SelectToken("ScreenName"));
                    context.Response.Write(xAuthResponse);
                    screenName = (string)accessToken.SelectToken("ScreenName");
                    return;
                }

                HTTPVerb verb = HTTPVerb.GET;
                switch (context.Request.HttpMethod)
                {
                case "GET":
                    verb = HTTPVerb.GET;
                    break;

                case "POST":
                    verb = HTTPVerb.POST;
                    break;

                case "DELETE":
                    verb = HTTPVerb.DELETE;
                    break;
                }
                if (context.Request.Headers["Authorization"] == null)
                {
                    tokens = null;
                    log.AppendLine("Request NOT authenticated");
                }
                WebRequestBuilder webreq = new WebRequestBuilder(urlBuilder.Uri, verb, tokens);
                webreq.Multipart = (context.Request.ContentType.Contains("multipart"));
                if (verb != HTTPVerb.GET)
                {
                    // adds body parameters to request
                    foreach (var key in context.Request.Form.AllKeys)
                    {
                        webreq.Parameters.Add(key, context.Request.Form[key]);
                    }
                    foreach (var fileKey in context.Request.Files.AllKeys)
                    {
                        webreq.Parameters.Add(fileKey, context.Request.Form[fileKey]);
                    }
                }
                ServicePointManager.Expect100Continue = false;
                HttpWebRequest req = webreq.PrepareRequest();
                try
                {
                    HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                    log.AppendLine("get Response");
                    StreamReader strReader = new StreamReader(resp.GetResponseStream());
                    String       response  = strReader.ReadToEnd();
                    if (ConfigurationManager.AppSettings["debugMode"] == "true")
                    {
                        log.AppendLine(response);
                    }
                    // replaces images url to use TwiX to load them
                    response = Regex.Replace(response, @"(((http:\\/\\/www)|(http:\\/\\/)|(https:\\/\\/www)|(https:\\/\\/)|(www))[-a-zA-Z0-9@:%_\\\+.~#?&//=]+)\.(jpg|jpeg|gif|png|bmp|tiff|tga|svg)", delegate(Match match)
                    {
                        string v = match.ToString();
                        return(ConfigurationManager.AppSettings["baseUrl"] + "image/" + shFunctions.encryptBase64Url(DES.Encrypt(v.Replace(@"\/", "/").Replace("_normal", ""), shFunctions.key) + ".jpg"));
                    });

                    strReader.Close();
                    context.Response.ClearContent();
                    context.Response.Write(response);
                }
                catch (WebException webex)
                {
                    if (webex.Status == WebExceptionStatus.ProtocolError)
                    {
                        context.Response.StatusCode = (int)((HttpWebResponse)webex.Response).StatusCode;
                    }
                    log.AppendLine("ERROR: " + webex.Message);
                    return;
                }
            }
            catch (Exception ee) {
                log.AppendLine("Error: " + ee.Message);
                log.AppendLine("stack: " + ee.StackTrace);
            }

            if (ConfigurationManager.AppSettings["log"] == "true")
            {
                writeLogToFile(log.ToString(), screenName, context.Request.HttpMethod, context);
            }
            //throw new Exception(context.Request.QueryString.ToString());
        }
示例#7
0
        private byte[] EncryptDecrypt(EnumCrypt typeCrypt, byte[] inputBytes, bool encrpyt)
        {
            //--------------------------
            /*Encoder tipo DES*/
            //DES.Create();
            //--------------------------
            /*Encoder tipo RC2*/
            //RC2.Create();
            //--------------------------
            /*Encoder tipo Rijndael*/
            //Rijndael.Create();
            //--------------------------
            /*Encoder tipo Triple-DES*/
            //TripleDES.Create();
            //--------------------------
            SymmetricAlgorithm SA;

            switch (typeCrypt)
            {
            case EnumCrypt.DES:
                SA = DES.Create();
                break;

            case EnumCrypt.RC2:
                SA = RC2.Create();
                break;

            case EnumCrypt.Rijndael:
                SA = Rijndael.Create();
                break;

            case EnumCrypt.TripleDES:
                SA = TripleDES.Create();
                break;

            default:
                throw new NotImplementedException($"Cryptation not implemented [{typeCrypt}].");
            }

            //--------------------------
            SA.Key = MKEY;
            SA.IV  = MIV;
            //Transformação correta baseado no opção so usuario
            var transform = encrpyt ? SA.CreateEncryptor() : SA.CreateDecryptor();
            //Memory stream para saida
            var memStream = new MemoryStream();

            //Array de bytes para saida
            byte[] output;
            //Configura o encriptador e escreve no MemoryStream a saida
            var cryptStream = new CryptoStream(memStream, transform, CryptoStreamMode.Write);

            //Escreve as informações no mecanismo do encriptador
            cryptStream.Write(inputBytes, 0, inputBytes.Length);
            //Finaliza e escreve todas as informações necessárias na memoria
            cryptStream.FlushFinalBlock();
            //Resgata o array de bytes
            output = memStream.ToArray();
            //Finaliza o mecanismo de criptografia e fecha o canal de comunicação de memoria
            cryptStream.Close();
            return(output);
        }
示例#8
0
 public DESEncrypt()
 {
     des = new DESCryptoServiceProvider();
 }
        public InsecureEncryptionAlgorithm()
        {
            // Rule will raise an issue for both S2278 and S5547 as they are activated by default in unit tests

            // Noncompliant@+1 {{Use the recommended AES (Advanced Encryption Standard) instead.}}
            using (var tripleDES = new MyTripleDESCryptoServiceProvider()) // Noncompliant    {{Use a strong cipher algorithm.}}
//                                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
            {
                //...
            }
            // Noncompliant@+1
            using (var des = new DESCryptoServiceProvider()) // Noncompliant
            {
                //...
            }
            // Noncompliant@+1
            using (TripleDES TripleDESalg = TripleDES.Create()) // Noncompliant
//                                          ^^^^^^^^^^^^^^^^^^
            {
            }
            // Noncompliant@+1
            using (var des = DES.Create("fgdsgsdfgsd")) // Noncompliant
            {
            }

            using (var aes = new AesCryptoServiceProvider())
            {
                //...
            }
            // Noncompliant@+1
            using (var rc21 = new RC2CryptoServiceProvider()) // Noncompliant
            {
            }

            // Noncompliant@+1
            using (var rc22 = RC2.Create()) // Noncompliant
            {
            }
            // Noncompliant@+1
            SymmetricAlgorithm des1 = SymmetricAlgorithm.Create("DES"); // Noncompliant

            // Noncompliant@+1
            des1 = SymmetricAlgorithm.Create("TripleDES"); // Noncompliant

            // Noncompliant@+1
            des1 = SymmetricAlgorithm.Create("3DES"); // Noncompliant

            // Noncompliant@+1
            var rc2 = SymmetricAlgorithm.Create("RC2"); // Noncompliant

            // Noncompliant@+1
            var crypto = CryptoConfig.CreateFromName("DES"); // Noncompliant

            // Noncompliant@+1
            var aesFastEngine = new AesFastEngine(); // Noncompliant
//                                  ^^^^^^^^^^^^^

            // Noncompliant@+1
            var blockCipher1 = new GcmBlockCipher(new AesFastEngine()); // Noncompliant

            var blockCipher2 = new GcmBlockCipher(new AesEngine());     // Compliant

            var oid = CryptoConfig.MapNameToOID("DES");                 // Compliant

            var unknown = new Unknown();                                // Compliant // Error [CS0246]
        }
示例#10
0
        public static void GenerateDESKey(out string key)
        {
            DESCryptoServiceProvider des = (DESCryptoServiceProvider)DES.Create();

            key = ASCIIEncoding.ASCII.GetString(des.Key);
        }
示例#11
0
 public LBDESEncrypt()
 {
     des = new DESCryptoServiceProvider();
 }
示例#12
0
    protected void Page_Load(object sender, EventArgs e)
    {
        //
        string showreport = Request.QueryString["showreport"] == null ? "0" : Request.QueryString["showreport"].ToString();

        if (showreport == "1")
        {
            try
            {
                this.Button1.Visible = false;
                string PARM = Request.QueryString["PARM"] == null ? "0" : Request.QueryString["PARM"].ToString();
                if (PARM != "0")
                {
                    string data_index = GlobeAtt.DATA_INDEX;
                    string strdata    = data_index + DES.DESDecrypt(PARM, DES.Key);
                    strdata     = strdata.Trim();
                    report_file = BaseFun.getStrByIndex(strdata, data_index + "REPORT_FILE|", data_index);
                    report_sql  = BaseFun.getStrByIndex(strdata, data_index + "REPORT_SQL|", data_index);
                    report_parm = BaseFun.getStrByIndex(strdata, data_index + "REPORT_PARM|", data_index);
                }
                else
                {
                    report_file = Session["REPORT_FILE"].ToString();
                    report_sql  = Session["REPORT_SQL"].ToString();
                    report_parm = Session["REPORT_PARM"].ToString();
                }
                // Response.Write(report_sql);
                ReportDocument rd = new ReportDocument();

                string file_ = Server.MapPath("../Report/" + report_file);

                try
                {
                    rd.Load(file_);
                    // cs.ReportDocument.Load(rd.FileName);
                    PageMargins pm = new PageMargins();

                    rd.PrintOptions.ApplyPageMargins(pm);
                }
                catch (Exception ex)
                {
                    Response.Write(report_file + ex.Message);
                    return;
                }
                if (report_sql.Length > 10)
                {
                    Oracle    db        = new Oracle();
                    DataTable dt_report = new DataTable();
                    db.ExcuteDataTable(dt_report, report_sql, CommandType.Text);

                    rd.SetDataSource(dt_report);
                    CrystalReportViewer1.ReportSource = rd;
                    CrystalReportViewer1.DataBind();
                }
                else
                {
                    Oracle         db = new Oracle();
                    ConnectionInfo ConnectionInfo1 = new ConnectionInfo();
                    ConnectionInfo1 = rd.Database.Tables[0].LogOnInfo.ConnectionInfo;
                    rd.SetDatabaseLogon(db.user_id, db.password);
                    ConnectionInfo1.DatabaseName = "";
                    ConnectionInfo1.UserID       = db.user_id;
                    ConnectionInfo1.Password     = db.password;
                    ConnectionInfo1.ServerName   = db.data_source;
                    SetDBLogonForReport(ConnectionInfo1, rd);
                    if (rd.HasSavedData == true)
                    {
                        rd.Refresh();
                    }
                    string[]        parm        = report_parm.Split(',');
                    ParameterFields ParamFields = new ParameterFields();
                    for (int i = 0; i < rd.ParameterFields.Count; i++)
                    {
                        ParameterDiscreteValue ParamDiscreteValue = new ParameterDiscreteValue();
                        if (parm[i] != "[]")
                        {
                            ParamDiscreteValue.Value = parm[i];
                            if (i < parm.Length && parm[i] != "")
                            {
                                rd.ParameterFields[i].CurrentValues.Add(ParamDiscreteValue);
                            }
                        }
                    }



                    CrystalReportViewer1.ReportSource = rd;
                    CrystalReportViewer1.DataBind();
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);

                return;
            }
        }
        else
        {
            //   string   a002_key = Request.QueryString["A002KEY"] == null ? "-1" : Request.QueryString["A002KEY"].ToString();
            //   string A00201KEY = Request.QueryString["A00201KEY"] == null ? "-1" : Request.QueryString["A00201KEY"].ToString();
            string report_conditon = Request.QueryString["reportconditon"] == null ? "1" : Request.QueryString["reportconditon"].ToString();
            string key             = Request.QueryString["JUMP_KEY"] == null ? "-1" : Request.QueryString["JUMP_KEY"].ToString();
            string a002_key        = Request.QueryString["JUMP_A002_KEY"] == null ? "-1" : Request.QueryString["JUMP_A002_KEY"].ToString();
            string IF_JUMP         = Request.QueryString["IF_JUMP"] == null ? "1" : Request.QueryString["IF_JUMP"].ToString();

            //   dt_a002 = Fun.getDtBySql("Select t.* from A002 t where menu_id='" + a002_key +"'");
            dt_main = Fun.getDtBySql("Select t.*,pkg_a.getmenuname(t.a002_key,'" + GlobeAtt.A007_KEY + "') as show_name  from A002_v01 t where a002_key='" + a002_key + "'");

            try
            {
                report_file = dt_main.Rows[0]["datawindow_name"].ToString();
            }
            catch (Exception ex)
            {
                Response.Write("report_file" + ex.Message);

                return;
            }

            try
            {
                menu_name = dt_main.Rows[0]["show_name"].ToString();
            }
            catch (Exception ex)
            {
                menu_name = "";
                Response.Write("title" + ex.Message);
            }


            try
            {
                if (report_conditon == "1")
                {
                    report_sql = dt_main.Rows[0]["query_table"].ToString();
                    if (report_sql.Length < 20)
                    {
                        report_sql = "Select t.* from " + report_sql + "t where 1=1 ";
                    }
                    Session["REPORT_SQL"] = report_sql;
                }
                else
                {
                    report_sql = Session["REPORT_SQL"].ToString();
                }
            }
            catch (Exception ex)
            {
                Response.Write("report_sql" + ex.Message);
                return;
            }

            string file_ = Server.MapPath("../report/" + report_file);
            try
            {
                rd.Load(file_);

                ConnectionInfo ConnectionInfo1 = new ConnectionInfo();
                ConnectionInfo1 = rd.Database.Tables[0].LogOnInfo.ConnectionInfo;
                ConnectionInfo1.DatabaseName = "";
                ConnectionInfo1.UserID       = Fun.db.user_id;
                ConnectionInfo1.Password     = Fun.db.password;
                ConnectionInfo1.ServerName   = Fun.db.data_source;
                SetDBLogonForReport(ConnectionInfo1, rd);
                if (rd.HasSavedData == true)
                {
                    rd.Refresh();
                }
                CrystalReportViewer1.ReportSource = rd;
                CrystalReportViewer1.DataBind();
            }
            catch (Exception ex)
            {
                Response.Write(report_file + ex.Message);
                return;
            }
            t_con.Visible   = false;
            Button1.Visible = false;


            //else
            //{

            //    cs = (CrystalReportSource) CrystalReportViewer1.ReportSource;
            //}

            /*
             *
             * if (report_conditon == "1")
             * {
             *  set_condition();
             * }
             * else
             * {
             *  //  Response.Write(report_sql);
             *  t_con.Visible = false;
             *  Button1.Visible = false;
             *  //cs.ReportDocument.SetDatabaseLogon(Fun.db.user_id, Fun.db.password, Fun.db.data_source, Fun.db.data_source);
             *  //cs.ReportDocument.Refresh();
             * // CrystalReportViewer1.ReportSource = cs;
             *  //CrystalReportViewer1.DataBind();
             * //  cs.DataBind();
             *  return;
             *  Oracle db = new Oracle();
             *  DataTable dt_report = new DataTable();
             *  db.ExcuteDataTable(dt_report, report_sql, CommandType.Text);
             *
             *  cs.ReportDocument.SetDataSource(dt_report);
             *  cs.DataBind();
             *
             *  CrystalReportViewer1.ReportSource = cs;
             *  CrystalReportViewer1.DataBind();
             *
             *
             * }
             *
             *
             *
             * }
             *
             * // CryReport.get_report_condition(CrystalReportViewer1, Server.MapPath("../report/" + report_file), t_con);
             */
        }
    }
示例#13
0
        private void ClReg()
        {
            Action action = () =>
            {
                if ((tbLogin.Text.Length == 0) | (tbLogin.Text.IndexOf('@') == -1) | (tbLogin.Text.IndexOf('.') == -1) | (tbLogin.Text.IndexOf('@') > tbLogin.Text.IndexOf('.')))
                {
                    tbLogin.BackColor = Color.Red;
                }
                else
                {
                    tbLogin.BackColor = Color.White;
                    ArrayList Checkarray = new ArrayList();
                    DES       des        = DES.Create();
                    byte[]    key        = Convert.FromBase64String("ybqAS+sVBLY=");
                    byte[]    IV         = Convert.FromBase64String("1mbClpyz5bU=");
                    des.Key = key;
                    des.IV  = IV;
                    byte[] login = Crypt_Class.SymmetricEncrypt(tbLogin.Text, des);
                    Checkarray.Add("\'" + Convert.ToBase64String(login) + "\'");
                    Function_class UQCheck = new Function_class("Client_Face_Adress_UQ_Check", Function_class.Function_Result.scalar, Checkarray);
                    if ((UQCheck.Regtable.Rows[0][0].ToString() == "False") & (tbLogin.Text == Login))
                    {
                        tbLogin.BackColor = Color.Red;
                    }
                    else
                    {
                        tbLogin.BackColor = Color.White;
                        if ((tbPassword.Text.Length < 6) | (tbPassword.Text.IndexOfAny(numbers) == -1) | (tbPassword.Text.IndexOfAny(ruLetters) != -1) | (tbPassword.Text != tbConfirm.Text))
                        {
                            tbPassword.BackColor = Color.Red;
                            if ((tbPassword.Text == tbConfirm.Text) & ((tbPassword.Text == Password) | (tbPassword.Text != "")))
                            {
                                tbPassword.BackColor = Color.White;
                                ArrayList array = new ArrayList();
                                array.Add(Program.intID);
                                Table_Class tableClient = new Table_Class(String.Format("SELECT [Client_Face_Name],[Client_Face_Firstname],[Client_Face_Patronymic],[Client_ID] FROM [dbo].[Client_Face] WHERE [ID_Client_Face] = {0}", Program.intID));
                                array.Add(tableClient.table.Rows[0][0].ToString());
                                array.Add(tableClient.table.Rows[0][1].ToString());
                                array.Add(tableClient.table.Rows[0][2].ToString());
                                DES    indes = DES.Create();
                                byte[] inkey = Convert.FromBase64String("ybqAS+sVBLY=");
                                byte[] inIV  = Convert.FromBase64String("1mbClpyz5bU=");
                                indes.Key = inkey;
                                indes.IV  = inIV;
                                byte[] inlogin  = Crypt_Class.SymmetricEncrypt(tbLogin.Text, indes);
                                byte[] inpasswd = Crypt_Class.SymmetricEncrypt(Password, indes);
                                array.Add(Convert.ToBase64String(inlogin));
                                array.Add(Convert.ToBase64String(inpasswd));
                                array.Add(tableClient.table.Rows[0][3].ToString());
                                array.Add("0");
                                Procedure_Class procedure = new Procedure_Class();
                                procedure.procedure_Execution("Client_Face_Update", array);
                                ClMainLoad();
                            }
                        }
                        else
                        {
                            tbPassword.BackColor = Color.White;
                            ArrayList array = new ArrayList();
                            array.Add(Program.intID);
                            Table_Class tableClient = new Table_Class(String.Format("SELECT [Client_Face_Name],[Client_Face_Firstname],[Client_Face_Patronymic],[Client_ID] FROM [dbo].[Client_Face] WHERE [ID_Client_Face] = {0}", Program.intID));
                            array.Add(tableClient.table.Rows[0][0].ToString());
                            array.Add(tableClient.table.Rows[0][1].ToString());
                            array.Add(tableClient.table.Rows[0][2].ToString());
                            DES    indes = DES.Create();
                            byte[] inkey = Convert.FromBase64String("ybqAS+sVBLY=");
                            byte[] inIV  = Convert.FromBase64String("1mbClpyz5bU=");
                            indes.Key = inkey;
                            indes.IV  = inIV;
                            byte[] inlogin  = Crypt_Class.SymmetricEncrypt(tbLogin.Text, indes);
                            byte[] inpasswd = Crypt_Class.SymmetricEncrypt(tbPassword.Text, indes);
                            array.Add(Convert.ToBase64String(inlogin));
                            array.Add(Convert.ToBase64String(inpasswd));
                            array.Add(tableClient.table.Rows[0][3].ToString());
                            array.Add("0");
                            Procedure_Class procedure = new Procedure_Class();
                            procedure.procedure_Execution("Client_Face_Update", array);
                            ClMainLoad();
                        }
                    }
                }
            };

            Invoke(action);
        }
示例#14
0
        protected virtual void Page_Load(object sender, EventArgs e)
        {
            if (this.userid > 0)
            {
                if (CheckUserPopedoms("X") || CheckUserPopedoms("4-1"))
                {
                    ucode   = DES.Encode(this.userinfo.uName + "|" + UsersUtils.GetCookiePassword(config.Passwordkey), config.Passwordkey);
                    Act     = HTTPRequest.GetString("Act");
                    StaffID = Utils.StrToInt(HTTPRequest.GetString("sid"), 0);
                    format  = HTTPRequest.GetString("format");
                    if (Act == "Edit")
                    {
                        si = tbStaffInfo.GetStaffInfoModel(StaffID);

                        sd = tbStaffInfo.GetStaffDataInfoModelByStaffID(StaffID);

                        if (sd != null)
                        {
                            sd.sBirthDay     = sd.sBirthDay != null?sd.sBirthDay:"";
                            sd.sPolitical    = sd.sPolitical != null ? sd.sPolitical : "";
                            sd.sBirthplace   = sd.sBirthplace != null ? sd.sBirthplace : "";
                            sd.sHometown     = sd.sHometown != null ? sd.sHometown : "";
                            sd.sEducation    = sd.sEducation != null ? sd.sEducation : "";
                            sd.sProfessional = sd.sProfessional != null ? sd.sProfessional : "";
                            sd.sHealth       = sd.sHealth != null ? sd.sHealth : "";

                            sd.sSpecialty      = sd.sSpecialty != null ? sd.sSpecialty : "";
                            sd.sHobbies        = sd.sHobbies != null ? sd.sHobbies : "";
                            sd.sContactAddress = sd.sContactAddress != null ? sd.sContactAddress : "";
                            sd.sPhotos         = sd.sPhotos != null ? sd.sPhotos : "";

                            sd.sCanBeDate = sd.sCanBeDate != null ? sd.sCanBeDate : "";
                        }

                        sad = tbStaffInfo.GetStaffAnalysisDataInfoModelByStaffID(StaffID);
                        if (sad != null)
                        {
                            sad.aEvaluationMSG = sad.aEvaluationMSG != null ? sad.aEvaluationMSG : "";
                        }
                    }
                    //修改状体
                    if (Act == "State")
                    {
                        si    = tbStaffInfo.GetStaffInfoModel(StaffID);
                        tJson = ",\"StaffID\":" + StaffID + "";
                        if (si != null)
                        {
                            si.sState = (si.sState == 0 ? 1 : 0);
                            tbStaffInfo.UpdateStaffInfo(si);
                            Logs.AddEventLog(this.userid, "修改人员状态." + si.sName);
                            tJson += ",\"StaffState\":" + si.sState;
                            AddMsgLine("修改成功!");
                        }
                        else
                        {
                            AddErrLine("修改失败,对象不存在!");
                        }
                    }
                    if (ispost)
                    {
                        sName              = Utils.ChkSQL(HTTPRequest.GetString("sName"));
                        sSex               = Utils.ChkSQL(HTTPRequest.GetString("sSex"));
                        sTel               = Utils.ChkSQL(HTTPRequest.GetString("sTel"));
                        sCarID             = Utils.ChkSQL(HTTPRequest.GetString("sCarID"));
                        sType              = Utils.StrToInt(HTTPRequest.GetString("sType"), 0);
                        sEmail             = Utils.ChkSQL(HTTPRequest.GetString("sEmail"));
                        DepartmentsClassID = Utils.StrToInt(HTTPRequest.GetString("DepartmentsClassID"), 0);
                        sState             = HTTPRequest.GetString("sState").Trim() != "" ? Utils.StrToInt(HTTPRequest.GetString("sState"), 0) : 1;

                        si.sSex               = sSex;
                        si.sTel               = sTel;
                        si.sCarID             = sCarID;
                        si.sType              = sType;
                        si.sState             = sState;
                        si.sEmail             = sEmail;
                        si.DepartmentsClassID = DepartmentsClassID;

                        sd = sd != null ? sd : new StaffDataInfo();

                        sd.sBirthDay       = Utils.ChkSQL(HTTPRequest.GetString("sBirthDay"));
                        sd.sPolitical      = Utils.ChkSQL(HTTPRequest.GetString("sPolitical"));
                        sd.sBirthplace     = Utils.ChkSQL(HTTPRequest.GetString("sBirthplace"));
                        sd.sHometown       = Utils.ChkSQL(HTTPRequest.GetString("sHometown"));
                        sd.sEducation      = Utils.ChkSQL(HTTPRequest.GetString("sEducation"));
                        sd.sProfessional   = Utils.ChkSQL(HTTPRequest.GetString("sProfessional"));
                        sd.sHealth         = Utils.ChkSQL(HTTPRequest.GetString("sHealth"));
                        sd.sHeight         = HTTPRequest.GetInt("sHeight", 0);
                        sd.sWeight         = HTTPRequest.GetInt("sWeight", 0);
                        sd.sSpecialty      = Utils.ChkSQL(HTTPRequest.GetString("sSpecialty"));
                        sd.sHobbies        = Utils.ChkSQL(HTTPRequest.GetString("sHobbies"));
                        sd.sContactAddress = Utils.ChkSQL(HTTPRequest.GetString("sContactAddress"));
                        sd.sPhotos         = Utils.ChkSQL(HTTPRequest.GetString("sPhotos"));
                        sd.sEmployment     = HTTPRequest.GetInt("sEmployment", 0);
                        sd.sCanBeDate      = Utils.ChkSQL(HTTPRequest.GetString("sCanBeDate"));
                        sd.sTreatment      = HTTPRequest.GetInt("sTreatment", 0);

                        sad = sad != null ? sad : new StaffAnalysisDataInfo();

                        sad.aWearing       = HTTPRequest.GetInt("aWearing", 0);
                        sad.aEducation     = HTTPRequest.GetInt("aEducation", 0);
                        sad.aWork          = HTTPRequest.GetInt("aWork", 0);
                        sad.aCommunication = HTTPRequest.GetInt("aCommunication", 0);
                        sad.aConfidence    = HTTPRequest.GetInt("aConfidence", 0);
                        sad.aLeadership    = HTTPRequest.GetInt("aLeadership", 0);
                        sad.aJobstability  = HTTPRequest.GetInt("aJobstability", 0);
                        sad.aComputer      = HTTPRequest.GetInt("aComputer", 0);
                        sad.aEnglish       = HTTPRequest.GetInt("aEnglish", 0);
                        sad.aWritten       = HTTPRequest.GetInt("aWritten", 0);
                        sad.aEvaluation    = HTTPRequest.GetInt("aEvaluation", 0);
                        sad.aEvaluationMSG = Utils.ChkSQL(HTTPRequest.GetString("aEvaluationMSG"));
                        try
                        {
                            sad.aDateTime = Utils.IsDateString(HTTPRequest.GetString("aDateTime")) ? DateTime.Parse(HTTPRequest.GetString("aDateTime").Trim()) : DateTime.Now;
                        }
                        catch {
                            sad.aDateTime = DateTime.Now;
                        }

                        EduDataListJson    = HTTPRequest.GetString("EduDataListJson");
                        WorkDataListJson   = HTTPRequest.GetString("WorkDataListJson");
                        FamilyDataListJson = HTTPRequest.GetString("FamilyDataListJson");

                        if (Act == "Add")
                        {
                            if (!tbStaffInfo.ExistsStaffInfo(sName))
                            {
                                si.sName       = sName;
                                si.sAppendTime = sAppendTime;
                                StaffID        = tbStaffInfo.AddStaffInfo(si);
                                if (StaffID > 0)
                                {
                                    sd.StaffID = StaffID;

                                    tbStaffInfo.AddStaffDataInfo(sd);

                                    sad.StaffID     = StaffID;
                                    sad.aAppendTime = DateTime.Now;

                                    tbStaffInfo.AddStaffAnalysisDataInfo(sad);

                                    if (EduDataListJson.Trim() != "")
                                    {
                                        StaffEduDataJson EduDataJson = (StaffEduDataJson)JavaScriptConvert.DeserializeObject(EduDataListJson, typeof(StaffEduDataJson));

                                        tbStaffInfo.AddStaffEduDataInfoByJson(EduDataJson);
                                    }
                                    if (WorkDataListJson.Trim() != "")
                                    {
                                        StaffWorkDataJson WorkDataJson = (StaffWorkDataJson)JavaScriptConvert.DeserializeObject(WorkDataListJson, typeof(StaffWorkDataJson));

                                        tbStaffInfo.AddStaffWorkDataInfoByJson(WorkDataJson);
                                    }
                                    if (FamilyDataListJson.Trim() != "")
                                    {
                                        StaffFamilyDataJson FamilyDataJson = (StaffFamilyDataJson)JavaScriptConvert.DeserializeObject(FamilyDataListJson, typeof(StaffFamilyDataJson));

                                        tbStaffInfo.AddStaffFamilyDataInfoByJson(FamilyDataJson);
                                    }
                                    Logs.AddEventLog(this.userid, "新增人员." + si.sName);
                                    AddMsgLine("创建成功!");
                                    AddScript("window.setTimeout('window.parent.HidBox();',1000);");
                                }
                                else
                                {
                                    AddErrLine("创建失败!");
                                    AddScript("window.setTimeout('history.back(1);',1000);");
                                }
                            }
                            else
                            {
                                AddErrLine("人员:" + sName + ",已存在,请更换!");
                                AddScript("window.setTimeout('history.back(1);',3000);");
                            }
                        }
                        if (Act == "Edit")
                        {
                            bool nOK = false;
                            if (si.sName.Trim() != sName.Trim())
                            {
                                if (!tbStaffInfo.ExistsStaffInfo(sName.Trim()))
                                {
                                    nOK = true;
                                }
                                else
                                {
                                    nOK = false;
                                    AddErrLine("人员:" + sName + ",已存在,请更换!");
                                    AddScript("window.setTimeout('history.back(1);',3000);");
                                }
                            }
                            else
                            {
                                nOK = true;
                            }
                            if (nOK)
                            {
                                try
                                {
                                    si.sName = sName;

                                    tbStaffInfo.UpdateStaffInfo(si);

                                    if (sd.StaffID > 0)
                                    {
                                        tbStaffInfo.UpdateStaffDataInfo(sd);
                                    }
                                    else
                                    {
                                        sd.StaffID = StaffID;

                                        tbStaffInfo.AddStaffDataInfo(sd);
                                    }

                                    if (sad.StaffID > 0)
                                    {
                                        tbStaffInfo.UpdateStaffAnalysisDataInfo(sad);
                                    }
                                    else
                                    {
                                        sad.StaffID     = StaffID;
                                        sad.aAppendTime = DateTime.Now;

                                        tbStaffInfo.AddStaffAnalysisDataInfo(sad);
                                    }

                                    if (EduDataListJson.Trim() != "")
                                    {
                                        StaffEduDataJson EduDataJson = (StaffEduDataJson)JavaScriptConvert.DeserializeObject(EduDataListJson, typeof(StaffEduDataJson));

                                        tbStaffInfo.UpdateStaffEduDataInfoByJson(EduDataJson, StaffID);
                                    }
                                    if (WorkDataListJson.Trim() != "")
                                    {
                                        StaffWorkDataJson WorkDataJson = (StaffWorkDataJson)JavaScriptConvert.DeserializeObject(WorkDataListJson, typeof(StaffWorkDataJson));

                                        tbStaffInfo.UpdateStaffWorkDataInfoByJson(WorkDataJson, StaffID);
                                    }
                                    if (FamilyDataListJson.Trim() != "")
                                    {
                                        StaffFamilyDataJson FamilyDataJson = (StaffFamilyDataJson)JavaScriptConvert.DeserializeObject(FamilyDataListJson, typeof(StaffFamilyDataJson));

                                        tbStaffInfo.UpdateStaffFamilyDataInfoByJson(FamilyDataJson, StaffID);
                                    }

                                    Logs.AddEventLog(this.userid, "修改人员." + si.sName);
                                    AddMsgLine("修改成功!");
                                    AddScript("window.setTimeout('window.parent.HidBox();',1000);");
                                }
                                catch (Exception ex)
                                {
                                    AddErrLine("修改失败!<br/>" + ex);
                                    //AddScript("window.setTimeout('window.parent.HidBox();',1000);");
                                }
                            }
                        }
                        Caches.ReSet();
                    }
                    else
                    {
                        DepartmentsClass = Caches.GetDepartmentsClassInfoToHTML();
                        if (Act == "Add")
                        {
                            si.sName  = "";
                            si.sSex   = "男";
                            si.sState = 0;
                            si.sType  = 0;
                        }
                        if (Act == "Edit")
                        {
                            EduDataListJson    = "";
                            WorkDataListJson   = "";
                            FamilyDataListJson = "";

                            EduDataList         = tbStaffInfo.GetStaffEduDataInfoList(" StaffID=" + StaffID + " order by StaffEduDataID desc").Tables[0];
                            StaffWorkDataList   = tbStaffInfo.GetStaffWorkDataInfoList(" StaffID=" + StaffID + " order by StaffWorkDataID desc").Tables[0];
                            StaffFamilyDataList = tbStaffInfo.GetStaffFamilyDataInfoList(" StaffID=" + StaffID + " order by StaffFamilyDataID desc").Tables[0];
                            try {
                                foreach (DataRow dr in EduDataList.Rows)
                                {
                                    EduDataListJson += "{\"StaffEduDataID\":\"" + dr["StaffEduDataID"].ToString() + "\",\"StaffID\":\"" + dr["StaffID"].ToString() + "\",\"eDate\":\"" + dr["eDate"].ToString() + "\",\"eSchools\":\"" + dr["eSchools"].ToString().Replace("\"", "\\\"") + "\",\"eContent\":\"" + dr["eContent"].ToString().Replace("\"", "\\\"") + "\"},";
                                }
                                if (EduDataListJson.Trim() != "")
                                {
                                    EduDataListJson = EduDataListJson.Substring(0, EduDataListJson.Length - 1);
                                }
                                EduDataListJson = "{\"EduDataList\":[" + EduDataListJson + "]}";

                                foreach (DataRow dr in StaffWorkDataList.Rows)
                                {
                                    WorkDataListJson += "{\"StaffWorkDataID\":\"" + dr["StaffWorkDataID"].ToString() + "\",\"StaffID\":\"" + dr["StaffID"].ToString() + "\",\"wDate\":\"" + dr["wDate"].ToString() + "\",\"wEnterprise\":\"" + dr["wEnterprise"].ToString().Replace("\"", "\\\"") + "\",\"wTel\":\"" + dr["wTel"].ToString().Replace("\"", "\\\"") + "\",\"wJobs\":\"" + dr["wJobs"].ToString().Replace("\"", "\\\"") + "\",\"wIncome\":\"" + dr["wIncome"].ToString().Replace("\"", "\\\"") + "\"},";
                                }
                                if (WorkDataListJson.Trim() != "")
                                {
                                    WorkDataListJson = WorkDataListJson.Substring(0, WorkDataListJson.Length - 1);
                                }
                                WorkDataListJson = "{\"WorkDataList\":[" + WorkDataListJson + "]}";

                                foreach (DataRow dr in StaffFamilyDataList.Rows)
                                {
                                    FamilyDataListJson += "{\"StaffFamilyDataID\":\"" + dr["StaffFamilyDataID"].ToString() + "\",\"StaffID\":\"" + dr["StaffID"].ToString() + "\",\"fTitle\":\"" + dr["fTitle"].ToString() + "\",\"fName\":\"" + dr["fName"].ToString().Replace("\"", "\\\"") + "\",\"fAge\":\"" + dr["fAge"].ToString().Replace("\"", "\\\"") + "\",\"fEnterprise\":\"" + dr["fEnterprise"].ToString().Replace("\"", "\\\"") + "\",\"fWork\":\"" + dr["fWork"].ToString().Replace("\"", "\\\"") + "\",\"fAddress\":\"" + dr["fAddress"].ToString().Replace("\"", "\\\"") + "\",\"fTel\":\"" + dr["fTel"].ToString().Replace("\"", "\\\"") + "\"},";
                                }
                                if (FamilyDataListJson.Trim() != "")
                                {
                                    FamilyDataListJson = FamilyDataListJson.Substring(0, FamilyDataListJson.Length - 1);
                                }
                                FamilyDataListJson = "{\"FamilyDataList\":[" + FamilyDataListJson + "]}";
                            }
                            finally {
                                EduDataList         = null;
                                StaffWorkDataList   = null;
                                StaffFamilyDataList = null;
                            }
                        }

                        if (Act == "Del")
                        {
                            try
                            {
                                tbStaffInfo.DeleteStaffInfo(HTTPRequest.GetString("sid"));
                                Logs.AddEventLog(this.userid, "删除人员." + HTTPRequest.GetString("sid"));
                                AddMsgLine("删除成功!");
                                AddScript("window.setTimeout('window.parent.HidBox();',1000);");
                            }
                            catch (Exception ex)
                            {
                                AddErrLine("删除失败!<br/>" + ex);
                                AddScript("window.setTimeout('window.parent.HidBox();',1000);");
                            }
                        }
                    }
                }
                else
                {
                    AddErrLine("权限不足!");
                    AddScript("window.setTimeout('window.parent.HidBox();',1000);");
                }
            }
            else
            {
                AddErrLine("请先登录!");
                SetBackLink("login.aspx?referer=" + Utils.UrlEncode(Utils.GetUrlReferrer()));
                SetMetaRefresh(1, "login.aspx?referer=" + Utils.UrlEncode(Utils.GetUrlReferrer()));
            }
            if (format == "json")
            {
                Response.ClearContent();
                Response.Buffer          = true;
                Response.ExpiresAbsolute = System.DateTime.Now.AddYears(-1);
                Response.Expires         = 0;

                Response.Charset         = "utf-8";
                Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
                Response.ContentType     = "application/json";
                string Json_Str = "{\"results\": {\"msg\":\"" + this.msgbox_text + "\",\"state\":\"" + (!IsErr()).ToString() + "\"" + tJson + "}}";
                Response.Write(Json_Str);
                Response.End();
            }
        }
示例#15
0
        public int Call_Login(GameSession session, AuthRequest au)
        {
            if (session.IsAuthorized)
            {
                return((int)GameErrorCode.重复登录);
            }
            var    json      = JObject.Parse(DES.DesDecrypt(au.loginid, _config.DESKey));
            var    ucenterId = json.Value <long>("id");
            var    usercode  = json.Value <String>("usercode");
            var    bind      = json.Value <bool>("bind");
            Player player    = null;

            if (!_db.Players.Any(p => p.UserCenterId == ucenterId))
            {
                //创建角色信息
                player    = new Player();
                player.Id = $"S{session.Server.Id}P{ucenterId}";
                int numb = _db.Players.Count();
                player.NickName      = "No." + numb;
                player.UserCenterId  = ucenterId;
                player.UserCode      = usercode;
                player.Camp          = 1;
                player.Icon          = "touxiang6";
                player.Level         = 1;
                player.Version       = au.ver;
                player.VIP           = 0;
                player.LastVipUpTime = player.LastLvUpTime = player.LastLoginTime = player.CreateTime = DateTime.Now;
                player.IsBind        = false;
                player.IP            = (session.Socket.RemoteEndPoint as IPEndPoint)?.Address.ToString();
                player.Wallet        = new Wallet()
                {
                    PlayerId = player.Id,
                };
                //初始化资源
                player.Wallet.AddCurrency(CurrencyType.GOLD, 300000);
                player.Wallet.AddCurrency(CurrencyType.DIAMOND, 12888);
                player.Wallet.AddCurrency(CurrencyType.IRON, 10000);
                player.Wallet.AddCurrency(CurrencyType.SUPPLY, 10000);
                player.Wallet.AddCurrency(CurrencyType.OIL, 300);

                _db.Players.Add(player);
                this.OnPlayerCreating(player);
                player.MaxPower = player.Units.Sum(x => x.Power);
                _db.SaveChanges();
            }
            else
            {
                var queryPlayer = _db.Players
                                  .Where(p => p.UserCode == usercode);
                PlayerLoader loader = new PlayerLoader()
                {
                    Loader = queryPlayer
                };
                this.OnPlayerLoading(loader);
                player = loader.Loader.First();

                player.LastLoginTime = DateTime.Now;
                _db.SaveChanges();

                OnPlayerLoaded(player);
                _db.SaveChanges();
            }
            session.Login(player.Id);
            session.SetBind(player);

            this.OnPlayerEntered(player);
            AuthResponse response = new AuthResponse()
            {
                success = true,
                pid     = player.Id
            };

            session.SendAsync(response);

            return(0);
        }
示例#16
0
        public Stream Encrypt(Stream message, Key key)
        {
            DES DESkey1 = new DES();
            FileProcessing fp = new FileProcessing();
            MemoryStream ms = new MemoryStream();

            fp.EnCryptFile(message, ms, cm1k, DESkey1.KeyList, null, null, 0, false);

            return ms;
        }
示例#17
0
 public void EncodeTest()
 {
     DES des = new DES();
     var data = des.Encode(key, iv, "this is a test");
     Assert.IsTrue(data == "sT4UXx8ZNqyNxRMyp+gm9Q==");
 }
示例#18
0
 public DESForm()
 {
     InitializeComponent();
     des = DES.Create();
 }
示例#19
0
		public TripleDESCipher1(byte[] key) {
			Debug.Assert(key.Length==24);
			_DESCipher1 = new DES();
			_DESCipher2 = new DES();
			_DESCipher3 = new DES();
			
			_DESCipher1.InitializeKey(key, 0);
			_DESCipher2.InitializeKey(key, 8);
			_DESCipher3.InitializeKey(key,16);

			_buffer = new byte[8];
		}
示例#20
0
文件: DesTest.cs 项目: JackyLi918/HKH
 public void Init()
 {
     des = new DES(key);
 }
示例#21
0
        public static string AddCompany(string aid, string dabc, string daddress, string dcode, string dname, string dtype, string iadmin, string idep, string iproduction, string manager, string telephone)
        {
            string              r    = "";
            Sys_Depment         sd   = new Sys_Depment();
            Sys_DepmentDpt      sdd  = new Sys_DepmentDpt();
            Sys_DepmentBll      sdb  = new Sys_DepmentBll();
            Sys_DepmentDptBll   sddb = new Sys_DepmentDptBll();
            SessionUserValidate iv   = SysValidateBll.ValidateSession();

            if (iv.f)
            {
                sd.dname        = dname;
                sd.dcode        = dcode;
                sd.disend       = true;
                sd.disused      = true;
                sd.dattr        = dtype;
                sd.dcdate       = DateTime.Now.ToString();
                sd.dmaker       = iv.u.ename;
                sd.dpcode       = "0001";
                sd.dpname       = "北京联汇软件";
                sd.dcdep        = idep;
                sd.dread        = true;
                sd.dabc         = dabc;
                sdd.dcode       = dcode;
                sdd.daddress    = daddress;
                sdd.dcontact    = telephone;
                sdd.ddetail     = "";
                sdd.dfitment    = DateTime.Now.ToString();
                sdd.dmaker      = iv.u.ename;
                sdd.dmanager    = manager;
                sdd.dno         = "";
                sdd.iadmin      = iadmin == "1" ? true : false;
                sdd.idepment    = idep;
                sdd.logo        = "";
                sdd.iproduction = iproduction == "1" ? true : false;
                sdd.dperson     = 0;
                if (aid == "0")
                {
                    if (sdb.AddDepWithChildDep(sd) > 0)
                    {
                        if (sdd.iadmin)
                        {
                            #region
                            Sys_Employee       se   = new Sys_Employee();
                            Sys_User           su   = new Sys_User();
                            Sys_EmployeeDpt    sed  = new Sys_EmployeeDpt();
                            Sys_EmployeeBll    seb  = new Sys_EmployeeBll();
                            Sys_UserBll        sub  = new Sys_UserBll();
                            Sys_Employee       cse  = new Sys_Employee();
                            Sys_EmployeeDptBll sedb = new Sys_EmployeeDptBll();

                            se.dname  = sd.dname;
                            se.dcode  = sd.dcode;
                            se.eno    = "E" + seb.GetEno().ToString().PadLeft(8, '0');
                            se.ename  = sd.dname + "管理员";
                            se.estate = true;
                            se.dtcode = "";
                            se.elogin = true;
                            se.ecdate = DateTime.Now.ToString();
                            se.emaker = iv.u.ename;
                            se.rcode  = "0001";

                            sed.eaddress     = "";
                            sed.eage         = 0;
                            sed.eeducation   = "";
                            sed.eemail       = "";
                            sed.eheadimage   = "";
                            sed.eidentity    = "";
                            sed.enativeplace = "";
                            sed.eno          = se.eno;
                            sed.esex         = true;
                            sed.etelephone   = "";
                            sed.eworkdate    = DateTime.Now.ToString();

                            su.eno        = se.eno;
                            su.upass      = DES.EncryptDES("123456");
                            su.uname      = sd.dabc + "_admin";
                            su.ulogin     = true;
                            su.uip        = "";
                            su.ulogintime = "";
                            seb.AddList(se, sed, su);
                            #endregion
                        }
                        if (sdd.iproduction)
                        {
                            #region
                            Sys_InventoryCategoryBll sicb = new Sys_InventoryCategoryBll();
                            Sys_InventoryCategory    zcp  = new Sys_InventoryCategory();
                            zcp.iccode  = sd.dcode;
                            zcp.icpcode = "";
                            zcp.icname  = sd.dname + "产品";
                            zcp.icpname = "";
                            zcp.maker   = iv.u.ename;
                            zcp.cdate   = DateTime.Now.ToString();
                            zcp.icsend  = true;
                            zcp.icstate = false;
                            zcp.icms    = "";
                            sicb.Add(zcp);
                            Sys_InventoryCategory ztm = new Sys_InventoryCategory();
                            ztm.iccode  = sd.dcode + "10";
                            ztm.icpcode = sd.dcode;
                            ztm.icname  = "整套门";
                            ztm.icpname = "";
                            ztm.maker   = iv.u.ename;
                            ztm.cdate   = DateTime.Now.ToString();
                            ztm.icsend  = true;
                            ztm.icstate = true;
                            ztm.icms    = "";
                            ztm.isort   = 1;
                            sicb.Add(ztm);
                            Sys_InventoryCategory ms = new Sys_InventoryCategory();
                            ms.iccode  = sd.dcode + "01";
                            ms.icpcode = sd.dcode;
                            ms.icname  = "门扇";
                            ms.icpname = "";
                            ms.maker   = iv.u.ename;
                            ms.cdate   = DateTime.Now.ToString();
                            ms.icsend  = true;
                            ms.icstate = false;
                            ms.icms    = "";
                            ms.isort   = 2;
                            sicb.Add(ms);
                            Sys_InventoryCategory dms = new Sys_InventoryCategory();
                            dms.iccode  = ms.iccode + "01";
                            dms.icpcode = ms.iccode;
                            dms.icname  = "单开门";
                            dms.icpname = "门扇";
                            dms.maker   = iv.u.ename;
                            dms.cdate   = DateTime.Now.ToString();
                            dms.icsend  = true;
                            dms.icstate = true;
                            dms.icms    = "";
                            dms.isort   = 21;
                            sicb.Add(dms);
                            Sys_InventoryCategory sms = new Sys_InventoryCategory();
                            sms.iccode  = ms.iccode + "02";
                            sms.icpcode = ms.iccode;
                            sms.icname  = "对开门";
                            sms.icpname = "门扇";
                            sms.maker   = iv.u.ename;
                            sms.cdate   = DateTime.Now.ToString();
                            sms.icsend  = true;
                            sms.icstate = true;
                            sms.icms    = "";
                            sms.isort   = 22;
                            sicb.Add(sms);
                            Sys_InventoryCategory zms = new Sys_InventoryCategory();
                            zms.iccode  = ms.iccode + "03";
                            zms.icpcode = ms.iccode;
                            zms.icname  = "子母门";
                            zms.icpname = "门扇";
                            zms.maker   = iv.u.ename;
                            zms.cdate   = DateTime.Now.ToString();
                            zms.icsend  = true;
                            zms.icstate = true;
                            zms.icms    = "";
                            zms.isort   = 23;
                            sicb.Add(zms);
                            Sys_InventoryCategory tlm = new Sys_InventoryCategory();
                            tlm.iccode  = ms.iccode + "04";
                            tlm.icpcode = ms.iccode;
                            tlm.icname  = "推拉门";
                            tlm.icpname = "门扇";
                            tlm.maker   = iv.u.ename;
                            tlm.cdate   = DateTime.Now.ToString();
                            tlm.icsend  = true;
                            tlm.icstate = false;
                            tlm.icms    = "";
                            tlm.isort   = 24;
                            sicb.Add(tlm);
                            Sys_InventoryCategory stlm = new Sys_InventoryCategory();
                            stlm.iccode  = tlm.iccode + "01";
                            stlm.icpcode = tlm.iccode;
                            stlm.icname  = "两扇推拉门";
                            stlm.icpname = "推拉门";
                            stlm.maker   = iv.u.ename;
                            stlm.cdate   = DateTime.Now.ToString();
                            stlm.icsend  = true;
                            stlm.icstate = true;
                            stlm.icms    = "";
                            stlm.isort   = 241;
                            sicb.Add(stlm);
                            Sys_InventoryCategory ftlm = new Sys_InventoryCategory();
                            ftlm.iccode  = tlm.iccode + "02";
                            ftlm.icpcode = tlm.iccode;
                            ftlm.icname  = "四扇推拉门";
                            ftlm.icpname = "推拉门";
                            ftlm.maker   = iv.u.ename;
                            ftlm.cdate   = DateTime.Now.ToString();
                            ftlm.icsend  = true;
                            ftlm.icstate = true;
                            ftlm.icms    = "";
                            ftlm.isort   = 242;
                            sicb.Add(ftlm);
                            Sys_InventoryCategory mt = new Sys_InventoryCategory();
                            mt.iccode  = sd.dcode + "02";
                            mt.icpcode = sd.dcode;
                            mt.icname  = "门套";
                            mt.icpname = "";
                            mt.maker   = iv.u.ename;
                            mt.cdate   = DateTime.Now.ToString();
                            mt.icsend  = true;
                            mt.icstate = false;
                            mt.icms    = "";
                            mt.isort   = 3;
                            sicb.Add(mt);
                            Sys_InventoryCategory dmt = new Sys_InventoryCategory();
                            dmt.iccode  = mt.iccode + "01";
                            dmt.icpcode = mt.iccode;
                            dmt.icname  = "单开门套";
                            dmt.icpname = "门套";
                            dmt.maker   = iv.u.ename;
                            dmt.cdate   = DateTime.Now.ToString();
                            dmt.icsend  = true;
                            dmt.icstate = true;
                            dmt.icms    = "";
                            dmt.isort   = 31;
                            sicb.Add(dmt);
                            Sys_InventoryCategory smt = new Sys_InventoryCategory();
                            smt.iccode  = mt.iccode + "02";
                            smt.icpcode = mt.iccode;
                            smt.icname  = "对开门套";
                            smt.icpname = "门套";
                            smt.maker   = iv.u.ename;
                            smt.cdate   = DateTime.Now.ToString();
                            smt.icsend  = true;
                            smt.icstate = true;
                            smt.icms    = "";
                            smt.isort   = 32;
                            sicb.Add(smt);
                            Sys_InventoryCategory zmt = new Sys_InventoryCategory();
                            zmt.iccode  = mt.iccode + "03";
                            zmt.icpcode = mt.iccode;
                            zmt.icname  = "子母门套";
                            zmt.icpname = "门套";
                            zmt.maker   = iv.u.ename;
                            zmt.cdate   = DateTime.Now.ToString();
                            zmt.icsend  = true;
                            zmt.icstate = true;
                            zmt.icms    = "";
                            zmt.isort   = 33;
                            sicb.Add(zmt);
                            Sys_InventoryCategory tmt = new Sys_InventoryCategory();
                            tmt.iccode  = mt.iccode + "04";
                            tmt.icpcode = mt.iccode;
                            tmt.icname  = "推拉门套";
                            tmt.icpname = "门套";
                            tmt.maker   = iv.u.ename;
                            tmt.cdate   = DateTime.Now.ToString();
                            tmt.icsend  = true;
                            tmt.icstate = true;
                            tmt.icms    = "";
                            tmt.isort   = 34;
                            sicb.Add(tmt);
                            Sys_InventoryCategory wj = new Sys_InventoryCategory();
                            wj.iccode  = sd.dcode + "04";
                            wj.icpcode = sd.dcode;
                            wj.icname  = "五金";
                            wj.icpname = "";
                            wj.maker   = iv.u.ename;
                            wj.cdate   = DateTime.Now.ToString();
                            wj.icsend  = true;
                            wj.icstate = true;
                            wj.icms    = "";
                            wj.isort   = 4;
                            sicb.Add(wj);
                            Sys_InventoryCategory bl = new Sys_InventoryCategory();
                            bl.iccode  = sd.dcode + "05";
                            bl.icpcode = sd.dcode;
                            bl.icname  = "玻璃";
                            bl.icpname = "";
                            bl.maker   = iv.u.ename;
                            bl.cdate   = DateTime.Now.ToString();
                            bl.icsend  = true;
                            bl.icstate = true;
                            bl.icms    = "";
                            bl.isort   = 5;
                            sicb.Add(bl);
                            Sys_InventoryCategory ct = new Sys_InventoryCategory();
                            ct.iccode  = sd.dcode + "06";
                            ct.icpcode = sd.dcode;
                            ct.icname  = "窗套";
                            ct.icpname = "";
                            ct.maker   = iv.u.ename;
                            ct.cdate   = DateTime.Now.ToString();
                            ct.icsend  = true;
                            ct.icstate = true;
                            ct.icms    = "";
                            ct.isort   = 6;
                            sicb.Add(ct);
                            Sys_InventoryCategory yk = new Sys_InventoryCategory();
                            yk.iccode  = sd.dcode + "07";
                            yk.icpcode = sd.dcode;
                            yk.icname  = "垭口";
                            yk.icpname = "";
                            yk.maker   = iv.u.ename;
                            yk.cdate   = DateTime.Now.ToString();
                            yk.icsend  = true;
                            yk.icstate = true;
                            yk.icms    = "";
                            yk.isort   = 7;
                            sicb.Add(yk);
                            Sys_InventoryCategory hj = new Sys_InventoryCategory();
                            hj.iccode  = sd.dcode + "08";
                            hj.icpcode = sd.dcode;
                            hj.icname  = "护角";
                            hj.icpname = "";
                            hj.maker   = iv.u.ename;
                            hj.cdate   = DateTime.Now.ToString();
                            hj.icsend  = true;
                            hj.icstate = true;
                            hj.icms    = "";
                            hj.isort   = 8;
                            sicb.Add(hj);
                            Sys_InventoryCategory qt = new Sys_InventoryCategory();
                            qt.iccode  = sd.dcode + "09";
                            qt.icpcode = sd.dcode;
                            qt.icname  = "其他";
                            qt.icpname = "";
                            qt.maker   = iv.u.ename;
                            qt.cdate   = DateTime.Now.ToString();
                            qt.icsend  = true;
                            qt.icstate = true;
                            qt.icms    = "";
                            qt.isort   = 9;
                            sicb.Add(qt);
                            #endregion
                        }
                        sddb.Add(sdd);
                        r = "S";
                    }
                    else
                    {
                        r = "F";
                    }
                }
                else
                {
                    if (sdb.Update(sd))
                    {
                        sddb.Update(sdd);
                        r = "S";
                    }
                    else
                    {
                        r = "F";
                    }
                }
            }
            else
            {
                r = iv.badstr;
            }
            return(r);
        }
示例#22
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string data = "";
            string Act  = HTTPRequest.GetString("Act");

            if (Act.Trim() != "")
            {
                //对账单
                if (Act == "d")
                {
                    int msid = HTTPRequest.GetInt("msid", 0);
                    if (msid > 0)
                    {
                        MonthlyStatementInfo msi = MonthlyStatements.GetMonthlyStatementInfoModel(msid);
                        if (msi != null)
                        {
                            data = "" + config.Sysurl + "/m-" + msi.MonthlyStatementID + ".aspx?rc=" + Utils.UrlEncode(DES.Encode(msi.LastPrintDateTime.ToString() + "|" + msi.sCode, config.Passwordkey)).Trim();
                        }
                    }
                }
            }
            else
            {
                OrderInfo oi = new OrderInfo();
                orderid   = HTTPRequest.GetInt("orderid", 0);
                ordertype = HTTPRequest.GetInt("ordertype", 0);
                if (orderid > 0)
                {
                    oi = Orders.GetOrderInfoModel(orderid);
                    if (oi != null)
                    {
                        data = "" + config.Sysurl + "/o-" + oi.OrderID + ".aspx?rc=" + Utils.UrlEncode(DES.Encode(oi.LastPrintDateTime.ToString() + "|" + oi.oOrderNum, config.Passwordkey)).Trim();
                    }
                }
            }
            if (data != "")
            {
                QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();

                qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;

                int scale = 2;
                qrCodeEncoder.QRCodeScale = scale;

                int version = 5;
                qrCodeEncoder.QRCodeVersion = version;

                qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.L;

                System.Drawing.Image image;

                //String data = "MEBKM:TITLE:OrderID(" + oi.oOrderNum + "),PrintTime(" + oi.LastPrintDateTime + ");URL:" + config.Sysurl + "/o-" + oi.OrderID + ".aspx?rc=" + Utils.UrlEncode(DES.Encode(oi.LastPrintDateTime.ToString() + "|" + oi.oOrderNum, config.Passwordkey)).Trim() + ";;";

                //String data = oi.oOrderNum;
                image = qrCodeEncoder.Encode(data);
                try
                {
                    byte[] bBuffer = PhotoImageInsert(image);
                    Response.ClearContent();
                    Response.ContentType = "image/jpeg";
                    Response.BinaryWrite(bBuffer);
                }
                finally
                {
                    image.Dispose();
                    Response.End();
                }
            }
        }
 public DesStorageEncryptionProvider(string key)
 {
     encryptionProvider         = DES.Create();
     encryptionProvider.KeySize = 256;
     encryptionProvider.Key     = Encoding.UTF8.GetBytes(key);
 }
示例#24
0
        private static object GetDefaultAlgorithm(string algorithm)
        {
            if (string.IsNullOrEmpty(algorithm))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(algorithm)));
            }

            switch (algorithm)
            {
            //case SecurityAlgorithms.RsaSha1Signature:
            //case SecurityAlgorithms.DsaSha1Signature:
            // For these algorithms above, crypto config returns internal objects.
            // As we cannot create those internal objects, we are returning null.
            // If no custom algorithm is plugged-in, at least these two algorithms
            // will be inside the delegate dictionary.
            case SecurityAlgorithms.Sha1Digest:
#pragma warning disable CA5350 // Do not use insecure cryptographic algorithm SHA1.
                return(SHA1.Create());

#pragma warning restore CA5350 // Do not use insecure cryptographic algorithm SHA1.
            case SecurityAlgorithms.ExclusiveC14n:
                throw ExceptionHelper.PlatformNotSupported();

            case SHA256String:
            case SecurityAlgorithms.Sha256Digest:
                return(SHA256.Create());

            case SecurityAlgorithms.Sha512Digest:
                return(SHA512.Create());

            case SecurityAlgorithms.Aes128Encryption:
            case SecurityAlgorithms.Aes192Encryption:
            case SecurityAlgorithms.Aes256Encryption:
            case SecurityAlgorithms.Aes128KeyWrap:
            case SecurityAlgorithms.Aes192KeyWrap:
            case SecurityAlgorithms.Aes256KeyWrap:
                return(Aes.Create());

            case SecurityAlgorithms.TripleDesEncryption:
            case SecurityAlgorithms.TripleDesKeyWrap:
#pragma warning disable CA5350 // Do Not Use Weak Cryptographic Algorithms
                return(TripleDES.Create());

#pragma warning restore CA5350 // Do Not Use Weak Cryptographic Algorithms
            case SecurityAlgorithms.HmacSha1Signature:
#pragma warning disable CA5350 // Do not use insecure cryptographic algorithm SHA1.
                return(new HMACSHA1());

#pragma warning restore CA5350 // Do not use insecure cryptographic algorithm SHA1.
            case SecurityAlgorithms.HmacSha256Signature:
                return(new HMACSHA256());

            case SecurityAlgorithms.ExclusiveC14nWithComments:
                throw ExceptionHelper.PlatformNotSupported();

            case SecurityAlgorithms.Ripemd160Digest:
                return(null);

            case SecurityAlgorithms.DesEncryption:
#pragma warning disable CA5351 // Do Not Use Broken Cryptographic Algorithms
                return(DES.Create());

#pragma warning restore CA5351 // Do Not Use Broken Cryptographic Algorithms
            default:
                return(null);
            }
        }
示例#25
0
        private void ClReg()
        {
            Action action = () =>
            {
                if (tbFirstname.Text.Length == 0)
                {
                    tbFirstname.BackColor = Color.Red;
                }
                else
                {
                    tbFirstname.BackColor = Color.White;
                    if (tbName.Text.Length == 0)
                    {
                        tbName.BackColor = Color.Red;
                    }
                    else
                    {
                        tbName.BackColor = Color.White;
                        if ((tbLogin.Text.Length == 0) | (tbLogin.Text.IndexOf('@') == -1) | (tbLogin.Text.IndexOf('.') == -1) | (tbLogin.Text.IndexOf('@') > tbLogin.Text.IndexOf('.')))
                        {
                            tbLogin.BackColor = Color.Red;
                        }
                        else
                        {
                            tbLogin.BackColor = Color.White;
                            ArrayList Checkarray = new ArrayList();
                            DES       des        = DES.Create();
                            byte[]    key        = Convert.FromBase64String("ybqAS+sVBLY=");
                            byte[]    IV         = Convert.FromBase64String("1mbClpyz5bU=");
                            des.Key = key;
                            des.IV  = IV;
                            byte[] login = Crypt_Class.SymmetricEncrypt(tbLogin.Text, des);
                            Checkarray.Add("\'" + Convert.ToBase64String(login) + "\'");
                            Function_class UQCheck = new Function_class("Client_Face_Adress_UQ_Check", Function_class.Function_Result.scalar, Checkarray);
                            if (UQCheck.Regtable.Rows[0][0].ToString() == "False")
                            {
                                tbLogin.BackColor = Color.Red;
                            }
                            else
                            {
                                tbLogin.BackColor = Color.White;
                                if ((tbPassword.Text.Length < 6) | (tbPassword.Text.IndexOfAny(numbers) == -1) | (tbPassword.Text.IndexOfAny(ruLetters) != -1) | (tbPassword.Text != tbConfirm.Text))
                                {
                                    tbPassword.BackColor = Color.Red;
                                }
                                else
                                {
                                    tbPassword.BackColor = Color.Red;
                                    ArrayList array = new ArrayList();
                                    array.Add(tbName.Text);
                                    array.Add(tbFirstname.Text);
                                    array.Add(tbPatronymic.Text);
                                    DES    indes = DES.Create();
                                    byte[] inkey = Convert.FromBase64String("ybqAS+sVBLY=");
                                    byte[] inIV  = Convert.FromBase64String("1mbClpyz5bU=");
                                    indes.Key = inkey;
                                    indes.IV  = inIV;
                                    byte[] inlogin  = Crypt_Class.SymmetricEncrypt(tbLogin.Text, indes);
                                    byte[] inpasswd = Crypt_Class.SymmetricEncrypt(tbPassword.Text, indes);
                                    array.Add(Convert.ToBase64String(inlogin));
                                    array.Add(Convert.ToBase64String(inpasswd));
                                    array.Add(cbClient.SelectedValue);
                                    array.Add("0");
                                    Procedure_Class procedure = new Procedure_Class();
                                    procedure.procedure_Execution("Client_Face_Insert", array);
                                    this.Hide();
                                    this.Owner.Show();
                                }
                            }
                        }
                    }
                }
            };

            Invoke(action);
        }
示例#26
0
        //шифровка массива строк
        public static void EncryptTextToFile(String[] Data, String FileName, byte[] Key, byte[] IV)
        {
            try
            {
                // Create or open the specified file.
                FileStream fStream = File.Open(FileName, FileMode.OpenOrCreate);

                // Create a new DES object.
                DES DESalg = DES.Create();

                // Create a CryptoStream using the FileStream
                // and the passed key and initialization vector (IV).
                CryptoStream cStream = new CryptoStream(fStream,
                                                        DESalg.CreateEncryptor(Key, IV),
                                                        CryptoStreamMode.Write);

                // Create a StreamWriter using the CryptoStream.
                StreamWriter sWriter = new StreamWriter(cStream);

                // Write the data to the stream
                // to encrypt it.



                // sWriter.WriteLine(Data);

                //сюда надо добавить запись множества строк в файл
                /**/ foreach (string str in Data)
                {
                    sWriter.WriteLine(str);// +'\n');
                }

                // Close the streams and
                // close the file.
                sWriter.Close();
                cStream.Close();
                fStream.Close();
            }
            catch (CryptographicException e)
            {
                Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
            }
            catch (UnauthorizedAccessException e)
            {
                Console.WriteLine("A file error occurred: {0}", e.Message);
            }
        }

        //шифровка одной строки
        public static void EncryptTextToFile(String Data, String FileName, byte[] Key, byte[] IV)
        {
            try
            {
                // Create or open the specified file.
                FileStream fStream = File.Open(FileName, FileMode.OpenOrCreate);

                // Create a new DES object.
                DES DESalg = DES.Create();

                // Create a CryptoStream using the FileStream
                // and the passed key and initialization vector (IV).
                CryptoStream cStream = new CryptoStream(fStream,
                                                        DESalg.CreateEncryptor(Key, IV),
                                                        CryptoStreamMode.Write);

                // Create a StreamWriter using the CryptoStream.
                StreamWriter sWriter = new StreamWriter(cStream);

                // Write the data to the stream
                // to encrypt it.



                sWriter.WriteLine(Data);

                //сюда надо добавить запись множества строк в файл

                /*
                 * foreach (string str in Data)
                 * {
                 *  sWriter.WriteLine(str);// +'\n');
                 * }
                 */
                // Close the streams and
                // close the file.
                sWriter.Close();
                cStream.Close();
                fStream.Close();
            }
            catch (CryptographicException e)
            {
                Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
            }
            catch (UnauthorizedAccessException e)
            {
                Console.WriteLine("A file error occurred: {0}", e.Message);
            }
        }
示例#27
0
        protected virtual void Page_Load(object sender, EventArgs e)
        {
            int      uid = -1;
            UserInfo ui  = new UserInfo();

            postusername = Utils.ChkSQL(HTTPRequest.GetString("username"));
            postpassword = Utils.ChkSQL(HTTPRequest.GetString("password"));

            if (!ispost)
            {
                if (this.userid > 0)
                {
                    AddErrLine("您已经登录,无需重复登录。");
                    AddScript("window.setTimeout(function(){top.location='Default.aspx';},1500);");
                    SetShowMsgLink(false);
                }
            }
            else
            {
                try
                {
                    if (postpassword.Equals(""))
                    {
                        AddErrLine("密码不能为空");
                    }
                    else
                    {
                        if (postusername.Equals(""))
                        {
                            AddErrLine("用户名不能为空");
                        }
                        else
                        {
                            if (BLL.tbUserInfo.ExistsUserInfo(postusername))
                            {
                                uid = BLL.tbUserInfo.CheckPassword(postusername, postpassword, true);
                                if (uid != -1)
                                {
                                    UserInfo tui = BLL.tbUserInfo.GetUserInfoModel(uid);
                                    if (tui.uEstate == 1)
                                    {
                                        AddErrLine("抱歉, 您的用户身份尚未得到验证");
                                    }
                                    if (!IsErr())
                                    {
                                        BLL.tbUserInfo.DeleteErrLoginRecord(this.GetIP());
                                        tui.uLastIP       = this.GetIP();
                                        tui.uUpAppendTime = DateTime.Now;
                                        BLL.tbUserInfo.UpdateUserInfo(tui);
                                        UsersUtils.WriteUserCookie(uid, Utils.StrToInt(HTTPRequest.GetString("expires"), -1), config.Passwordkey, HTTPRequest.GetInt("loginmode", -1));
                                        UsersUtils.WriteCookie("UserPKey", DES.Encode(postpassword, config.Passwordkey));

                                        AddMsgLine("登录成功,页面转接中,请稍后!");

                                        AddScript("window.setTimeout(function(){top.location='Default.aspx';},1000);");

                                        SetShowMsgLink(false);
                                    }
                                }
                                else
                                {
                                    CheckPassErrorCount();
                                }
                            }
                            else
                            {
                                AddErrLine("用户不存在");
                            }
                        }
                    }
                    if (IsErr())
                    {
                        AddScript("window.setTimeout(function(){window.history.go(-1);},1500);");
                        SetShowMsgLink(false);
                    }
                }
                finally
                {
                    ui = null;
                }
            }
        }
示例#28
0
        /// <summary>
        /// 初始连接字符串
        /// </summary>
        public static void InitConnList()
        {
            lock (obj)//对象同步 许亚修改2014.3.14
            {
                //获取连接字符串是否成功
                bool getConnectionSuccess = false;
                //获取连接字符串次数
                int getConnectionCounter = 0;

                while (!getConnectionSuccess && getConnectionCounter <= RETRY_COUNT)
                {
                    try
                    {
                        Logger.InfoFormat("第{0}次获取连接字符串开始...", getConnectionCounter + 1);
                        lock (DbListObj)
                        {
                            _lstConnStrings = ConnectionStringFactory.Create(ConfigConnStringCreator.Create())
                                              .GetConnectionStrings();

                            if (_lstConnStrings.Count == 0)
                            {
                                throw new Exception("没有要使用的字符串.请检查配置文件");
                            }
                            //日志
                            if (Logger.IsInfoEnabled)
                            {
                                var stringBuilder = new StringBuilder();
                                stringBuilder.Append(string.Format("ConnectionString初始化完成,共有数据库连接字符串:{0}个",
                                                                   _lstConnStrings.Count));
                                foreach (IConnectionString databaseModel in _lstConnStrings)
                                {
                                    stringBuilder.AppendLine(databaseModel.ToString());
                                }
                                Logger.Info(stringBuilder.ToString());
                            }
                        }
                        getConnectionSuccess = true;
                    }
                    catch (Exception ex)
                    {
                        Logger.Error(ex.Message, ex);
                        Thread.Sleep(500);
                        getConnectionCounter++;
                    }
                }
                foreach (IConnectionString connString in _lstConnStrings)
                {
                    try
                    {
                        if (!IsPlainText(connString.ConnectionString))
                        {
                            connString.ConnectionString = DES.Decrypt3DES(connString.ConnectionString);
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Error("解密连接串失败:name:" + connString.Name + "  message:" + ex.Message, ex);
                    }
                    if (!ConnStringCache.ContainsKey(connString.Name))
                    {
                        ConnStringCache.Add(connString.Name, connString.ConnectionString);
                    }
                    if (!ProviderNameCache.ContainsKey(connString.Name))
                    {
                        ProviderNameCache.Add(connString.Name, connString.ProviderName);
                    }
                }
            }
        }
示例#29
0
 public clsDES(string key, string iv)
 {
     this.mydes = new DESCryptoServiceProvider();
     this.Key   = key;
     this.IV    = iv;
 }
示例#30
0
        private void onDecryptBtnClicked(object sender, EventArgs e)
        {
            if (!checkOptions())
            {
                return;
            }

            byte[] key;
            for (int i = 0; i < files.Length; i++)
            {
                byte[] iv         = null;
                byte[] fileBytes  = FileUtil.readFile(files[i]);
                byte[] fileBytes2 = null;
                if (hashType == "md5")
                {
                    if (passRadio.Checked)
                    {
                        key = Hash.md5(Encoding.UTF8.GetBytes(password));
                    }
                    else
                    {
                        key = Hash.md5(FileUtil.readFile(keyFile));
                    }
                    iv = new byte[16];
                    Buffer.BlockCopy(fileBytes, 0, iv, 0, 16);
                    fileBytes2 = new byte[fileBytes.Length - 16];
                    Buffer.BlockCopy(fileBytes, 16, fileBytes2, 0, fileBytes.Length - 16);
                }
                else if (hashType == "ripemd256")
                {
                    if (passRadio.Checked)
                    {
                        key = Hash.ripemd256(Encoding.UTF8.GetBytes(password));
                    }
                    else
                    {
                        key = Hash.ripemd256(FileUtil.readFile(keyFile));
                    }
                    iv = new byte[32];
                    Buffer.BlockCopy(fileBytes, 0, iv, 0, 32);
                    fileBytes2 = new byte[fileBytes.Length - 32];
                    Buffer.BlockCopy(fileBytes, 32, fileBytes2, 0, fileBytes.Length - 32);
                }
                else if (hashType == "sha256")
                {
                    if (passRadio.Checked)
                    {
                        key = Hash.sha256(Encoding.UTF8.GetBytes(password));
                    }
                    else
                    {
                        key = Hash.sha256(FileUtil.readFile(keyFile));
                    }
                    iv = new byte[32];
                    Buffer.BlockCopy(fileBytes, 0, iv, 0, 32);
                    fileBytes2 = new byte[fileBytes.Length - 32];
                    Buffer.BlockCopy(fileBytes, 32, fileBytes2, 0, fileBytes.Length - 32);
                }
                else if (hashType == "sha512")
                {
                    if (passRadio.Checked)
                    {
                        key = Hash.sha512(Encoding.UTF8.GetBytes(password));
                    }
                    else
                    {
                        key = Hash.sha512(FileUtil.readFile(keyFile));
                    }
                    iv = new byte[64];
                    Buffer.BlockCopy(fileBytes, 0, iv, 0, 64);
                    fileBytes2 = new byte[fileBytes.Length - 64];
                    Buffer.BlockCopy(fileBytes, 64, fileBytes2, 0, fileBytes.Length - 64);
                }
                else                     //Whirlpool
                {
                    if (passRadio.Checked)
                    {
                        key = Hash.whirlpool(Encoding.UTF8.GetBytes(password));
                    }
                    else
                    {
                        key = Hash.whirlpool(FileUtil.readFile(keyFile));
                    }
                    iv = new byte[64];
                    Buffer.BlockCopy(fileBytes, 0, iv, 0, 64);
                    fileBytes2 = new byte[fileBytes.Length - 64];
                    Buffer.BlockCopy(fileBytes, 64, fileBytes2, 0, fileBytes.Length - 64);
                }

                byte[] decryptedBytes;
                if (encryptType == "aes")
                {
                    decryptedBytes = AES.decrypt(fileBytes2, key, iv, encryptMode, encryptPadding);
                }
                else if (encryptType == "blowfish")
                {
                    decryptedBytes = Blowfish.decrypt(fileBytes2, key, iv, encryptMode, encryptPadding);
                }
                else                     //Triple-DES
                {
                    decryptedBytes = DES.decrypt(fileBytes2, key, iv, encryptMode, encryptPadding);
                }

                FileUtil.writeFile((replaceOpt) ? files[i] : files[i] + ".decrypted", decryptedBytes);
            }
        }
示例#31
0
 public static String GetEncryptText(String cryptText)
 {
     return(DES.Encrypt(cryptText, KEY));
 }
示例#32
0
        private void onEncryptBtnClicked(object sender, EventArgs e)
        {
            if (!checkOptions())
            {
                return;
            }

            byte[] key;
            for (int i = 0; i < files.Length; i++)
            {
                byte[] iv        = null;
                byte[] fileBytes = FileUtil.readFile(files[i]);
                if (hashType == "md5")
                {
                    if (passRadio.Checked)
                    {
                        key = Hash.md5(Encoding.UTF8.GetBytes(password));
                    }
                    else
                    {
                        key = Hash.md5(FileUtil.readFile(keyFile));
                    }
                    iv = rand.getNextBytes(16);
                }
                else if (hashType == "ripemd256")
                {
                    if (passRadio.Checked)
                    {
                        key = Hash.ripemd256(Encoding.UTF8.GetBytes(password));
                    }
                    else
                    {
                        key = Hash.ripemd256(FileUtil.readFile(keyFile));
                    }
                    iv = rand.getNextBytes(32);
                }
                else if (hashType == "sha256")
                {
                    if (passRadio.Checked)
                    {
                        key = Hash.sha256(Encoding.UTF8.GetBytes(password));
                    }
                    else
                    {
                        key = Hash.sha256(FileUtil.readFile(keyFile));
                    }
                    iv = rand.getNextBytes(32);
                }
                else if (hashType == "sha512")
                {
                    if (passRadio.Checked)
                    {
                        key = Hash.sha512(Encoding.UTF8.GetBytes(password));
                    }
                    else
                    {
                        key = Hash.sha512(FileUtil.readFile(keyFile));
                    }
                    iv = rand.getNextBytes(64);
                }
                else                     //Whirlpool
                {
                    if (passRadio.Checked)
                    {
                        key = Hash.whirlpool(Encoding.UTF8.GetBytes(password));
                    }
                    else
                    {
                        key = Hash.whirlpool(FileUtil.readFile(keyFile));
                    }
                    iv = rand.getNextBytes(64);
                }

                byte[] encryptedBytes;
                if (encryptType == "aes")
                {
                    encryptedBytes = AES.encrypt(fileBytes, key, iv, encryptMode, encryptPadding);
                }
                else if (encryptType == "blowfish")
                {
                    encryptedBytes = Blowfish.encrypt(fileBytes, key, iv, encryptMode, encryptPadding);
                }
                else                     //Triple-DES
                {
                    encryptedBytes = DES.encrypt(fileBytes, key, iv, encryptMode, encryptPadding);
                }

                byte[] outBytes = new byte[encryptedBytes.Length + iv.Length];
                Buffer.BlockCopy(iv, 0, outBytes, 0, iv.Length);
                Buffer.BlockCopy(encryptedBytes, 0, outBytes, iv.Length, encryptedBytes.Length);

                FileUtil.writeFile((replaceOpt) ? files[i] : files[i] + ".encrypted", outBytes);
            }
        }
示例#33
0
    private void Init(byte[] key)
    {
      Debug.Assert(key.Length == 24);
      _buffer = new byte[8];
      _ivSave = new byte[8];
      _DESCipher1 = new DES();
      _DESCipher2 = new DES();
      _DESCipher3 = new DES();

      _DESCipher1.InitializeKey(key, 0);
      _DESCipher2.InitializeKey(key, 8);
      _DESCipher3.InitializeKey(key, 16);
    }
        /// <summary>
        /// Decrypt DES encrypted scoped PDU.
        /// </summary>
        /// <param name="encryptedData">Source data buffer</param>
        /// <param name="key">Decryption key. Key length has to be 32 bytes in length or longer (bytes beyond 32 bytes are ignored).</param>
        /// <param name="privacyParameters">Privacy parameters extracted from USM header</param>
        /// <returns>Decrypted byte array</returns>
        /// <exception cref="ArgumentNullException">Thrown when encrypted data is null or length == 0</exception>
        /// <exception cref="ArgumentOutOfRangeException">Thrown when encryption key length is less then 32 byte or if privacy parameters
        /// argument is null or length other then 8 bytes</exception>
        public static byte[] Decrypt(byte[] encryptedData, byte[] key, byte[] privacyParameters)
        {
            if (encryptedData == null)
            {
                throw new ArgumentNullException("encryptedData");
            }

            if (key == null)
            {
                throw new ArgumentNullException("key");
            }

            if (privacyParameters == null)
            {
                throw new ArgumentNullException("privacyParameters");
            }

            if (encryptedData.Length == 0)
            {
                throw new ArgumentException("empty encrypted data", "encryptedData");
            }

            if ((encryptedData.Length % 8) != 0)
            {
                throw new ArgumentException("Encrypted data buffer has to be divisible by 8.", "encryptedData");
            }

            if (privacyParameters.Length != PrivacyParametersLength)
            {
                throw new ArgumentOutOfRangeException("privacyParameters", "Privacy parameters argument has to be 8 bytes long");
            }

            if (key.Length < MinimumKeyLength)
            {
                throw new ArgumentOutOfRangeException("key", "Decryption key has to be at least 16 bytes long.");
            }

            var iv = new byte[8];

            for (var i = 0; i < 8; ++i)
            {
                iv[i] = (byte)(key[8 + i] ^ privacyParameters[i]);
            }

            using (DES des = DES.Create())
            {
                des.Mode    = CipherMode.CBC;
                des.Padding = PaddingMode.Zeros;

                // .NET implementation only takes an 8 byte key
                var outKey = new byte[8];
                Buffer.BlockCopy(key, 0, outKey, 0, 8);

                des.Key = outKey;
                des.IV  = iv;
                using (var transform = des.CreateDecryptor())
                {
                    var decryptedData = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
                    des.Clear();
                    return(decryptedData);
                }
            }
        }
示例#35
0
 public void GentrateKeyTest()
 {
     DES des = new DES();
     var data = des.GenerateRandomKey();
     Assert.IsTrue(data != null);
 }
        /// <summary>
        /// Encrypt scoped PDU using DES encryption protocol
        /// </summary>
        /// <param name="unencryptedData">Unencrypted scoped PDU byte array</param>
        /// <param name="key">Encryption key. Key has to be at least 32 bytes is length</param>
        /// <param name="privacyParameters">Privacy parameters out buffer. This field will be filled in with information
        /// required to decrypt the information. Output length of this field is 8 bytes and space has to be reserved
        /// in the USM header to store this information</param>
        /// <returns>Encrypted byte array</returns>
        /// <exception cref="ArgumentOutOfRangeException">Thrown when encryption key is null or length of the encryption key is too short.</exception>
        public static byte[] Encrypt(byte[] unencryptedData, byte[] key, byte[] privacyParameters)
        {
            if (unencryptedData == null)
            {
                throw new ArgumentNullException("unencryptedData");
            }

            if (key == null)
            {
                throw new ArgumentNullException("key");
            }

            if (privacyParameters == null)
            {
                throw new ArgumentNullException("privacyParameters");
            }

            if (key.Length < MinimumKeyLength)
            {
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Encryption key length has to 32 bytes or more. Current: {0}", key.Length), "key");
            }

            var iv = GetIV(key, privacyParameters);

            // DES uses 8 byte keys but we need 16 to encrypt ScopedPdu. Get first 8 bytes and use them as encryption key
            var outKey = GetKey(key);

            var div = (int)Math.Floor(unencryptedData.Length / 8.0);

            if ((unencryptedData.Length % 8) != 0)
            {
                div += 1;
            }

            var newLength = div * 8;
            var result    = new byte[newLength];
            var buffer    = new byte[newLength];

            var inbuffer   = new byte[8];
            var cipherText = iv;
            var posIn      = 0;
            var posResult  = 0;

            Buffer.BlockCopy(unencryptedData, 0, buffer, 0, unencryptedData.Length);

            using (DES des = DES.Create())
            {
                des.Mode    = CipherMode.ECB;
                des.Padding = PaddingMode.None;

                using (var transform = des.CreateEncryptor(outKey, null))
                {
                    for (var b = 0; b < div; b++)
                    {
                        for (var i = 0; i < 8; i++)
                        {
                            inbuffer[i] = (byte)(buffer[posIn] ^ cipherText[i]);
                            posIn++;
                        }

                        transform.TransformBlock(inbuffer, 0, inbuffer.Length, cipherText, 0);
                        Buffer.BlockCopy(cipherText, 0, result, posResult, cipherText.Length);
                        posResult += cipherText.Length;
                    }
                }

                des.Clear();
            }

            return(result);
        }
示例#37
0
        public override void InitObjects(Unity_Level level)
        {
            // Hard-code event animations for the different Rayman types
            Unity_ObjGraphics rayDes = null;

            var rayEvent = (Unity_Object_R1)level.Rayman ?? level.EventData.Cast <Unity_Object_R1>().FirstOrDefault(x => x.EventData.Type == R1_EventType.TYPE_RAY_POS);

            if (rayEvent != null)
            {
                rayDes = DES.ElementAtOrDefault(rayEvent.DESIndex)?.Data.Graphics;
            }

            if (rayDes == null)
            {
                return;
            }

            var miniRay         = level.EventData.Cast <Unity_Object_R1>().FirstOrDefault(x => x.EventData.Type == R1_EventType.TYPE_DEMI_RAYMAN);
            var miniRayDESIndex = miniRay?.DESIndex;

            if (miniRayDESIndex == null && EventTemplates.ContainsKey(WldObjType.RayLittle))
            {
                miniRayDESIndex = UsesPointers ? DESLookup.TryGetItem(EventTemplates[WldObjType.RayLittle].ImageDescriptorsPointer?.AbsoluteOffset ?? 0, -1) : (int)EventTemplates[WldObjType.RayLittle].PC_ImageDescriptorsIndex;
            }

            if (miniRayDESIndex != null)
            {
                var miniRayDes = DES.ElementAtOrDefault(miniRayDESIndex.Value)?.Data.Graphics;

                if (miniRayDes != null)
                {
                    miniRayDes.Animations = rayDes.Animations.Select(anim =>
                    {
                        var newAnim = new Unity_ObjAnimation
                        {
                            Frames = anim.Frames.Select(x => new Unity_ObjAnimationFrame(x.SpriteLayers.Select(l => new Unity_ObjAnimationPart()
                            {
                                ImageIndex            = l.ImageIndex,
                                XPosition             = l.XPosition / 2,
                                YPosition             = l.YPosition / 2,
                                IsFlippedHorizontally = l.IsFlippedHorizontally,
                                IsFlippedVertically   = l.IsFlippedVertically,
                            }).ToArray())).ToArray()
                        };

                        return(newAnim);
                    }).ToList();
                }
            }

            var badRay = level.EventData.Cast <Unity_Object_R1>().FirstOrDefault(x => x.EventData.Type == R1_EventType.TYPE_BLACK_RAY);

            if (badRay != null)
            {
                var badRayDes = DES.ElementAtOrDefault(badRay.DESIndex)?.Data.Graphics;

                if (badRayDes != null)
                {
                    badRayDes.Animations = rayDes.Animations;
                }
            }

            // Set frames for linked events
            for (int i = 0; i < level.EventData.Count; i++)
            {
                // Recreated from allocateOtherPosts
                var baseEvent   = (Unity_Object_R1)level.EventData[i];
                var linkedIndex = LinkTable[i];

                if (baseEvent.EventData.Type.UsesRandomFrame() && i != linkedIndex)
                {
                    var index = 0;

                    do
                    {
                        index++;

                        var e = (Unity_Object_R1)level.EventData[linkedIndex];
                        e.ForceFrame = (byte)((baseEvent.ForceFrame + index) % (e.CurrentAnimation?.Frames.Length ?? 1));
                        e.XPosition  = (short)(baseEvent.EventData.XPosition + 32 * index * (baseEvent.EventData.HitPoints - 2));
                        e.YPosition  = baseEvent.YPosition;

                        linkedIndex = LinkTable[linkedIndex];
                    } while (i != linkedIndex);
                }
            }

            // Set DES and ETA for worldmap
            if (Context.Settings.R1_World == R1_World.Menu)
            {
                var mapObj = EventTemplates[WldObjType.MapObj];
                var rayman = level.Rayman as Unity_Object_R1;

                // Change Rayman to small Rayman
                if (miniRayDESIndex != null && rayman != null)
                {
                    rayman.DESIndex           = miniRayDESIndex.Value;
                    rayman.EventData.OffsetBX = (byte)(rayman.EventData.OffsetBX / 2);
                    rayman.EventData.OffsetBY = (byte)(rayman.EventData.OffsetBY / 2);
                }

                // Set Rayman's properties
                if (rayman != null)
                {
                    rayman.EventData.Etat    = rayman.EventData.InitialEtat = 0;
                    rayman.EventData.SubEtat = rayman.EventData.InitialSubEtat = 0;

                    if (Context.Settings.EngineVersion == EngineVersion.R1_PC_Kit)
                    {
                        // ?
                        rayman.XPosition = (short)(level.EventData[0].XPosition + 42 - rayman.EventData.OffsetBX);
                        rayman.YPosition = (short)(level.EventData[0].YPosition + 48 - rayman.EventData.OffsetBY);
                    }
                    else if (Context.Settings.EngineVersion == EngineVersion.R1_PC_Edu || Context.Settings.EngineVersion == EngineVersion.R1_PS1_Edu)
                    {
                        // ?
                        rayman.XPosition           = (short)(level.EventData[0].XPosition + 42 + 44 - rayman.EventData.OffsetBX);
                        rayman.YPosition           = (short)(level.EventData[0].YPosition + 48 + 24 - rayman.EventData.OffsetBY);
                        rayman.EventData.PC_Flags |= R1_EventData.PC_EventFlags.IsFlipped;
                    }
                    else
                    {
                        rayman.XPosition = (short)(level.EventData[0].XPosition + 70 - rayman.EventData.OffsetBX + 9); // The game does +4 instead of 9 - why?
                        rayman.YPosition = (short)(level.EventData[0].YPosition + 64 - rayman.EventData.OffsetBY + 8); // Is this correct?
                    }
                }

                foreach (var e in level.EventData.Cast <Unity_Object_R1>().Select(x => x.EventData))
                {
                    e.ImageDescriptorsPointer = mapObj.ImageDescriptorsPointer;
                    e.ImageBufferPointer      = mapObj.ImageBufferPointer;
                    e.AnimDescriptorsPointer  = mapObj.AnimDescriptorsPointer;
                    e.ETAPointer = mapObj.ETAPointer;

                    e.PC_ImageDescriptorsIndex     = mapObj.PC_ImageDescriptorsIndex;
                    e.PC_ImageBufferIndex          = mapObj.PC_ImageBufferIndex;
                    e.PC_AnimationDescriptorsIndex = mapObj.PC_AnimationDescriptorsIndex;
                    e.PC_ETAIndex = mapObj.PC_ETAIndex;
                }
            }
        }
示例#38
-1
 private static void Main2()
 {
     var des = new DES();
     string key = des.GenerateKey();
     string s0 = "中国软件 - csdn.net";
     string s1 = des.EncryptString(s0, key);
     string s2 = des.DecryptString(s1, key);
     Console.WriteLine("原串: [{0}]", s0);
     Console.WriteLine("加密: [{0}]", s1);
     Console.WriteLine("解密: [{0}]", s2);
     Console.ReadKey();
 }