Exemple #1
0
        protected void Page_Load(object sender, EventArgs e)
        {
            aesMgr   = new AESManager();
            emailMgr = new EmailManager();
            custMgr  = new CustomerModel();

            if (!IsPostBack)
            {
                if (Session[CommonManager.GetCustEmailSessionName()] == null)
                {
                    string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority + Request.ApplicationPath.TrimEnd('/') + "/";
                    Response.Redirect("Login.aspx");
                }
            }

            var _page = Request.QueryString["page"];

            if (_page != null)
            {
                currentPage = Convert.ToInt32(_page);
            }

            CommonHtmlManager.AddPurchItemPagination(currentPage, currentViewPerPage, ref this.paginationCtrl, PurchItemGetType.customerEmail, 0,
                                                     new AESManager().EncryptToString(Session[CommonManager.GetCustEmailSessionName()].ToString()));
        }
Exemple #2
0
        static public int UpdatePassWord(string userName, string OldpassWord, string NewPassWord)
        {
            if (VerifyLogin(userName, OldpassWord) != 3)
            {
                return(0);
            }
            MysqlConnector mySql = new MysqlConnector();

            mySql.SetServer(AESManager.AESDecrypt(AppVars.dbInfo.ipUrl, AppVars.AppParas.Enc0));
            mySql.SetDataBase(AESManager.AESDecrypt(AppVars.dbInfo.dataName, AppVars.AppParas.Enc1));
            mySql.SetUserID(AESManager.AESDecrypt(AppVars.dbInfo.userName, AppVars.AppParas.Enc2));
            mySql.SetPassword(AESManager.AESDecrypt(AppVars.dbInfo.passWord, AppVars.AppParas.Enc3));
            mySql.SetPort(AppVars.dbInfo.portNum.ToString());
            mySql.SetCharset("utf-8");
            string pwd = NewPassWord, salt = AppVars.AppParas.salt;

            try
            {
                mySql.ExeUpdate(string.Format("update {0} set password = '******' where uid = {2}",
                                              "user", MD5Manager.HashString(MD5Manager.HashString(NewPassWord) + salt), AppVars.AppParas.uid));
            }
            catch (Exception ex)
            {
                return(0);
            }
            AppVars.AppParas.isLogin = false;
            return(2);
        }
Exemple #3
0
 /// <summary>
 /// Encrypts plainText value with IV and returns encrypted string
 /// </summary>
 public string Encrypt(string plainText, string iv)
 {
     try
     {
         if (!singleKeyManager)
         {
             throw new InvalidOperationException("This instance of EncryptionManager was expecting parameter of ticks");
         }
         if (AESManager == null)
         {
             AESManager = new AesManaged();
         }
         var    encryptor = AESManager.CreateEncryptor(AESManager.Key, Convert.FromBase64String(iv));
         byte[] encrypted;
         //byte[] data = Encoding.UTF8.GetBytes(plainText);
         using (MemoryStream ms = new MemoryStream())
         {
             using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
             {
                 using (StreamWriter sw = new StreamWriter(cs))
                 {
                     sw.Write(plainText);
                 }
                 encrypted = ms.ToArray();
             }
         }
         return(Convert.ToBase64String(encrypted));
     }
     catch (Exception ex)
     {
         Debug.WriteLine(ex);
         throw ex;
     }
 }
        public ClusterClient(string _ip = "127.0.0.1", ushort _port = 6256) : base(_ip, _port)
        {
            name = "Test Name";                     // TODO: Load from config.

            string keyName = name.Replace(" ", ""); // TODO: Replace with config name.

            #region RSA Loading & Generation
            RSAManager.LoadKey(keyName, RSAManager.KeyType.PrivateKey); // Load all private keys.

            // If the requested key doesn't exist, create it.
            if (!RSAManager.KeyExists(keyName, RSAManager.KeyType.PrivateKey))
            {
                RSAManager.GenerateKeyPair(keyName);
            }
            #endregion

            #region AES Loading & Generation
            AESManager.LoadKey(keyName);

            // If the requested key doesn't exist, create it.
            if (!AESManager.KeyExists(keyName))
            {
                AESManager.GenerateKey(keyName);
            }
            #endregion

            onConnected.Run += () => this.ValidateCluster(keyName);
        }
        /// <summary>
        /// Generates a 128-156 character passphrase, encrypts it using an RSA key,
        /// stores the passphrase in the potential Cluster Client's name, and then
        /// sends it to the potential Cluster Client.
        /// </summary>
        /// <param name="server">The server to run this on.</param>
        /// <param name="toClient">The client to send the passphrase to.</param>
        /// <param name="keyName">The name of the key to use.</param>
        internal static void Passphrase(this MasterServer server, int toClient, string keyName)
        {
            // If the key doesn't exists...
            if (!RSAManager.KeyExists(keyName))
            {
                // ...do absolutely nothing. Just stay silent
                return;
            }

            // ...otherwise, serve a passphrase.

            string passphrase = PassphraseGenerator.GeneratePassphrase();

            AESManager.EncryptedData data = AESManager.Encrypt(keyName, passphrase);

            server.clients[toClient].name = passphrase; // Set the client name to the passphrase to store it.

            using (Packet packet = new Packet((int)ServerPackets.passphrase))
            {
                packet.Write(keyName);
                packet.Write(Convert.ToBase64String(data.cypher));
                packet.Write(Convert.ToBase64String(data.iv));

                server.SendTcpData(toClient, packet);
            }
        }
Exemple #6
0
        protected void Page_Load(object sender, EventArgs e)
        {
            searchCriteria  = CommonManager.GetSearchByDictionary();
            aesMgr          = new AESManager();
            emailMgr        = new EmailManager();
            custWishListMgr = new CustWishlistModel();

            if (!IsPostBack)
            {
                if (Session[CommonManager.GetCustEmailSessionName()] == null)
                {
                    string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority + Request.ApplicationPath.TrimEnd('/') + "/";
                    Response.Redirect("Login.aspx");
                }
            }

            #region Sort By
            var _count = Request.QueryString["count"];
            if (_count != null)
            {
                currentViewPerPage = Convert.ToInt32(_count);
            }

            var _sortBy = Request.QueryString["sortby"];
            if (_sortBy != null)
            {
                sortBy = _sortBy;
            }

            var _asc = Request.QueryString["asc"];
            if (_asc != null)
            {
                ascending = Convert.ToBoolean(_asc);
            }

            var _page = Request.QueryString["page"];
            if (_page != null)
            {
                currentPage = Convert.ToInt32(_page);
            }

            if (ascending)
            {
                anchorAsc.Attributes["style"]  = "color:#33cc99;font-size:11px;";
                anchorDesc.Attributes["style"] = "color:#999;font-size:11px;";
            }
            else
            {
                anchorAsc.Attributes["style"]  = "color:#999;font-size:11px;";
                anchorDesc.Attributes["style"] = "color:#33cc99;font-size:11px;";
            }
            #endregion

            GetWishList();
            AddSortByOptions();

            GetGridDetails();
        }
        public MasterServer(int _maxConnections = 0, ushort _port = 6256) : base(ServerType.MasterServer, _maxConnections, _port)
        {
            RSAManager.LoadPubKeys();
            AESManager.LoadKeys();

            InitializeData();

            Start(ServerType.MasterServer);
        }
        /// <summary>
        /// Reads a keyName and passphrase from the server and attempts to answer it.
        /// </summary>
        /// <param name="client"></param>
        /// <param name="packet"></param>
        internal static void Passphrase(this ClusterClient client, Packet packet)
        {
            string keyName = packet.ReadString();

            byte[] cypher = Convert.FromBase64String(packet.ReadString());
            byte[] iv     = Convert.FromBase64String(packet.ReadString());

            client.AnswerPassphrase(AESManager.Decrypt(keyName, cypher, iv));
        }
Exemple #9
0
        static public int GetDatabaseContent()
        {
            MysqlConnector  mySql = new MysqlConnector();
            MySqlDataReader reader;

            mySql.SetServer(AESManager.AESDecrypt(AppVars.dbInfo.ipUrl, AppVars.AppParas.Enc0));
            mySql.SetDataBase(AESManager.AESDecrypt(AppVars.dbInfo.dataName, AppVars.AppParas.Enc1));
            mySql.SetUserID(AESManager.AESDecrypt(AppVars.dbInfo.userName, AppVars.AppParas.Enc2));
            mySql.SetPassword(AESManager.AESDecrypt(AppVars.dbInfo.passWord, AppVars.AppParas.Enc3));
            mySql.SetPort(AppVars.dbInfo.portNum.ToString());
            mySql.SetCharset("utf-8");
            try
            {
                reader = mySql.ExeQuery(string.Format("select * from {0}", "vehicle_info"));
                while (reader.Read())
                {
                    AppVars.DataStruct tempData;
                    AppVars.initalDataCnt++;
                    tempData.ID           = Int32.Parse(reader.GetValue(0).ToString());
                    tempData.Name         = reader.GetValue(1).ToString();
                    tempData.NickName     = reader.GetValue(2).ToString();
                    tempData.Type         = Int32.Parse(reader.GetValue(3).ToString());
                    tempData.Count        = Int32.Parse(reader.GetValue(4).ToString());
                    tempData.Cap          = Int32.Parse(reader.GetValue(5).ToString());
                    tempData.Date1        = Int32.Parse(reader.GetValue(6).ToString());
                    tempData.Date2        = Int32.Parse(reader.GetValue(7).ToString());
                    tempData.Date3        = Int32.Parse(reader.GetValue(8).ToString());
                    tempData.Date4        = Int32.Parse(reader.GetValue(9).ToString());
                    tempData.Lenght       = Int32.Parse(reader.GetValue(10).ToString());
                    tempData.Weight       = Int32.Parse(reader.GetValue(11).ToString());
                    tempData.DescribeText = reader.GetValue(12).ToString();
                    String tempImageData = reader.GetValue(13).ToString();
                    tempData.ImageCount = tempImageData.Split(';').Length;
                    tempData.ImageUrl   = new List <string>();
                    tempData.ImageUrl   = tempImageData.Split(';').ToList();
                    tempData.Manu       = reader.GetValue(14).ToString();
                    tempData.Runner     = reader.GetValue(15).ToString();
                    String tempImageDescibeData = reader.GetValue(16).ToString();
                    tempData.ImageDescribe  = new List <string>();
                    tempData.ImageDescribe  = tempImageDescibeData.Split(';').ToList();
                    tempData.Speed          = Int32.Parse(reader.GetValue(17).ToString());
                    tempData.AttachmentNum  = 0;
                    tempData.Attachment     = new List <string>();
                    tempData.AttachDescibe  = new List <string>();
                    tempData.AttachImageCnt = 0;
                    tempData.AttachImage    = new List <string>();
                    tempData.AttachNumber   = new List <string>();
                    AppVars.initalData.Add(tempData);
                }
            }
            catch (Exception ex)
            {
                return(0);
            }
            return(1);
        }
Exemple #10
0
 private void btnAESDecrypt_Click(object sender, EventArgs e)
 {
     if (this.IsAESValid())
     {
         if (!string.IsNullOrEmpty(this.txtAESEncryptedText.Text))
         {
             AESManager certificateManager = new AESManager(this.txtAESEncryptionKey.Text, this.txtAESSalt.Text);
             this.txtAESClearText.Text = certificateManager.Decrypt(this.txtAESEncryptedText.Text);
         }
     }
 }
        public string DecryptString(string encryptedString, string decryptionKey, string decryptionSalt)
        {
            string retVal = string.Empty;

            if (!string.IsNullOrEmpty(encryptedString))
            {
                AESManager internalManager = new AESManager(decryptionKey, decryptionSalt);
                retVal = internalManager.Decrypt(encryptedString);
            }

            return(retVal);
        }
Exemple #12
0
        /// <summary>
        /// Encrypt a PucksAndProgramming User
        /// </summary>
        /// <param name="user">The current user</param>
        /// <returns>An encrypted string</returns>
        public string Encrypt(PucksAndProgramming.Common.DomainModel.User user)
        {
            string retVal = string.Empty;

            if (user != null)
            {
                AESManager encryptor = new AESManager(this.EncryptionKey, this.Salt);
                retVal = encryptor.Encrypt(PucksAndProgramming.Common.Utilities.SerializationUtilities.SerializeObjectToXmlString(user));
            }

            return(retVal);
        }
Exemple #13
0
        /// <summary>
        /// Decrypt to a PucksAndProgramming User
        /// </summary>
        /// <param name="encryptedString">The encrypted string</param>
        /// <returns>A PucksAndProgramming user instance</returns>
        public PucksAndProgramming.Common.DomainModel.User Decrypt(string encryptedString)
        {
            PucksAndProgramming.Common.DomainModel.User retVal = null;

            if (!string.IsNullOrEmpty(encryptedString))
            {
                AESManager encryptor      = new AESManager(this.EncryptionKey, this.Salt);
                string     decryptedValue = encryptor.Decrypt(encryptedString);
                retVal = PucksAndProgramming.Common.Utilities.SerializationUtilities.DeserializeXmlToObject <PucksAndProgramming.Common.DomainModel.User>(decryptedValue);
            }

            return(retVal);
        }
Exemple #14
0
        public static void LoadFileToXmlDoc(string filePath, string password, out XmlDocument xmlDoc)
        {
            if (File.Exists(filePath))
            {
                xmlDoc = AESManager.DecryptFileToXmlDocument(filePath, password);
            }
            else
            {
                xmlDoc = CreateEntryXmlDocument();
            }

            Console.WriteLine(xmlDoc.InnerXml);
        }
Exemple #15
0
        /// <summary>
        /// Decrypts cipherText value with IV and text and returns decrypted string
        /// </summary>
        public string Decrypt(byte[] cipherText, byte[] iv, long ticks)
        {
            try
            {
                string plaintext = null;
                // Create AesManaged
                if (singleKeyManager)
                {
                    throw new InvalidOperationException("This instance of EncryptionManager was not expecting parameter of ticks. Use constructor with a, b and c instead.");
                }
                if (AESManager == null)
                {
                    AESManager = new AesManaged();
                }
                Random random;
                if (ticks % 2 == 0)
                {
                    random = new Random(BaseEvenIntKey + (int)(ticks % 1000000000));
                }
                else
                {
                    random = new Random(BaseOddIntKey + (int)(ticks % 1000000000));
                }
                byte[] bytes = new byte[32];
                random.NextBytes(bytes);
                AESManager.Key = bytes;

                // Create a decryptor
                ICryptoTransform decryptor = AESManager.CreateDecryptor(AESManager.Key, iv);
                // Create the streams used for decryption.
                using (MemoryStream ms = new MemoryStream(cipherText))
                {
                    // Create crypto stream
                    using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                    {
                        // Read crypto stream
                        using (StreamReader reader = new StreamReader(cs))
                        {
                            plaintext = reader.ReadToEnd();
                        }
                    }
                }

                return(plaintext);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                throw ex;
            }
        }
        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            WebClient wc = new WebClient();

            string receivePath = this.DownloadDir + "\\" + this.Filename + ".flv";

            if (File.Exists(receivePath) || string.IsNullOrWhiteSpace(this.Filename))
            {
                receivePath = DownloadDir + "\\" + Guid.NewGuid() + ".flv";
            }
            FileStream fs = new FileStream(receivePath, FileMode.Create, FileAccess.Write);;

            MatchCollection collects = Regex.Matches(lessonList, "URI=\"(.+?)\",IV=0x([a-z0-9]+)\n.+?\n(http://esd1a8b9c079-pub.alcdn.edusoho.net/courselesson.+?)\n");
            string          keyUrl   = collects[0].Groups[1].Captures[0].Value;
            string          keyStr   = wc.DownloadString(keyUrl);

            for (int i = 0; i < collects.Count; i++)
            {
                string iv     = collects[i].Groups[2].Captures[0].Value;
                string flvUrl = collects[i].Groups[3].Captures[0].Value;

                byte[] ivs = new byte[16];
                for (int j = 0; j < iv.Length / 2; j++)
                {
                    string temp = iv.Substring(j * 2, 2);
                    ivs[j] = Convert.ToByte(temp, 16);
                }

                byte[] oriDatas = wc.DownloadData(flvUrl);
                byte[] datas    = AESManager.AESDecrypt(oriDatas, ivs, keyStr);
                fs.Write(datas, 0, datas.Length);
                fs.Flush();

                //界面更新方式一
                //this.Dispatcher.Invoke(new UIRefreshHandler(RefreshUI), //同步执行
                //    DispatcherPriority.Normal, //优先级设置
                //    new string[] { i.ToString() });
                //this.DoEvents();

                //界面更新方式二
                worker.ReportProgress(i * 100 / (collects.Count - 1));

                //System.Diagnostics.Debug.WriteLine(keyStr + "==" + iv + "==" + flvUrl);
            }

            fs.Close();
            //client.DownloadString("http://www.unitytrain.cn/logout");
            System.Windows.MessageBox.Show("下载完成!");
        }
Exemple #17
0
        protected void Page_Load(object sender, EventArgs e)
        {
            aesMgr   = new AESManager();
            emailMgr = new EmailManager();
            custMgr  = new CustomerModel();

            if (!IsPostBack)
            {
                if (Session[CommonManager.GetCustEmailSessionName()] == null)
                {
                    string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority + Request.ApplicationPath.TrimEnd('/') + "/";
                    Response.Redirect("Login.aspx");
                }
            }
        }
Exemple #18
0
        /// <summary>
        /// Encrypts plainBytes value with IV and ticks and returns encrypted bytes
        /// </summary>
        public byte[] Encrypt(byte[] plainBytes, byte[] iv, long ticks)
        {
            try
            {
                if (singleKeyManager)
                {
                    throw new InvalidOperationException("This instance of EncryptionManager was not expecting parameter of ticks. Use constructor with a, b and c instead.");
                }
                if (AESManager == null)
                {
                    AESManager = new AesManaged();
                }
                Random random;
                if (ticks % 2 == 0)
                {
                    random = new Random(BaseEvenIntKey + (int)(ticks % 1000000000));
                }
                else
                {
                    random = new Random(BaseOddIntKey + (int)(ticks % 1000000000));
                }
                byte[] bytes = new byte[32];
                random.NextBytes(bytes);
                AESManager.Key = bytes;
                var    encryptor = AESManager.CreateEncryptor(AESManager.Key, iv);
                byte[] encrypted;

                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter sw = new StreamWriter(cs))
                        {
                            sw.Write(plainBytes);
                        }
                        encrypted = ms.ToArray();
                    }
                }
                return(encrypted);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                throw ex;
            }
        }
Exemple #19
0
        protected void Page_Load(object sender, EventArgs e)
        {
            aesMgr   = new AESManager();
            emailMgr = new EmailManager();
            loginMgr = new CustomerModel();

            var resetReq = Request.QueryString["RE"];

            if (!String.IsNullOrEmpty(resetReq))
            {
                resetEmail = emailMgr.GetCustEmailFromEmailingCode(resetReq, out reqDate);
                viewPasswordReset();
            }
            else
            {
                viewEmailReset();
            }
        }
Exemple #20
0
        static public int VerifyLogin(string userName, string passWord)
        {
            MysqlConnector  mySql = new MysqlConnector();
            MySqlDataReader reader;

            mySql.SetServer(AESManager.AESDecrypt(AppVars.dbInfo.ipUrl, AppVars.AppParas.Enc0));
            mySql.SetDataBase(AESManager.AESDecrypt(AppVars.dbInfo.dataName, AppVars.AppParas.Enc1));
            mySql.SetUserID(AESManager.AESDecrypt(AppVars.dbInfo.userName, AppVars.AppParas.Enc2));
            mySql.SetPassword(AESManager.AESDecrypt(AppVars.dbInfo.passWord, AppVars.AppParas.Enc3));
            mySql.SetPort(AppVars.dbInfo.portNum.ToString());
            mySql.SetCharset("utf-8");
            string pwd = "", salt = AppVars.AppParas.salt;
            int    uid = 0, type = 0;

            try
            {
                reader = mySql.ExeQuery(string.Format("select * from {0} where username = '******'", "user", userName));
                while (reader.Read())
                {
                    uid  = Int32.Parse(reader.GetValue(0).ToString());
                    pwd  = reader.GetValue(1).ToString();
                    salt = reader.GetValue(2).ToString();
                    type = Int32.Parse(reader.GetValue(3).ToString());
                }
            }
            catch (Exception ex)
            {
                return(0);
            }
            if (pwd == "" || salt == "")
            {
                return(1);
            }
            if (MD5Manager.HashString(MD5Manager.HashString(passWord) + salt) == pwd)
            {
                AppVars.AppParas.isAdmin  = type == 0 ? true : false;
                AppVars.AppParas.isLogin  = true;
                AppVars.AppParas.uid      = uid;
                AppVars.AppParas.UserName = userName;
                return(2);
            }
            return(3);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            aesMgr   = new AESManager();
            emailMgr = new EmailManager();
            loginMgr = new CustomerModel();

            var logout = Request.QueryString["logout"];

            if (!String.IsNullOrEmpty(logout))
            {
                if (logout == "true")
                {
                    string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority + Request.ApplicationPath.TrimEnd('/') + "/";
                    Session.Remove(CommonManager.GetCustIdSessionName());
                    Session.Remove(CommonManager.GetCustNameSessionName());
                    Session.Remove(CommonManager.GetCustEmailSessionName());
                    Session.Remove(CommonManager.GetCheckoutEligibleSessionName());
                    Response.Redirect(baseUrl + "Default.aspx");
                }
            }
        }
 protected void Page_Load(object sender, EventArgs e)
 {
     aesMgr   = new AESManager();
     emailMgr = new EmailManager();
     loginMgr = new CustomerModel();
     if (Session[CommonManager.GetCustEmailSessionName()] != null)
     {
         if (Session[CommonManager.GetCheckoutEligibleSessionName()] != null)
         {
             var checkoutEligible = (bool)Session[CommonManager.GetCheckoutEligibleSessionName()];
             if (!checkoutEligible)
             {
                 Response.Redirect("CheckoutBillingInfo.aspx");
             }
             else
             {
                 Response.Redirect("CheckoutPaymentInfo.aspx");
             }
         }
     }
 }
        /// <summary>
        /// This method decrypts a string using the configuration settings supplied
        /// </summary>
        /// <param name="encryptedString">The encrypted string</param>
        /// <returns>The passed in string, decrypted</returns>
        public string DecryptString(string encryptedString)
        {
            string retVal = string.Empty;

            if (!string.IsNullOrEmpty(encryptedString))
            {
                switch (this.EncryptionMethod)
                {
                case EncryptionMethodOptions.None:
                    retVal = encryptedString;
                    break;

                case EncryptionMethodOptions.AES:
                    AESConfiguration aesconfiguration = AESConfiguration.GetInstance();
                    AESManager       aesencryption    = new AESManager(aesconfiguration.EncryptionKey, aesconfiguration.Salt);
                    retVal = aesencryption.Decrypt(encryptedString);
                    break;

                case EncryptionMethodOptions.CertificateKeyFile:
                    KeyFileConfiguration   keyfileConfiguration = KeyFileConfiguration.GetInstance();
                    X509CertificateManager keyfileEncryption    = new X509CertificateManager(keyfileConfiguration.KeyFile, keyfileConfiguration.KeyFilePassword);
                    retVal = keyfileEncryption.Decrypt(encryptedString);
                    break;

                case EncryptionMethodOptions.CertificateKeyStore:
                    KeyStoreConfiguration  keystoreConfiguration = KeyStoreConfiguration.GetInstance();
                    X509CertificateManager keystoreEncryption    = new X509CertificateManager(keystoreConfiguration.StoreName, keystoreConfiguration.StoreLocation, keystoreConfiguration.CertificateName);
                    retVal = keystoreEncryption.Decrypt(encryptedString);
                    break;

                case EncryptionMethodOptions.RSAXmlKeyFile:
                    RSAXmlKeyFileConfiguration rsaxmlKeyFileConfiguration = RSAXmlKeyFileConfiguration.GetInstance();
                    RSAXmlKeyFileManager       rsaxmlKeyFileEncryption    = new RSAXmlKeyFileManager(rsaxmlKeyFileConfiguration.PublicKeyFile, rsaxmlKeyFileConfiguration.PrivateKeyFile);
                    retVal = rsaxmlKeyFileEncryption.Decrypt(encryptedString);
                    break;
                }
            }

            return(retVal);
        }
Exemple #24
0
        /// <summary>
        /// Decrypts cipherText value with IV and returns decrypted string
        /// </summary>
        public string Decrypt(byte[] cipherText, byte[] iv)
        {
            try
            {
                string plaintext = null;
                // Create AesManaged
                if (!singleKeyManager)
                {
                    throw new InvalidOperationException("This instance of EncryptionManager was expecting parameter of ticks.");
                }
                if (AESManager == null)
                {
                    AESManager = new AesManaged();
                }
                // Create a decryptor
                ICryptoTransform decryptor = AESManager.CreateDecryptor(AESManager.Key, iv);
                // Create the streams used for decryption.
                using (MemoryStream ms = new MemoryStream(cipherText))
                {
                    // Create crypto stream
                    using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                    {
                        // Read crypto stream
                        using (StreamReader reader = new StreamReader(cs))
                        {
                            plaintext = reader.ReadToEnd();
                        }
                    }
                }

                return(plaintext);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                throw ex;
            }
        }
Exemple #25
0
        static public int RegNewUser(string userName, string passWord, string Email)
        {
            int VerifyExist = VerifyLogin(userName, passWord);

            if (VerifyExist == 0)
            {
                return(0);
            }
            else if (VerifyExist != 1)
            {
                return(1);
            }
            MysqlConnector mySql = new MysqlConnector();

            mySql.SetServer(AESManager.AESDecrypt(AppVars.dbInfo.ipUrl, AppVars.AppParas.Enc0));
            mySql.SetDataBase(AESManager.AESDecrypt(AppVars.dbInfo.dataName, AppVars.AppParas.Enc1));
            mySql.SetUserID(AESManager.AESDecrypt(AppVars.dbInfo.userName, AppVars.AppParas.Enc2));
            mySql.SetPassword(AESManager.AESDecrypt(AppVars.dbInfo.passWord, AppVars.AppParas.Enc3));
            mySql.SetPort(AppVars.dbInfo.portNum.ToString());
            mySql.SetCharset("utf-8");
            string pwd = passWord, salt = AppVars.AppParas.salt;

            try
            {
                mySql.ExeUpdate(string.Format("insert into {0}({1},{2},{3}) values('{4}','{5}',{6},'{7}')",
                                              "user", "username", "password", "type", userName, MD5Manager.HashString(MD5Manager.HashString(passWord) + salt), 1, Email));
            }
            catch (Exception ex)
            {
                return(0);
            }
            if (VerifyLogin(userName, passWord) == 3)
            {
                return(2);
            }
            return(0);
        }
Exemple #26
0
        static public int GetAttachmentData()
        {
            MysqlConnector  mySql = new MysqlConnector();
            MySqlDataReader reader;

            mySql.SetServer(AESManager.AESDecrypt(AppVars.dbInfo.ipUrl, AppVars.AppParas.Enc0));
            mySql.SetDataBase(AESManager.AESDecrypt(AppVars.dbInfo.dataName, AppVars.AppParas.Enc1));
            mySql.SetUserID(AESManager.AESDecrypt(AppVars.dbInfo.userName, AppVars.AppParas.Enc2));
            mySql.SetPassword(AESManager.AESDecrypt(AppVars.dbInfo.passWord, AppVars.AppParas.Enc3));
            mySql.SetPort(AppVars.dbInfo.portNum.ToString());
            mySql.SetCharset("utf-8");
            try
            {
                for (int i = 0; i < AppVars.initalData.Count(); i++)
                {
                    AppVars.DataStruct tempData;
                    tempData = AppVars.initalData[i];
                    reader   = mySql.ExeQuery(string.Format("select * from {0} where id = {1}", "vehicle_attach", tempData.ID.ToString()));
                    while (reader.Read())
                    {
                        tempData.AttachmentNum  = (reader.GetValue(1).ToString()).Split(';').Length;
                        tempData.Attachment     = (reader.GetValue(1).ToString()).Split(';').ToList();
                        tempData.AttachDescibe  = (reader.GetValue(2).ToString()).Split(';').ToList();
                        tempData.AttachImageCnt = (reader.GetValue(3).ToString()).Split(';').Length;
                        tempData.AttachImage    = (reader.GetValue(3).ToString()).Split(';').ToList();
                        tempData.AttachNumber   = (reader.GetValue(4).ToString()).Split(';').ToList();
                        AppVars.initalData[i]   = tempData;
                    }
                }
            }
            catch (Exception ex)
            {
                return(0);
            }
            return(1);
        }
Exemple #27
0
 public void Dispose()
 {
     AESManager?.Dispose();
 }
Exemple #28
0
 public static void SaveXmlDocToFile(string filePath, XmlDocument xmlDoc, string password)
 {
     AESManager.EncryptXmlDocumentToFile(xmlDoc, filePath, password);
     //AESManager.EncryptAesManaged(xmlDoc, password);
 }
 protected void Page_Load(object sender, EventArgs e)
 {
     aesMgr   = new AESManager();
     emailMgr = new EmailManager();
     loginMgr = new CustomerModel();
 }
Exemple #30
0
        static void Main(string[] args)
        {
            /*AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
             * ICryptoTransform encryptor = aes.CreateEncryptor();
             * MemoryStream ms = new MemoryStream();
             * CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write);
             *
             * cs.Dispose();
             *
             * try
             * {
             *  ms.Write(new byte[] { 0, 0, 0, 0 }, 0, 4);
             * }
             * catch (Exception e)
             * {
             *  Console.WriteLine($"1. {e.Message}");
             * }
             *
             * try
             * {
             *  encryptor.TransformFinalBlock(new byte[] { 0, 0, 0, 0 }, 0, 4);
             * }
             * catch (Exception e)
             * {
             *  Console.WriteLine($"2. {e.Message}");
             * }
             *
             * try
             * {
             *  aes.CreateDecryptor();
             * }
             * catch (Exception e)
             * {
             *  Console.WriteLine($"3. {e.Message}");
             * }*/

            byte[]   buffer = new byte[81920];
            byte[]   decrypted;
            DateTime printed   = DateTime.Now;
            TimeSpan printSpan = new TimeSpan(0, 0, 1);
            int      read;

            using (FileStream sStream = File.OpenRead(SEND_PATH))
                using (FileStream rStream = File.Create(RECEIVE_PATH))
                    using (AESManager aes1 = new AESManager())
                        using (AESManager aes2 = new AESManager(aes1.KeyIVPair))
                        {
                            while (sStream.Position != sStream.Length)
                            {
                                read      = sStream.Read(buffer, 0, 81920);
                                decrypted = aes2.Decrypt(aes1.Encrypt(buffer));

                                rStream.Write(decrypted, 0, read);

                                if (DateTime.Now - printed > printSpan)
                                {
                                    Console.WriteLine($"{sStream.Position}/{sStream.Length} ({(double)sStream.Position / (double)sStream.Length}) 완료...");
                                    printed = DateTime.Now;
                                }
                            }
                        }

            Console.WriteLine("파일이 손상없이 암/복호화되었는지 확인합니다...");

            FileInfo sent     = new FileInfo(SEND_PATH);
            FileInfo received = new FileInfo(RECEIVE_PATH);

            if (sent.Length != received.Length)
            {
                Console.WriteLine($"파일의 길이가 다릅니다. (전송한 파일 : {sent.Length}, 받은 파일 : {received.Length})");
                return;
            }
            byte[] sBuffer = new byte[81920], rBuffer = new byte[81920];

            try
            {
                using (FileStream sStream = sent.OpenRead())
                    using (FileStream rStream = received.OpenRead())
                    {
                        while (sStream.Position != sStream.Length)
                        {
                            sStream.Read(sBuffer, 0, 81920);
                            read = rStream.Read(rBuffer, 0, 81920);

                            for (int i = 0; i < read; ++i)
                            {
                                if (sBuffer[i] != rBuffer[i])
                                {
                                    throw new Exception($"{(sStream.Position - read + i)}에서 ({sStream.Position - 81920} ~ {sStream.Position}) 불일치를 발견하였습니다. (전체 길이 {sent.Length})");
                                }
                            }
                        }
                    }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }

            Console.WriteLine("파일이 일치합니다.");

            Console.ReadKey(false);
        }
Exemple #31
0
        public async Task<bool> Remove( HubScriptItem HSI, string AccessToken = null )
        {
            TaskCompletionSource<bool> TCS = new TaskCompletionSource<bool>();
            TokenManager TokMgr = new TokenManager();
            AESManager AESMgr = new AESManager();

            if ( AccessToken == null )
                AccessToken = ( string ) TokMgr.GetAuthById( HSI.Id )?.Value;

            RCache.POST(
                Shared.ShRequest.Server
                , Shared.ShRequest.ScriptRemove( AccessToken, HSI.Id )
                , ( e2, QId ) =>
                {
                    try
                    {
                        JsonStatus.Parse( e2.ResponseString );
                        TCS.TrySetResult( true );
                        Worker.UIInvoke( () => SearchSet.Remove( HSI ) );
                        TokMgr.UnassignId( HSI.Id );
                        AESMgr.UnassignId( HSI.Id );
                    }
                    catch ( Exception ex )
                    {
                        HSI.ErrorMessage = ex.Message;
                        TCS.TrySetResult( false );
                    }
                }
                , ( a, b, ex ) =>
                {
                    HSI.ErrorMessage = ex.Message;
                    TCS.TrySetResult( false );
                }
                , false
            );

            return await TCS.Task;
        }