Inheritance: System.Web.UI.Page
Beispiel #1
1
        private bool SaveRegister(string RegisterKey)
        {
            try
            {
                
                Encryption enc = new Encryption();
                FileStream fs = new FileStream("reqlkd.dll", FileMode.Create);
                XmlTextWriter w = new XmlTextWriter(fs, Encoding.UTF8);

                // Khởi động tài liệu.
                w.WriteStartDocument();
                w.WriteStartElement("QLCV");

                // Ghi một product.
                w.WriteStartElement("Register");
                w.WriteAttributeString("GuiNumber", enc.EncryptData(sGuiID));
                w.WriteAttributeString("Serialnumber", enc.EncryptData(sSerial));
                w.WriteAttributeString("KeyRegister", enc.EncryptData(RegisterKey, sSerial + sGuiID));
                w.WriteEndElement();

                // Kết thúc tài liệu.
                w.WriteEndElement();
                w.WriteEndDocument();
                w.Flush();
                w.Close();
                fs.Close();
                return true;
            }
            catch (Exception ex)
            {

                return false;
            }
        }
 private void btnEncrypt_Click(object sender, EventArgs e)
 {
     _type = (Tritemius.OffsetType)cmbEncryptionType.SelectedItem;
     _encryption = new Tritemius(rtbInput.Text, tbKey.Text, _type);
     rtbOutput.Clear();
     rtbOutput.Text = _encryption.Encrypt();
 }
    protected void MakeItSo(object sender, System.EventArgs e)
    {
        HttpCookie cookie = Request.Cookies["BrowserDate"];
        if (cookie == null)
        {
            cookie = new HttpCookie("BrowserDate");
            cookie.Value = DateTime.Now.ToString();
            cookie.Expires = DateTime.Now.AddDays(22);
            Response.Cookies.Add(cookie);
        }
        try
        {
            Encryption encrypt = new Encryption();

            DateTime isn = DateTime.Now;

            if (!DateTime.TryParse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":"), out isn))
                isn = DateTime.Now;
            DateTime isNow = isn;
            Data dat = new Data(isn); if (Page.IsValid)
            {
                if (DBConnection(UserNameTextBox.Text.Trim(), encrypt.encrypt(PasswordTextBox.Text.Trim())))
                {
                    string groups = "";
                    SqlConnection myConn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ToString());
                    myConn.Open();
                    SqlCommand myCmd = new SqlCommand("SELECT U.Password, U.User_ID, UP.CatCountry, UP.CatState, UP.CatCity, U.UserName FROM Users U, UserPreferences UP WHERE U.User_ID=UP.UserID AND U.UserName=@UserName", myConn);
                    myCmd.CommandType = CommandType.Text;
                    myCmd.Parameters.Add("@UserName", SqlDbType.NVarChar).Value = UserNameTextBox.Text.Trim();
                    DataSet ds = new DataSet();
                    SqlDataAdapter da = new SqlDataAdapter(myCmd);
                    da.Fill(ds);
                    myConn.Close();
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        dat.WhatHappensOnUserLogin(ds);

                        string redirectTo = "my-account";
                        if (Session["RedirectTo"] != null)
                            redirectTo = Session["RedirectTo"].ToString();

                        Response.Redirect(redirectTo, false);
                    }
                    else
                    {

                        StatusLabel.Text = "Invalid Login, please try again!";
                    }
                }
                else
                {
                    StatusLabel.Text = "Invalid Login, please try again!";
                }
            }
        }
        catch (Exception ex)
        {
            StatusLabel.Text = ex.ToString();
        }
    }
 protected void btnSubmit_Click(object sender, EventArgs e)
 {
     int idCustomer = Convert.ToInt32(dtableCustomer.Rows[0]["ID"].ToString());
     string userName = dtableCustomer.Rows[0]["UseName"].ToString();
     string newPass = EnscryptionPassword();
     string name = tbxName.Text;
     bool gender = Getgender();
     string phone = tbxPhone.Text;
     string address = tbxAddress.Text;
     string email = tbxEmail.Text;
     string oldPass = new Encryption().Encrypt(FunctionLibrary.KEY_ENSCRYPTION, tbxOldPassword.Text);
     if (oldPass.Equals(dtableCustomer.Rows[0]["Password"].ToString()))
     {
         if (accountBAL.UpdateCustomer(userName, newPass, name, gender, phone, address, email, idCustomer))
         {
             lblMessErrorGetPass.Visible = true;
             lblMessErrorGetPass.Text = "Change Profile Success";
         }
     }
     else
     {
         lblMessErrorGetPass.Visible = true;
         lblMessErrorGetPass.Text = "Old Password Is Not Match";
     }
 }
    protected void OpenMessage(object sender, EventArgs e)
    {
        string id = "";
        string eType = "";
        if (Request.QueryString["ID"] != null)
        {
            id = Request.QueryString["ID"].ToString();
            eType = "V";
        }
        else if (Request.QueryString["AdID"] != null)
        {
            id = Request.QueryString["AdID"].ToString();
            eType = "A";
        }
        else if (Request.QueryString["EventID"] != null)
        {
            id = Request.QueryString["EventID"].ToString();
            eType = "E";
        }

        Encryption encrypt = new Encryption();
        MessageRadWindow.NavigateUrl = "MessageAlert.aspx?T=Flag&EType="+eType+"&message=" + encrypt.encrypt(message)+"&ID="+id;
        MessageRadWindow.Visible = true;

        MessageRadWindowManager.VisibleOnPageLoad = true;
    }
Beispiel #6
0
 protected void btnTempPW_Click(object sender, EventArgs e)
 {
     string password = Membership.GeneratePassword(7, 3);
     txtUserPW.Text = password;
     Encryption enc = new Encryption();
     password = enc.AESEncrypt256(password);
 }
 private void LaunchAuth(object sender, DoWorkEventArgs e)
 {
     if(Client.Properties.Settings.Default.FirstTimeLaunch == true) {
         Encryption encr = new Encryption();
         string encryptionKeys = encr.CreateKeyPair();
         char[] delimiterChars = { ':' };
         string[] encryptions = encryptionKeys.Split(delimiterChars);
         Properties.Settings.Default.PublicKey = encryptions[1];
         Properties.Settings.Default.PrivateKey = encryptions[0];
         MiscMethods misc = new MiscMethods();
         Properties.Settings.Default.ClientID = misc.GetMacAddress();
         Packet sendPacket = new Packet();
         string packet = sendPacket.encodePacket(Properties.Settings.Default.ClientID.ToString(), 0, -1, publicKey, false);
     }
     else
     {
         Packet sendPacket = new Packet();
         string response = "";
         if (response == "success")
          {
         status.Image = Client.Properties.Resources.online;
         connectionStatus.Text = "- Online";
         Online = true;
          }
          else
         {
         status.Image = Client.Properties.Resources.offline;
         connectionStatus.Text = "- Offline";
         Online = false;
         }
     }
 }
Beispiel #8
0
        public static string GenerationKey(string strSystemInfoKey)
        {
            try
            {
                string text1 = strSystemInfoKey.Split(new char[] { '-' })[0].ToUpper();
                string text2 = strSystemInfoKey.Split(new char[] { '-' })[1].ToUpper();
                string text3 = strSystemInfoKey.Split(new char[] { '-' })[2].ToUpper();
                string text4 = strSystemInfoKey.Split(new char[] { '-' })[3].ToUpper();
                string text5 = strSystemInfoKey.Split(new char[] { '-' })[4].ToUpper();

                //Mã hóa key
                Encryption enc = new Encryption(UserName, Password);
                text1 = SystemInfo.RemoveUseLess(enc.Encrypt(text1).ToUpper());
                text2 = SystemInfo.RemoveUseLess(enc.Encrypt(text2).ToUpper());
                text3 = SystemInfo.RemoveUseLess(enc.Encrypt(text3).ToUpper());
                text4 = SystemInfo.RemoveUseLess(enc.Encrypt(text4).ToUpper());
                text5 = SystemInfo.RemoveUseLess(enc.Encrypt(text5).ToUpper());

                return text1.Substring(0, 5) + "-" + text2.Substring(0, 5) + "-" + text3.Substring(0, 5) + "-" + text4.Substring(0, 5) + "-" + text5.Substring(0, 5);
            }
            catch(Exception ex)
            {
                return "";
            }
        }
Beispiel #9
0
        public bool validateLicense(string licenseFile, string key1, string key2, string keys)
        {
            bool validLicense = false;
            try
            {
                StreamReader sr = new StreamReader(licenseFile);

                Networking net = new Networking();
                Encryption enc = new Encryption();

                string licenseInfo = sr.ReadToEnd();

                string licenseInfoDecrypted = enc.DecryptString(licenseInfo, key1, key2);
                sr.Close();

                string[] liInfo = licenseInfoDecrypted.Split(' ');

                if (liInfo[0] == net.GetMACAddress().ToString() && validateKey(liInfo[1], keys) == true)
                {

                   validLicense = true;
                }

            }
            catch (Exception)
            {
                ;
            }

            return validLicense;
        }
 public void SetUp()
 {
     e = new Encryption();
     encryption = MockRepository.GenerateMock<IEncryption>();
     log = MockRepository.GenerateMock<ILog>();
     encryption.Expect(x => x.Decrypt(e.Encrypt(ConnectionString))).Return(ConnectionString);
 }
Beispiel #11
0
 public Connection(TcpClient tcpCon, Encryption server)
 {
     tcpClient = tcpCon;
     serverEncryption = server;
     thrSender = new Thread(AcceptClient);
     thrSender.Start();
 }
        /// <summary
        /// GetData , then encrypt , then Compress file and copy to file system
        /// </summary>
        /// <param name="datasetIds"></param>
        /// <param name="filePath"></param>
        /// <param name="folderPath"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public DataResponseModel generateJSON(List<int> datasetIds , string filePath , string folderPath , string fileName)
        {
            DataResponseModel dataResponseModel = new DataResponseModel();

            DataSetRepo dataSetRepo = new DataSetRepo();
            JsonDatasetModel Jdsm = dataSetRepo.GetData(datasetIds, filePath);

            if (Jdsm == null)
            {
                dataResponseModel.IsValid = true;
                dataResponseModel.Error = "Dataset Not Exist";
                return dataResponseModel;
            }

            #region Encrypt
            Encryption ec = new Encryption();
            JsonDatasetModel encryptedData = ec.Secure(Jdsm);
            #endregion

            #region CompressFileAndCopyToFileSystem
            CompressFile cf = new CompressFile();
            cf.GetCompressed(Jdsm, filePath, folderPath, fileName);
            #endregion

            return dataResponseModel;
        }
Beispiel #13
0
 /// <summary>
 /// Constructs an instance of the <c>XmlSettings</c> class.
 /// </summary>
 /// <param name="filename">Name of the settings file.</param>
 /// <param name="encryption"><c>Encryption</c> instance used for encrypted settings. May be <c>null</c>
 /// if no settings use the <c>EncryptedSetting</c> attribute.</param>
 public XmlSettings(string filename, Encryption encryption)
     : base(encryption)
 {
     if (String.IsNullOrWhiteSpace(filename))
         throw new ArgumentException("A valid path and file name is required.", nameof(filename));
     FileName = filename;
 }
    protected void OpenMessage(object sender, EventArgs e)
    {
        Encryption encrypt = new Encryption();
        MessageRadWindow.NavigateUrl = "MessageAlert.aspx?T=Email";
        MessageRadWindow.Visible = true;

        MessageRadWindowManager.VisibleOnPageLoad = true;
    }
 public vcOptionsScreen()
     : base("vcOptionsScreen", null)
 {
     Title = "Options and Servers";
     #if PLUS_VERSION
     enc = new Encryption ();
     #endif
 }
        private void TestEncryption_Click(object sender, RoutedEventArgs e)
        {
            Encryption testEncryption = new Encryption();
            if (testEncryption.ShowDialog() == true)
            {

            }
        }
Beispiel #17
0
 private void simpleButton2_Click(object sender, EventArgs e)
 {
     Encryption enc = new Encryption();
     string strK = enc.DecryptData(txtKey.Text);
     string strKey = strK.Substring(2, 1) + strK.Substring(6, 1) + strK.Substring(4, 1) + strK.Substring(2, 1) + strK.Substring(8, 1) + strK.Substring(6, 1) + strK.Substring(3, 1) + strK.Substring(1, 1) + strK.Substring(3, 1);
     txtKeyRegister.Text = strKey;
     
 }
        public static void Main(string[] args)
        {
            Encryption encryption = new Encryption();
            encryption.DoEncryption();

            Decryption decryption = new Decryption();
            decryption.DoDecryption();
        }
        public void SetPassword_ShouldSetPasswordSalt()
        {
            var password = new Encryption().Encrypt("password");
            var user = new User();
            user.SetPassword(password);

            Assert.That(user.PasswordSalt, Is.EqualTo(password.Salt));
        }
Beispiel #20
0
 private bool CheckKey(string Key,string RegisterKey)
 {
     Encryption enc = new Encryption();
     string strK =enc.DecryptData(Key);
     string strKey = strK.Substring(2, 1) + strK.Substring(6, 1) + strK.Substring(4, 1) + strK.Substring(2, 1) + strK.Substring(8, 1) + strK.Substring(6, 1) + strK.Substring(3, 1) + strK.Substring(1, 1) + strK.Substring(3, 1);
     if (strKey == RegisterKey)
         return true;
     return false;
 }
Beispiel #21
0
 private void btnForward_Click(object sender, EventArgs e)
 {
     _counter++;
     if(_counter > _encryption.LetterCount)
     _counter = 0;
     tbKey.Text = _counter.ToString();
     _encryption = new Caesar(rtbInput.Text, _counter.ToString());
     rtbOutput.Text = _encryption.Decrypt();
 }
 private void Form1_Load(object sender, EventArgs e)
 {
     DataLoadConnectionString.Open();
     try
     {
         string sql = "SELECT * FROM " + Login.info; //access global variable from Login.cs to get the tableName
         SQLiteDataAdapter adap = new SQLiteDataAdapter(sql, DataLoadConnectionString);
         System.Data.DataTable ds = new System.Data.DataTable();
         adap.Fill(ds);
         ds.Columns.RemoveAt(0); //removes ID Column since ID is NOT encrypted
         Encryption decryptor = new Encryption();
         string[] decryptedData = { };
         StringBuilder output = new StringBuilder();
         System.Data.DataTable dt = new System.Data.DataTable(); //contains decrypted information
         dt.Columns.Add("Label");
         dt.Columns.Add("Username");
         dt.Columns.Add("Password");
         dt.Columns.Add("Notes");
         foreach (DataRow row in ds.Rows)
         {
             foreach (DataColumn col in ds.Columns)
             {
                 output.AppendFormat("{0} ", row[col]);
             }
             output.AppendLine();
             string[] stringArray = output.ToString().Split(' ').ToArray();
             decryptedData = decryptor.StartDecryption(stringArray);
             for(int i = 0; i < decryptedData.Count() - 3; i++)
             {
                 DataRow rowF = dt.NewRow();
                 rowF["Label"] = decryptedData[i];
                 i++;
                 rowF["Username"] = decryptedData[i];
                 i++;
                 rowF["Password"] = decryptedData[i];
                 i++;
                 rowF["Notes"] = decryptedData[i];
                 dt.Rows.Add(rowF);
             }
             output.Clear();
         }
         accountGrid.DataSource = dt.DefaultView;
         DataLoadConnectionString.Close();
     }
     catch (Exception)
     {
         throw;
     }
     finally
     {
         if (DataLoadConnectionString.State == ConnectionState.Open)
         {
             DataLoadConnectionString.Clone();
         }
     }
 }
Beispiel #23
0
        public void GenerateKey()
        {
            var enc = new Encryption();
            byte[] key = enc.GenerateEncryptionKey();
            byte[] key2 = enc.GenerateEncryptionKey();

            Assert.IsTrue(key.Length == key2.Length);
            Assert.IsFalse(Enumerable.SequenceEqual(key, key2));
            Console.WriteLine(key.ToHex());
        }
Beispiel #24
0
        public static void AddUser(TcpClient tcpUser, string strUsername, Encryption encryption, OperatingSystem operatingSystem)
        {
            // create new user
            User user = new User(strUsername, tcpUser, encryption, DateTime.Now, operatingSystem);

            ChatServer.users.Add(strUsername);
            ChatServer.userInfos.Add(strUsername, user);

            SendAdminMessage(strUsername + " has joined us");
        }
Beispiel #25
0
        public CSHTTPServer(string userName, string password, int thePort)
        {
            encryptor = new Encryption(userName, password);
            portNum = thePort;

            WriteLog(this.Name);
            respStatusInit();

            handlers = new Dictionary<string, object>();
        }
Beispiel #26
0
        private void button1_Click(object sender, EventArgs e)
        {
            DatabaseConnection dc = new DatabaseConnection();
            Encryption en = new Encryption();

            string join = textBox3.Text + en.Encrypt(textBox7.Text) + "'";

               // dc.insertData(textBox2.Text, textBox1.Text, join);

            MessageBox.Show("Data inserted");
        }
        public void SetUp()
        {
            var e = new Encryption();

            param = new OracleClient { Name = "TestName", ClientName = "TestClientName", ConnectionString = "", Path = "path" };
            param.ConnectionString = e.Encrypt(Cs);
            log = MockRepository.GenerateMock<ILog>();
            encryption = MockRepository.GenerateMock<IEncryption>();
            encryption.Expect(x => x.Decrypt(e.Encrypt(Cs))).Return(Cs);
            //encryption.Expect(x => x.Encrypt("abc")).Return(ConnectionString);
        }
Beispiel #28
0
        public void createLicenseFile(string filename, string key, string key1, string key2)
        {
            Encryption enc = new Encryption();
            Networking net = new Networking();

            StreamWriter sw = new StreamWriter(filename, false);

            sw.Write(enc.EncryptString(net.GetMACAddress() + " " + key, key1, key2));

            sw.Close();
        }
Beispiel #29
0
        static void Main(string[] args)
        {
            Console.Title = "NetLicensing Test";

            Console.WriteLine("NetLicensing Test...");
            Console.WriteLine();

            Encryption enc = new Encryption();
            Networking net = new Networking();
            Validation val = new Validation();
            License lic = new License();

            string key1 = "1234567890123456";
            string key2 = "12345678901234567890123456789012";

            string[] keys = new String[] { "111-111-111", "222-222-222", "333-333-333" };

            string userkey;

            if (File.Exists("license.lli") == true)
            {
                Console.WriteLine("Found License File...");

                if (val.validateLicenseArray("license.lli", key1, key2, keys) == true)
                {
                    Console.WriteLine("Valid License!");
                }
                else
                {
                    Console.WriteLine("Invalid License!");
                }
            }
            else
            {
                Console.WriteLine("You need to license this product!");
                Console.WriteLine();
                Console.Write("Enter your product key: ");
                userkey = Console.ReadLine();

                if (val.validateKeyArray(userkey, keys) == true)
                {
                    lic.createLicenseFile("license.lli", userkey, key1, key2);
                    Console.WriteLine("Product licensed!");
                }
                else
                {
                    Console.WriteLine("Invalid Product Key!");
                }
            }

            Console.WriteLine();
            Console.WriteLine("Press a key to exit...");
            Console.ReadKey();
        }
Beispiel #30
0
 public static void Main(string[] args)
 {
     string input_string = "";
     int key = Int32.Parse(args[args.Length - 1]);
     for(int i = 0; i < args.Length - 1; i++) {
         input_string += args [i] + " ";
     }
     input_string = input_string.Remove (input_string.Length - 1);
     Encryption e = new Encryption (input_string, key);
     Console.WriteLine(e.encrypt ());
 }
Beispiel #31
0
    public static byte[] EncryptBytesFromBytes(byte[] inBytes, byte[] key, byte[] iv)
    {
        string plainText = Convert.ToBase64String(inBytes);

        return(Encryption.EncryptStringToBytes(plainText, key, iv));
    }
Beispiel #32
0
        public ReturnMessage GetAuthenticateUser(string szUsername, string szPassword)
        {
            try
            {
                if (string.IsNullOrEmpty(szUsername.Trim()) || string.IsNullOrEmpty(szPassword.Trim()))
                {
                    return(new ReturnMessage
                    {
                        Success = false,
                        Message = "Please enter valid credentials."
                    });
                }
                var retVal = _IAppUserRepository.GetAppUser(null, szUsername);
                //If User Found
                if (retVal != null && retVal.AppUserId > 0)
                {
                    //Check if User has been Deleted
                    if (retVal.isDeleted)
                    {
                        return(new ReturnMessage
                        {
                            Success = false,
                            Message = $"Sorry, {szUsername} has been Deleted. Please contact Admin."
                        });
                    }
                    //Check if User has been Disabled
                    if (retVal.iStatus > 0)
                    {
                        return(new ReturnMessage
                        {
                            Success = false,
                            Message = $"Sorry, {szUsername} has been Disabled. Please contact Admin."
                        });
                    }

                    var passwordSalt      = retVal.szPasswordSalt.ToString();
                    var originalPassword  = retVal.szPassword.Trim();
                    var decryptedPassword = Encryption.SaltDecrypt(originalPassword, passwordSalt);

                    //password correct
                    if (decryptedPassword.Trim() == szPassword.Trim())
                    {
                        //Login User
                        string loginToken = Guid.NewGuid().ToString();
                        _IAppUserRepository.LoginAppUser(retVal.szUsername, true, loginToken);

                        LoginAppUserVM loginAppUserVM = new LoginAppUserVM
                        {
                            AppUserId      = retVal.AppUserId,
                            szImgURL       = retVal.szImgURL,
                            szUsername     = retVal.szUsername,
                            iStatus        = retVal.iStatus,
                            iChangePW      = retVal.iChangePW,
                            userLoginToken = loginToken
                        };
                        return(new ReturnMessage
                        {
                            ID = retVal.AppUserId,
                            Success = true,
                            Message = "Login Successful",
                            Data = loginAppUserVM
                        });
                    }
                    else
                    {
                        return(new ReturnMessage
                        {
                            Success = false,
                            Message = "Password Incorrect. Forgotten your password?. You can reset it."
                        });
                    }
                }
                else
                {
                    return(new ReturnMessage
                    {
                        Success = false,
                        Message = "Invalid Credentials. Check your entry and try again."
                    });
                }
            }
            catch (Exception ex)
            {
                return(new ReturnMessage
                {
                    Success = false,
                    Message = "Error Encountered: " + ex.Message
                });
            }
        }
        // GET: Message
        public ActionResult Index(string sortOrder, string searchString, int page = 1, int pageSize = 10)
        {
            var currentUserId = User.Identity.GetUserId();

            sortOrder = string.IsNullOrWhiteSpace(sortOrder) ? "createdDate_desc" : sortOrder;
            page      = page > 0 ? page : 1;
            pageSize  = pageSize > 0 ? pageSize : 25;


            ViewBag.searchQuery          = String.IsNullOrEmpty(searchString) ? "" : searchString;
            ViewBag.TitleSortParam       = sortOrder == "title" ? "title_desc" : "title";
            ViewBag.CreatedDateSortParam = sortOrder == "createdDate" ? "createdDate_desc" : "createdDate";
            ViewBag.CurrentSort          = sortOrder;
            ViewBag.CurrentUserId        = currentUserId;

            var query = db.Orders.Include(m => m.Messages).Include(m => m.Stock)
                        .Select(m => m.Messages
                                .OrderByDescending(y => y.CreatedDate)
                                .FirstOrDefault(x => x.CreatedBy.Id == currentUserId ||
                                                x.Order.Stock.Owner.Id == currentUserId ||
                                                x.Order.CreatedBy.Id == currentUserId))
                        .Where(x => x != null);


            query = string.IsNullOrEmpty(searchString) ? query : query.Where(x => x.Order.Stock.Item.Title.Contains(searchString) ||
                                                                             x.CreatedBy.UserName.Contains(searchString));

            switch (sortOrder)
            {
            case "title":
                query = query.OrderBy(x => x.Order.Stock.Item.Title);
                break;

            case "createdDate":
                query = query.OrderBy(x => x.CreatedDate);
                break;

            case "title_desc":
                query = query.OrderByDescending(x => x.Order.Stock.Item.Title);
                break;

            case "createdDate_desc":
                query = query.OrderByDescending(x => x.CreatedDate);
                break;
            }
            var pagedList = query.Select(x => new MessageModel
            {
                UserName    = x.CreatedBy.UserName,
                CreatedById = x.CreatedBy.Id,
                Id          = x.Id,
                ItemTitle   = x.Order.Stock.Item.Title,
                OrderId     = x.OrderId,
                CreatedDate = x.CreatedDate,
                Seen        = x.Seen,
                Text        = x.Text
            }).ToPagedList(page, pageSize);

            foreach (var messageModel in pagedList)
            {
                if (messageModel.CreatedById != currentUserId && !messageModel.Seen)
                {
                    var message = db.Messages.FirstOrDefault(x => x.Id == messageModel.Id);
                    if (message != null)
                    {
                        message.Seen            = true;
                        messageModel.Seen       = true;
                        db.Entry(message).State = EntityState.Modified;
                    }
                }
            }
            db.SaveChanges();

            foreach (var message in pagedList)
            {
                message.Text = Encryption.Decrypt(message.Text);
            }

            return(View(pagedList));
        }
Beispiel #34
0
        /// <summary>
        /// Sets any payment information that the <seealso cref="GatewayComponent">paymentGateway</seealso> didn't set
        /// </summary>
        /// <param name="paymentInfo">The payment information.</param>
        /// <param name="paymentGateway">The payment gateway.</param>
        /// <param name="rockContext">The rock context.</param>
        public void SetFromPaymentInfo(PaymentInfo paymentInfo, GatewayComponent paymentGateway, RockContext rockContext)
        {
            if (AccountNumberMasked.IsNullOrWhiteSpace() && paymentInfo.MaskedNumber.IsNotNullOrWhiteSpace())
            {
                AccountNumberMasked = paymentInfo.MaskedNumber;
            }

            GatewayPersonIdentifier       = (paymentInfo as ReferencePaymentInfo)?.GatewayPersonIdentifier;
            FinancialPersonSavedAccountId = (paymentInfo as ReferencePaymentInfo)?.FinancialPersonSavedAccountId;

            if (!CurrencyTypeValueId.HasValue && paymentInfo.CurrencyTypeValue != null)
            {
                CurrencyTypeValueId = paymentInfo.CurrencyTypeValue.Id;
            }

            if (!CreditCardTypeValueId.HasValue && paymentInfo.CreditCardTypeValue != null)
            {
                CreditCardTypeValueId = paymentInfo.CreditCardTypeValue.Id;
            }

            if (paymentInfo is CreditCardPaymentInfo)
            {
                var ccPaymentInfo = ( CreditCardPaymentInfo )paymentInfo;

                string nameOnCard  = paymentGateway.SplitNameOnCard ? ccPaymentInfo.NameOnCard + " " + ccPaymentInfo.LastNameOnCard : ccPaymentInfo.NameOnCard;
                var    newLocation = new LocationService(rockContext).Get(
                    ccPaymentInfo.BillingStreet1, ccPaymentInfo.BillingStreet2, ccPaymentInfo.BillingCity, ccPaymentInfo.BillingState, ccPaymentInfo.BillingPostalCode, ccPaymentInfo.BillingCountry);

                if (NameOnCard.IsNullOrWhiteSpace() && NameOnCard.IsNotNullOrWhiteSpace())
                {
                    NameOnCardEncrypted = Encryption.EncryptString(nameOnCard);
                }

                if (!ExpirationMonth.HasValue)
                {
                    ExpirationMonthEncrypted = Encryption.EncryptString(ccPaymentInfo.ExpirationDate.Month.ToString());
                }

                if (!ExpirationYear.HasValue)
                {
                    ExpirationYearEncrypted = Encryption.EncryptString(ccPaymentInfo.ExpirationDate.Year.ToString());
                }

                if (!BillingLocationId.HasValue && newLocation != null)
                {
                    BillingLocationId = newLocation.Id;
                }
            }
            else if (paymentInfo is SwipePaymentInfo)
            {
                var swipePaymentInfo = ( SwipePaymentInfo )paymentInfo;

                if (NameOnCard.IsNullOrWhiteSpace() && NameOnCard.IsNotNullOrWhiteSpace())
                {
                    NameOnCardEncrypted = Encryption.EncryptString(swipePaymentInfo.NameOnCard);
                }

                if (!ExpirationMonth.HasValue)
                {
                    ExpirationMonthEncrypted = Encryption.EncryptString(swipePaymentInfo.ExpirationDate.Month.ToString());
                }

                if (!ExpirationYear.HasValue)
                {
                    ExpirationYearEncrypted = Encryption.EncryptString(swipePaymentInfo.ExpirationDate.Year.ToString());
                }
            }
            else
            {
                var newLocation = new LocationService(rockContext).Get(
                    paymentInfo.Street1, paymentInfo.Street2, paymentInfo.City, paymentInfo.State, paymentInfo.PostalCode, paymentInfo.Country);

                if (!BillingLocationId.HasValue && newLocation != null)
                {
                    BillingLocationId = newLocation.Id;
                }
            }
        }
Beispiel #35
0
        static void Main()
        {
            LibTLSClient      cSSL;
            Common            cf;
            Encryption        e;
            Cipher            c;
            ClientHello       clientHello;
            ClientKeyExchange cke;

            int    debug   = 0;
            String request = "";

            string[] args = Environment.GetCommandLineArgs();

            try
            {
                debug = (int)UInt32.Parse(args[4]);

                if (debug == 1)
                {
                    Console.WriteLine("Server: {0} Port: {1} Cipher: {2} Debug: {3}", args[1], args[2], args[3], args[4]);
                }
                request = args[5];
                cf      = new Common(debug);

                e    = new Encryption();
                cSSL = new LibTLSClient(cf, e);

                cSSL.cipher    = UInt32.Parse(args[3], System.Globalization.NumberStyles.HexNumber);
                c              = new Cipher((ushort)cSSL.cipher);
                cSSL.cipherObj = c;
                cSSL.serverIP  = args[1];
            }
            catch (Exception ex)
            {
                Console.WriteLine("<prog> <ip/fqdn> <port> <cipher hex> <debug [0/1/2]> <a GET request>");
                Console.WriteLine("Example: TLSClient.exe 10.209.113.104 443 002f 2 \"GET / HTTP/1.1\"");
                return;
            }

            if (c.Supported() == false)
            {
                Console.WriteLine("Cipher Suite not supported currently");
                Console.WriteLine("Please try 002f/0035/003c/003d/009c/009d");
                return;
            }

            cSSL.CreateTCPConn(args[1], Convert.ToInt32(args[2]));
            cf.HandleResult(cSSL.errorCode, "TCP Connection");
            cf.ExitOnError(cSSL.errorCode);

            cSSL.InitBufs();

            List <UInt32> cipher_suites = new List <UInt32>();

            cipher_suites.Add(cSSL.cipher);

            String clientIP = cSSL.GetIPAddress();
            String serverIP = cSSL.serverIP;

            clientHello = new ClientHello(clientIP, serverIP, 3, 3, false, cipher_suites);

            List <byte> chello_hs = clientHello.Get();

            List <byte> crandom = clientHello.GetRandom();

            cSSL.StoreClientHelloParams(crandom);

            cSSL.SendHandshakeMessage(chello_hs, 0x1);
            cf.ExitOnError(cSSL.errorCode);

            cSSL.ReceiveHandshakeMessage();
            cf.ExitOnError(cSSL.errorCode);

            cSSL.ParseServerHandshakeMessages();
            cf.ExitOnError(cSSL.errorCode);

            if (cSSL.HasServerKeyExchange())
            {
                cke = new ClientKeyExchange(cf, cSSL.sCert_hs, 3, 3, cSSL.sKeyExch_hs, (String)"ECDHE");
            }
            else
            {
                cke = new ClientKeyExchange(cf, cSSL.sCert_hs, 3, 3, null, (String)"RSA");
            }

            List <byte> cke_hs = cke.CreateCKE();

            cSSL.StoreCKEParams(cke_hs, cke.GetPremasterSecret(), cke.ecdhCngClient, cke.server_pub_key, cke.client_pub_key);

            cSSL.SendHandshakeMessage(cke_hs, 0x10);
            cf.ExitOnError(cSSL.errorCode);

            cSSL.PrintHandshakeMessages();

            cSSL.SendChangeCipherSpec();

            cSSL.ComputeMasterSecret();
            cSSL.ComputeVerifyData();
            cSSL.ComputeKeys();

            cSSL.SendClientFinished();
            cSSL.ReadServerFinished();
            cf.debugPrint(cSSL.ErrorCodeToString(cSSL.errorCode));

            if (cSSL.errorCode != 0)
            {
                return;
            }
            cSSL.SendHTTPSData(request);

            cSSL.ReadHTTPSData();
            cf.debugPrint(cSSL.ErrorCodeToString(cSSL.errorCode));
            cSSL.ParseHTTPSData();

            byte[] dec = cSSL.DecryptResp();

            String dec_s = Encoding.ASCII.GetString(dec, 0, dec.Length);

            if ((dec_s.IndexOf("HTTP") == 0) && (debug == 0))
            {
                Console.WriteLine("{0} Successful", cSSL.cipherObj.cipher_name);
            }

            if ((debug == 2) || (debug == 1))
            {
                Console.WriteLine(dec_s);
            }
        }
Beispiel #36
0
        public ActionResult RegisterTH(Customer obj)
        {
            try
            {
                ModelState.Remove("IdentityID");
                if (ModelState.IsValid)
                {
                    obj.IdentityID = obj.tempIden.UrlDescriptHttp();

                    /*
                     * var rst = _RegisterTH(obj);
                     * if(rst.Status == true)
                     * {
                     * rst.text = Url.Action("Index", "Home");
                     * }
                     */

                    //return Json(rst,JsonRequestBehavior.AllowGet);

                    CustomerMapDao map = new CustomerMapDao();
                    if (map.FindIdentityCard(obj.IdentityID).Count == 0)
                    {
                        //obj.IdentityID = obj.IdentValid.UrlDescriptHttp();
                        int            ID      = SaveAccount.Register(obj.IdentityID, obj.TitleID, obj.Fname, obj.Lname, obj.Sex, obj.DateOfBirthStr, obj.Address, obj.DistrictID, obj.PrefectureID, obj.ProvinceID, obj.ZipCode, obj.Tel, obj.Tel_ext, obj.Mobile, obj.Fax, obj.Email, obj.OccupationID, obj.SalaryID, obj.TypeCustomer, obj.FromApp, obj.IsOversea);
                        CustomerMapDao _CusMap = new CustomerMapDao();
                        obj = _CusMap.FindById(ID);
                        if (!string.IsNullOrEmpty(obj.Email))
                        {
                            SendEmail.SendMail(obj.Email, "สํานักงานคณะกรรมการคุ้มครองผู้บริโภค ยินดีต้อนรับเข้าสู่การเป็นสมาชิก", RenderPartialViewToString("regisTemplate", obj));
                            //SendMail.Send(obj.Email, "สํานักงานคณะกรรมการคุ้มครองผู้บริโภค ยินดีต้อนรับเข้าสู่การเป็นสมาชิก", RenderPartialViewToString("ChangePassword", obj));
                        }

                        if (!string.IsNullOrEmpty(obj.Mobile))
                        {
                            //SmsLibs.SendSMS(obj.Mobile, SmsLibs.TypeMessage.register);
                            SmsLibs.SendSMS(obj.Mobile, string.Format(SmsLibs.CallStr(SmsLibs.TypeMessage.register), obj.IdentityID, Encryption.Decrypt(obj.Password)));
                        }

                        return(Json(new ResultData()
                        {
                            Status = true, text = Url.Action("Index", "Home")
                        }, JsonRequestBehavior.AllowGet));
                    }
                    else
                    {
                        return(Json(new ResultData()
                        {
                            Status = false, text = Resources.Message.MsgDuplicate
                        }, JsonRequestBehavior.AllowGet));
                    }
                }
            }
            catch (Exception ex)
            {
                SaveUtility.logError(ex);
            }
            return(View(obj));
        }
Beispiel #37
0
        public static bool Connect(Server server)
        {
            ConnectedServer = server;

            return(Client.Connect(server.Host, server.Port, Encryption.DecryptString(server.Password, "0?NRAnRBm;SWd41BUbKsT7)kN1y=RHLm=DR4ZZUBk&!JF3i\"Ra2Eg,8qwhA0^ydo")));
        }
Beispiel #38
0
        public ActionResult Authenticate(User usr)
        {
            bool       flag = false;
            dal        dal  = new dal();
            Encryption enc  = new Encryption();

            if (ModelState.IsValid)
            {
                //code to check if user==password and exist on db
                //transfer to homepage



                List <User> userValidated = (from u in dal.Users
                                             where (u.UserName == usr.UserName)
                                             select u).ToList <User>();
                if (userValidated != null)
                {
                    //if (enc.ValidatePassword(usr.Password, userValidated[0].Password))
                    if (userValidated.Count > 0 && usr.Password == userValidated[0].Password)
                    {
                        ViewBag.message = "Login Successfully!";
                        flag            = true;
                    }
                    else
                    {
                        ViewBag.message = "Incorrect Username/Password!";
                    }
                }
                if (flag == true)
                {
                    flag = false;
                    if (userValidated[0].UserType == "Student")
                    {
                        //user authenticated successfully
                        FormsAuthentication.SetAuthCookie("cookie", true);
                        Session["Student"] = userValidated[0].Id;
                    }
                    else if (userValidated[0].UserType == "Lecturer")
                    {
                        FormsAuthentication.SetAuthCookie("cookie", true);
                        Session["Lecturer"] = userValidated[0].Id;
                    }
                    else if (userValidated[0].UserType == "Administrator")
                    {
                        FormsAuthentication.SetAuthCookie("cookie", true);
                        Session["Administrator"] = userValidated[0].Id;
                    }

                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    return(View("Login", usr));
                }
            }

            else
            {
                ViewBag.message = "Invalid Username/Password!";
                return(View("Login", usr));
            }
        }
Beispiel #39
0
    public static bool ExtendSubscription(string username, string password, string license)
    {
        if (!Constants.Initialized)
        {
            System.Windows.Forms.MessageBox.Show("Please initialize your application first!", OnProgramStart.Name, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
            Security.End();
            Process.GetCurrentProcess().Kill();
        }
        if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password) || string.IsNullOrWhiteSpace(license))
        {
            System.Windows.Forms.MessageBox.Show("Invalid registrar information!", ApplicationSettings.Name, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
            Process.GetCurrentProcess().Kill();
        }
        string[] response = new string[] { };
        using (WebClient wc = new WebClient())
        {
            try
            {
                Security.Start();
                wc.Proxy = null;
                response = Encryption.DecryptService(Encoding.Default.GetString(wc.UploadValues(Constants.ApiUrl, new NameValueCollection
                {
                    ["token"]       = Encryption.EncryptService(Constants.Token),
                    ["timestamp"]   = Encryption.EncryptService(DateTime.Now.ToString()),
                    ["aid"]         = Encryption.APIService(OnProgramStart.AID),
                    ["session_id"]  = Constants.IV,
                    ["api_id"]      = Constants.APIENCRYPTSALT,
                    ["api_key"]     = Constants.APIENCRYPTKEY,
                    ["session_key"] = Constants.Key,
                    ["secret"]      = Encryption.APIService(OnProgramStart.Secret),
                    ["type"]        = Encryption.APIService("extend"),
                    ["username"]    = Encryption.APIService(username),
                    ["password"]    = Encryption.APIService(password),
                    ["license"]     = Encryption.APIService(license),
                }))).Split("|".ToCharArray());
                if (response[0] != Constants.Token)
                {
                    System.Windows.Forms.MessageBox.Show("Security error has been triggered!", OnProgramStart.Name, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                    Security.End();
                    Process.GetCurrentProcess().Kill();
                }
                if (Security.MaliciousCheck(response[1]))
                {
                    System.Windows.Forms.MessageBox.Show("Possible malicious activity detected!", OnProgramStart.Name, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
                    Process.GetCurrentProcess().Kill();
                }
                if (Constants.Breached)
                {
                    System.Windows.Forms.MessageBox.Show("Possible malicious activity detected!", OnProgramStart.Name, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
                    Process.GetCurrentProcess().Kill();
                }
                switch (response[2])
                {
                case "success":
                    Security.End();
                    return(true);

                case "invalid_token":
                    System.Windows.Forms.MessageBox.Show("Token does not exist!", ApplicationSettings.Name, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                    Security.End();
                    return(false);

                case "invalid_details":
                    System.Windows.Forms.MessageBox.Show("Your user details are invalid!", ApplicationSettings.Name, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                    Security.End();
                    return(false);
                }
            }
            catch
            {
                System.Windows.Forms.MessageBox.Show("Failed to establish a secure SSL tunnel with the server!", ApplicationSettings.Name, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                Process.GetCurrentProcess().Kill();
            }
            return(false);
        }
    }
Beispiel #40
0
    public static void Initialize(string name, string aid, string secret, string version)
    {
        if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(aid) || string.IsNullOrWhiteSpace(secret) || string.IsNullOrWhiteSpace(version))
        {
            System.Windows.Forms.MessageBox.Show("Invalid application information!", Name, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
            Process.GetCurrentProcess().Kill();
        }
        AID     = aid;
        Secret  = secret;
        Version = version;
        Name    = name;
        string[] response = new string[] { };
        using (WebClient wc = new WebClient())
        {
            try
            {
                wc.Proxy = null;
                Security.Start();
                response = (Encryption.DecryptService(Encoding.Default.GetString(wc.UploadValues(Constants.ApiUrl, new NameValueCollection
                {
                    ["token"] = Encryption.EncryptService(Constants.Token),
                    ["timestamp"] = Encryption.EncryptService(DateTime.Now.ToString()),
                    ["aid"] = Encryption.APIService(AID),
                    ["session_id"] = Constants.IV,
                    ["api_id"] = Constants.APIENCRYPTSALT,
                    ["api_key"] = Constants.APIENCRYPTKEY,
                    ["session_key"] = Constants.Key,
                    ["secret"] = Encryption.APIService(Secret),
                    ["type"] = Encryption.APIService("start")
                }))).Split("|".ToCharArray()));
                if (Security.MaliciousCheck(response[1]))
                {
                    System.Windows.Forms.MessageBox.Show("Possible malicious activity detected!", OnProgramStart.Name, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
                    Process.GetCurrentProcess().Kill();
                }
                if (Constants.Breached)
                {
                    System.Windows.Forms.MessageBox.Show("Possible malicious activity detected!", OnProgramStart.Name, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
                    Process.GetCurrentProcess().Kill();
                }
                if (response[0] != Constants.Token)
                {
                    System.Windows.Forms.MessageBox.Show("Security error has been triggered!", Name, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                    Process.GetCurrentProcess().Kill();
                }
                switch (response[2])
                {
                case "success":
                    Constants.Initialized = true;
                    if (response[3] == "Enabled")
                    {
                        ApplicationSettings.Status = true;
                    }
                    if (response[4] == "Enabled")
                    {
                        ApplicationSettings.DeveloperMode = true;
                    }
                    ApplicationSettings.Hash        = response[5];
                    ApplicationSettings.Version     = response[6];
                    ApplicationSettings.Update_Link = response[7];
                    if (response[8] == "Enabled")
                    {
                        ApplicationSettings.Freemode = true;
                    }
                    if (response[9] == "Enabled")
                    {
                        ApplicationSettings.Login = true;
                    }
                    ApplicationSettings.Name = response[10];
                    if (response[11] == "Enabled")
                    {
                        ApplicationSettings.Register = true;
                    }
                    if (ApplicationSettings.DeveloperMode)
                    {
                        System.Windows.Forms.MessageBox.Show("Application is in Developer Mode, bypassing integrity and update check!", Name, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
                        File.Create(Environment.CurrentDirectory + "/integrity.log").Close();
                        string hash = Security.Integrity(Process.GetCurrentProcess().MainModule.FileName);
                        File.WriteAllText(Environment.CurrentDirectory + "/integrity.log", hash);
                        System.Windows.Forms.MessageBox.Show("Your applications hash has been saved to integrity.txt, please refer to this when your application is ready for release!", Name, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
                    }
                    else
                    {
                        if (response[12] == "Enabled")
                        {
                            if (ApplicationSettings.Hash != Security.Integrity(Process.GetCurrentProcess().MainModule.FileName))
                            {
                                System.Windows.Forms.MessageBox.Show($"File has been tampered with, couldn't verify integrity!", Name, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                                Process.GetCurrentProcess().Kill();
                            }
                        }
                        if (ApplicationSettings.Version != Version)
                        {
                            System.Windows.Forms.MessageBox.Show($"Update {ApplicationSettings.Version} available, redirecting to update!", Name, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                            Process.Start(ApplicationSettings.Update_Link);
                            Process.GetCurrentProcess().Kill();
                        }
                    }
                    if (ApplicationSettings.Status == false)
                    {
                        System.Windows.Forms.MessageBox.Show("Looks like this application is disabled, please try again later!", Name, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                        Process.GetCurrentProcess().Kill();
                    }
                    break;

                case "binderror":
                    System.Windows.Forms.MessageBox.Show(Encryption.Decode("RmFpbGVkIHRvIGJpbmQgdG8gc2VydmVyLCBjaGVjayB5b3VyIEFJRCAmIFNlY3JldCBpbiB5b3VyIGNvZGUh"), Name, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                    Process.GetCurrentProcess().Kill();
                    return;

                case "banned":
                    System.Windows.Forms.MessageBox.Show("This application has been banned for violating the TOS" + Environment.NewLine + "Contact us at [email protected]", Name, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                    Process.GetCurrentProcess().Kill();
                    return;
                }
                Security.End();
            }
            catch
            {
                System.Windows.Forms.MessageBox.Show("Failed to establish a secure SSL tunnel with the server!", Name, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                Process.GetCurrentProcess().Kill();
            }
        }
    }
Beispiel #41
0
        public static string CheckRegitry()
        {
            var partwwwroot = System.IO.Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");
            /*Create Path */
            string KeyOne    = "ZaniimzOxide";
            string FILE_NAME = "KeyOne.DAT";
            string pathImage = @"\OEM\Key\";
            string pathSave  = $"wwwroot{pathImage}";

            var param1 = Encryption.Encrypt(getUniqueID("C"), KeyOne);
            var param2 = Encryption.Encrypt(GetMachineGuid(), KeyOne);
            var dir    = Encryption.Encrypt(partwwwroot + pathImage, KeyOne);

            //string location = @"SOFTWARE\Foglight\";
            //RegistryKey key = Registry.CurrentUser.CreateSubKey(location);
            ///key.SetValue("param1", param1);
            //key.SetValue("param2", param2);
            //key.SetValue("dir", dir);


            if (!Directory.Exists(pathSave))
            {
                Directory.CreateDirectory(pathSave);
            }
            /**/

            List <string> datalists = new List <string>();

            try
            {
                using (FileStream fs = new FileStream(pathSave + FILE_NAME, FileMode.Open, FileAccess.Read))
                {
                    using (BinaryReader r = new BinaryReader(fs))
                    {
                        for (int i = 0; i < 8; i++)
                        {
                            datalists.Add(r.ReadString());
                        }
                    }
                }

                if (Encryption.Decrypt(datalists[0], KeyOne) == getUniqueID("C"))
                {
                }
                else
                {
                    return("Please Regiter License");
                }
                if (Encryption.Decrypt(datalists[1], KeyOne) == GetMachineGuid())
                {
                }
                else
                {
                    return("Please Regiter License");
                }

                var a = JavaTimeStamp.JavaTimeStampToDateTime(Convert.ToDouble(Encryption.Decrypt(datalists[3], KeyOne)));

                if (DateTime.Now > JavaTimeStamp.JavaTimeStampToDateTime(Convert.ToDouble(Encryption.Decrypt(datalists[3], KeyOne))))
                {
                    return("License Expired");
                }
                else
                {
                }
            }
            catch
            {
                return("Please Regiter License");
            }



            return("true");
        }
        internal static StorageAccountData DeserializeStorageAccountData(JsonElement element)
        {
            Optional <Models.Sku>        sku              = default;
            Optional <Kind>              kind             = default;
            Optional <Identity>          identity         = default;
            Optional <ExtendedLocation>  extendedLocation = default;
            IDictionary <string, string> tags             = default;
            Location                     location         = default;
            ResourceIdentifier           id   = default;
            string                       name = default;
            ResourceType                 type = default;
            Optional <ProvisioningState> provisioningState   = default;
            Optional <Endpoints>         primaryEndpoints    = default;
            Optional <string>            primaryLocation     = default;
            Optional <AccountStatus>     statusOfPrimary     = default;
            Optional <DateTimeOffset>    lastGeoFailoverTime = default;
            Optional <string>            secondaryLocation   = default;
            Optional <AccountStatus>     statusOfSecondary   = default;
            Optional <DateTimeOffset>    creationTime        = default;
            Optional <CustomDomain>      customDomain        = default;
            Optional <SasPolicy>         sasPolicy           = default;
            Optional <KeyPolicy>         keyPolicy           = default;
            Optional <KeyCreationTime>   keyCreationTime     = default;
            Optional <Endpoints>         secondaryEndpoints  = default;
            Optional <Encryption>        encryption          = default;
            Optional <AccessTier>        accessTier          = default;
            Optional <AzureFilesIdentityBasedAuthentication> azureFilesIdentityBasedAuthentication = default;
            Optional <bool>                 supportsHttpsTrafficOnly = default;
            Optional <NetworkRuleSet>       networkAcls          = default;
            Optional <bool>                 isHnsEnabled         = default;
            Optional <GeoReplicationStats>  geoReplicationStats  = default;
            Optional <bool>                 failoverInProgress   = default;
            Optional <LargeFileSharesState> largeFileSharesState = default;
            Optional <IReadOnlyList <PrivateEndpointConnectionData> > privateEndpointConnections = default;
            Optional <RoutingPreference> routingPreference = default;
            Optional <BlobRestoreStatus> blobRestoreStatus = default;
            Optional <bool> allowBlobPublicAccess          = default;
            Optional <MinimumTlsVersion> minimumTlsVersion = default;
            Optional <bool> allowSharedKeyAccess           = default;
            Optional <bool> isNfsV3Enabled = default;
            Optional <bool> allowCrossTenantReplication = default;

            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("sku"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    sku = Models.Sku.DeserializeSku(property.Value);
                    continue;
                }
                if (property.NameEquals("kind"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    kind = new Kind(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("identity"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    identity = Identity.DeserializeIdentity(property.Value);
                    continue;
                }
                if (property.NameEquals("extendedLocation"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    extendedLocation = ExtendedLocation.DeserializeExtendedLocation(property.Value);
                    continue;
                }
                if (property.NameEquals("tags"))
                {
                    Dictionary <string, string> dictionary = new Dictionary <string, string>();
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        dictionary.Add(property0.Name, property0.Value.GetString());
                    }
                    tags = dictionary;
                    continue;
                }
                if (property.NameEquals("location"))
                {
                    location = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("id"))
                {
                    id = new ResourceIdentifier(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("type"))
                {
                    type = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("properties"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        if (property0.NameEquals("provisioningState"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            provisioningState = property0.Value.GetString().ToProvisioningState();
                            continue;
                        }
                        if (property0.NameEquals("primaryEndpoints"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            primaryEndpoints = Endpoints.DeserializeEndpoints(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("primaryLocation"))
                        {
                            primaryLocation = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("statusOfPrimary"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            statusOfPrimary = property0.Value.GetString().ToAccountStatus();
                            continue;
                        }
                        if (property0.NameEquals("lastGeoFailoverTime"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            lastGeoFailoverTime = property0.Value.GetDateTimeOffset("O");
                            continue;
                        }
                        if (property0.NameEquals("secondaryLocation"))
                        {
                            secondaryLocation = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("statusOfSecondary"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            statusOfSecondary = property0.Value.GetString().ToAccountStatus();
                            continue;
                        }
                        if (property0.NameEquals("creationTime"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            creationTime = property0.Value.GetDateTimeOffset("O");
                            continue;
                        }
                        if (property0.NameEquals("customDomain"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            customDomain = CustomDomain.DeserializeCustomDomain(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("sasPolicy"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            sasPolicy = SasPolicy.DeserializeSasPolicy(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("keyPolicy"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            keyPolicy = KeyPolicy.DeserializeKeyPolicy(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("keyCreationTime"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            keyCreationTime = KeyCreationTime.DeserializeKeyCreationTime(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("secondaryEndpoints"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            secondaryEndpoints = Endpoints.DeserializeEndpoints(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("encryption"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            encryption = Encryption.DeserializeEncryption(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("accessTier"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            accessTier = property0.Value.GetString().ToAccessTier();
                            continue;
                        }
                        if (property0.NameEquals("azureFilesIdentityBasedAuthentication"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            azureFilesIdentityBasedAuthentication = AzureFilesIdentityBasedAuthentication.DeserializeAzureFilesIdentityBasedAuthentication(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("supportsHttpsTrafficOnly"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            supportsHttpsTrafficOnly = property0.Value.GetBoolean();
                            continue;
                        }
                        if (property0.NameEquals("networkAcls"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            networkAcls = NetworkRuleSet.DeserializeNetworkRuleSet(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("isHnsEnabled"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            isHnsEnabled = property0.Value.GetBoolean();
                            continue;
                        }
                        if (property0.NameEquals("geoReplicationStats"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            geoReplicationStats = GeoReplicationStats.DeserializeGeoReplicationStats(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("failoverInProgress"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            failoverInProgress = property0.Value.GetBoolean();
                            continue;
                        }
                        if (property0.NameEquals("largeFileSharesState"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            largeFileSharesState = new LargeFileSharesState(property0.Value.GetString());
                            continue;
                        }
                        if (property0.NameEquals("privateEndpointConnections"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            List <PrivateEndpointConnectionData> array = new List <PrivateEndpointConnectionData>();
                            foreach (var item in property0.Value.EnumerateArray())
                            {
                                array.Add(PrivateEndpointConnectionData.DeserializePrivateEndpointConnectionData(item));
                            }
                            privateEndpointConnections = array;
                            continue;
                        }
                        if (property0.NameEquals("routingPreference"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            routingPreference = RoutingPreference.DeserializeRoutingPreference(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("blobRestoreStatus"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            blobRestoreStatus = BlobRestoreStatus.DeserializeBlobRestoreStatus(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("allowBlobPublicAccess"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            allowBlobPublicAccess = property0.Value.GetBoolean();
                            continue;
                        }
                        if (property0.NameEquals("minimumTlsVersion"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            minimumTlsVersion = new MinimumTlsVersion(property0.Value.GetString());
                            continue;
                        }
                        if (property0.NameEquals("allowSharedKeyAccess"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            allowSharedKeyAccess = property0.Value.GetBoolean();
                            continue;
                        }
                        if (property0.NameEquals("isNfsV3Enabled"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            isNfsV3Enabled = property0.Value.GetBoolean();
                            continue;
                        }
                        if (property0.NameEquals("allowCrossTenantReplication"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            allowCrossTenantReplication = property0.Value.GetBoolean();
                            continue;
                        }
                    }
                    continue;
                }
            }
            return(new StorageAccountData(id, name, type, tags, location, sku.Value, Optional.ToNullable(kind), identity.Value, extendedLocation.Value, Optional.ToNullable(provisioningState), primaryEndpoints.Value, primaryLocation.Value, Optional.ToNullable(statusOfPrimary), Optional.ToNullable(lastGeoFailoverTime), secondaryLocation.Value, Optional.ToNullable(statusOfSecondary), Optional.ToNullable(creationTime), customDomain.Value, sasPolicy.Value, keyPolicy.Value, keyCreationTime.Value, secondaryEndpoints.Value, encryption.Value, Optional.ToNullable(accessTier), azureFilesIdentityBasedAuthentication.Value, Optional.ToNullable(supportsHttpsTrafficOnly), networkAcls.Value, Optional.ToNullable(isHnsEnabled), geoReplicationStats.Value, Optional.ToNullable(failoverInProgress), Optional.ToNullable(largeFileSharesState), Optional.ToList(privateEndpointConnections), routingPreference.Value, blobRestoreStatus.Value, Optional.ToNullable(allowBlobPublicAccess), Optional.ToNullable(minimumTlsVersion), Optional.ToNullable(allowSharedKeyAccess), Optional.ToNullable(isNfsV3Enabled), Optional.ToNullable(allowCrossTenantReplication)));
        }
Beispiel #43
0
 public ResultData _Forget(string Identity, string Email)
 {
     if (!string.IsNullOrEmpty(Identity) && !string.IsNullOrEmpty(Email))
     {
         CustomerMapDao map = new CustomerMapDao();
         var            obj = map.FindByIdentityAndEmail(Identity.Trim(), Email.Trim());
         if (obj != null)
         {
             String newPass = Helplibery.CreatePassword(10);
             // Method ส่ง Email
             obj.Password = Encryption.Encrypt(newPass);
             map.AddOrUpdate(obj);
             map.CommitChange();
             Log_Customer_reset_passMapDao logmap = new Log_Customer_reset_passMapDao();
             logmap.Add(new Log_Customer_reset_pass {
                 CreateDate = DateTime.Now, EmailTo = Email, ErrorText = "", IPAddress = Extension.GetIPAddress(), Result = true
             });
             logmap.CommitChange();
             if (!string.IsNullOrEmpty(Email))
             {
                 //  string ttt = System.Web.Mvc.Html.PartialExtensions.Partial("ChangePassword", obj);
                 string filePath = Path.Combine(HttpRuntime.AppDomainAppPath, "Templates/ChgPass.htm");
                 string html     = System.IO.File.ReadAllText(filePath);
                 SendEmail.SendMail(Email, "แก้ไขรหัสผ่านสํานักงานคณะกรรมการคุ้มครองผู้บริโภค", string.Format(html, obj.FullNameStr, obj.IdentityID, Encryption.Decrypt(obj.Password), obj.Email));
                 //SendMail.Send(obj.Email, "สํานักงานคณะกรรมการคุ้มครองผู้บริโภค ยินดีต้อนรับเข้าสู่การเป็นสมาชิก", RenderPartialViewToString("ChangePassword", obj));
             }
             return(new ResultData()
             {
                 Status = true, text = "รหัสผ่านใหม่ ถูกจัดส่งไปยังอีเมลของท่าน เรียบร้อยแล้ว"
             });
         }
         else
         {
             return(new ResultData()
             {
                 Status = false, text = "ข้อมูลไม่ถูกต้อง"
             });
         }
     }
     else
     {
         return(new ResultData()
         {
             Status = false, text = "กรุณากรอกข้อมูลให้ครบถ้วน"
         });
     }
 }
Beispiel #44
0
 public ActionResult Nation(IdentityCheck obj, string mode)
 {
     try
     {
         if (ModelState.IsValid)
         {
             CustomerMapDao map = new CustomerMapDao();
             if (map.FindIdentityCard(obj.IdentStr).Count == 0)
             {
                 return(Json(new ResultData()
                 {
                     Status = true, text = Url.Action("Register", "Home", new { mode = mode, key = Encryption.Encrypt(obj.IdentStr) })
                 }, JsonRequestBehavior.AllowGet));
                 //return Json(new { RedirectUrl =  });
             }
             else
             {
                 //return Json("Is Dupplicate!!!",JsonRequestBehavior.AllowGet );
                 return(Json(new ResultData()
                 {
                     Status = false, text = "Is Dupplicate!!!"
                 }, JsonRequestBehavior.AllowGet));
             }
         }
     }
     catch (Exception ex)
     {
         SaveUtility.logError(ex);
     }
     return(Json(new ResultData()
     {
         Status = false, text = "ข้อมูลไม่ถูกต้อง"
     }, JsonRequestBehavior.AllowGet));
 }
Beispiel #45
0
        public ActionResult RegisterEN(Customer_Oversea obj)
        {
            if (ModelState.IsValid)
            {
                if (TempData["Customer"] != null)
                {
                    CustomerMapDao Map    = new CustomerMapDao();
                    Customer       Cusobj = new Customer();

                    Cusobj = (Customer)TempData["Customer"];

                    Cusobj.Keygen            = Guid.NewGuid().ToString();
                    Cusobj.CreateDate        = DateTime.Now;
                    Cusobj.Active            = true;
                    Cusobj.IsConfirmRegister = false;
                    Cusobj.IsOversea         = true;
                    Cusobj.DateOfBirth       = Cusobj.DateOfBirthStr.todate();
                    //obj.Password = Helplibery.CreatePassword(8);
                    //Cusobj.Password = Encryption.Encrypt("12345678");
                    Cusobj.Password = Encryption.Encrypt(Helplibery.CreatePassword(8));
                    //Cusobj.Password = Helplibery.CreatePassword(10);

                    Map.Add(Cusobj);
                    Map.CommitChange();

                    int ID = GetAccount.GetCustomerLastID();
                    Customer_OverseaMapDao OverMap = new Customer_OverseaMapDao();
                    obj.CustomerID = ID;

                    if (obj.PurposeIList != null)
                    {
                        obj.purpose_id = Convert.ToInt32(string.Join(",", obj.PurposeIList));
                    }

                    OverMap.Add(obj);
                    OverMap.CommitChange();

                    //////////////////////////////////////////////////////////////////////////////////////////////////////////

                    CustomerMapDao map = new CustomerMapDao();
                    if (map.FindIdentityCard(Cusobj.IdentityID).Count == 0)
                    {
                        //obj.IdentityID = obj.IdentValid.UrlDescriptHttp();
                        int            CusID   = SaveAccount.Register(Cusobj.IdentityID, Cusobj.TitleID, Cusobj.Fname, Cusobj.Lname, Cusobj.Sex, Cusobj.DateOfBirthStr, Cusobj.Address, Cusobj.DistrictID, Cusobj.PrefectureID, Cusobj.ProvinceID, Cusobj.ZipCode, Cusobj.Tel, Cusobj.Tel_ext, Cusobj.Mobile, Cusobj.Fax, Cusobj.Email, Cusobj.OccupationID, Cusobj.SalaryID, Cusobj.TypeCustomer, Cusobj.FromApp, Cusobj.IsOversea);
                        CustomerMapDao _CusMap = new CustomerMapDao();
                        Cusobj = _CusMap.FindById(CusID);
                        if (!string.IsNullOrEmpty(Cusobj.Email))
                        {
                            SendEmail.SendMail(Cusobj.Email, "สํานักงานคณะกรรมการคุ้มครองผู้บริโภค ยินดีต้อนรับเข้าสู่การเป็นสมาชิก", RenderPartialViewToString("regisTemplate", Cusobj));
                            //SendMail.Send(obj.Email, "สํานักงานคณะกรรมการคุ้มครองผู้บริโภค ยินดีต้อนรับเข้าสู่การเป็นสมาชิก", RenderPartialViewToString("ChangePassword", obj));
                        }
                        return(Json(new ResultData()
                        {
                            Status = true, text = Url.Action("Index", "Home")
                        }, JsonRequestBehavior.AllowGet));
                    }
                    else
                    {
                        //return Json(new ResultData() { Status = false, text = Resources.Message.MsgDuplicate }, JsonRequestBehavior.AllowGet);
                        CustomerMapDao _CusMap = new CustomerMapDao();
                        int            CusID   = GetAccount.GetCustomerLastID();
                        if (!string.IsNullOrEmpty(Cusobj.Email))
                        {
                            SendEmail.SendMail(Cusobj.Email, "สํานักงานคณะกรรมการคุ้มครองผู้บริโภค ยินดีต้อนรับเข้าสู่การเป็นสมาชิก", RenderPartialViewToString("regisTemplate", Cusobj));
                            //SendMail.Send(obj.Email, "สํานักงานคณะกรรมการคุ้มครองผู้บริโภค ยินดีต้อนรับเข้าสู่การเป็นสมาชิก", RenderPartialViewToString("ChangePassword", obj));
                        }
                        return(Json(new ResultData()
                        {
                            Status = true, text = Url.Action("Index", "Home")
                        }, JsonRequestBehavior.AllowGet));
                    }

                    //////////////////////////////////////////////////////////////////////////////////////////////////////////

                    return(Json(new ResultData()
                    {
                        Status = true, text = Url.Action("Index", "Home")
                    }, JsonRequestBehavior.AllowGet));

                    //return Json(new { RedirectUrl = Url.Action("Index", "Home") });
                }
            }
            return(View(obj));
        }
Beispiel #46
0
    protected void gvwEvaluations_DBlClick(object sender, ClickEventArgs e)
    {
        DataSet Ds = new DataSet( );

        Ds = SQLHelper.ExecuteDataset(Cache["ApplicationDatabase"].ToString( ), "GetEvaluatorbyEvaluated", new object[] { e.Row.Cells[e.Row.Cells.IndexOf("Legajo Evaluado")].ToString( ) });
        string evaluador = Ds.Tables[0].Rows[0].ItemArray[0].ToString( );
        string groupid   = Ds.Tables[0].Rows[0].ItemArray[1].ToString( );


        if ((e.Row.Cells.All[0] != null))
        {
            Response.Redirect(Server.HtmlEncode("./EvaluationFormLink.aspx?.=" + Server.UrlEncode(Encryption.Encrypt(groupid + ".2." + evaluador))));
        }
    }
Beispiel #47
0
        public ResultData _RegisterTH(Customer obj)
        {
            CustomerMapDao map = new CustomerMapDao();

            if (map.FindIdentityCard(obj.IdentityID).Count == 0)
            {
                //obj.IdentityID = obj.IdentValid.UrlDescriptHttp();
                int            ID      = SaveAccount.Register(obj.IdentityID, obj.TitleID, obj.Fname, obj.Lname, obj.Sex, obj.DateOfBirthStr, obj.Address, obj.DistrictID, obj.PrefectureID, obj.ProvinceID, obj.ZipCode, obj.Tel, obj.Tel_ext, obj.Mobile, obj.Fax, obj.Email, obj.OccupationID, obj.SalaryID, obj.TypeCustomer, obj.FromApp, obj.IsOversea);
                CustomerMapDao _CusMap = new CustomerMapDao();
                obj = _CusMap.FindById(ID);
                if (!string.IsNullOrEmpty(obj.Email))
                {
                    string filePath = Path.Combine(HttpRuntime.AppDomainAppPath, "Templates/regisTemplate.cshtml");
                    string html     = System.IO.File.ReadAllText(filePath);
                    SendEmail.SendMail(obj.Email, "สํานักงานคณะกรรมการคุ้มครองผู้บริโภค ยินดีต้อนรับเข้าสู่การเป็นสมาชิก", string.Format(html, obj.FullNameStr, obj.IdentityID, Encryption.Decrypt(obj.Password)));
                    if (!string.IsNullOrEmpty(obj.Mobile))
                    {
                        //SmsLibs.SendSMS(obj.Mobile, SmsLibs.TypeMessage.register);
                        SmsLibs.SendSMS(obj.Mobile, string.Format(SmsLibs.CallStr(SmsLibs.TypeMessage.register), obj.IdentityID, Encryption.Decrypt(obj.Password)));
                    }



                    //SendEmail.SendMail(obj.Email, "สํานักงานคณะกรรมการคุ้มครองผู้บริโภค ยินดีต้อนรับเข้าสู่การเป็นสมาชิก", RenderPartialViewToString("regisTemplate", obj));
                }
                return(new ResultData()
                {
                    Status = true
                });
            }
            else
            {
                return(new ResultData()
                {
                    Status = false, text = Resources.Message.MsgDuplicate
                });
            }
        }
 /// <summary>
 /// Generate a hash for a password
 /// </summary>
 /// <param name="plainTextPassword">The password to hash</param>
 /// <returns>The hashed password</returns>
 public static string GetPasswordHash(string plainTextPassword)
 {
     return(Encryption.GetStringHash(plainTextPassword, Encryption.HashType.Sha256));
 }
Beispiel #49
0
        public static void Execute(bool execute)
        {
            if (!execute)
            {
                Console.WriteLine($"Audit: {nameof(EncryptionAudit)} has not been marked for execution, skipping audit.");
                Console.WriteLine($"*** PRESS ANY KEY TO CONTINUE *** \r\n");
                Console.ReadKey();

                return;
            }

            try
            {
                ///
                /// Encryption.Encrypt();
                ///

                var           key = "yourstringpasswordhere";
                var           iv  = "16charlongivonly";
                List <string> encrList;

                List <string> myLine = new List <string>();
                myLine.Add("Test Line 1");
                myLine.Add("Test Line 2");

                using (Encryption encr_1 = new Encryption(key, iv))
                {
                    encrList = encr_1.Encrypt(myLine);

                    Console.WriteLine("");
                    Console.WriteLine("-- Encrypt Test --");
                    Console.WriteLine("");

                    foreach (string line in encrList)
                    {
                        Console.WriteLine($"Contents: {line}");
                    }
                }

                ///
                /// Encryption.Decrypt();
                ///

                using (Encryption encr_2 = new Encryption(key, iv))
                {
                    var myNewList = encr_2.Decrypt(encrList);

                    Console.WriteLine("");
                    Console.WriteLine("-- Decrypt Test --");
                    Console.WriteLine("");

                    foreach (string line in myNewList)
                    {
                        Console.WriteLine($"Contents: {line}");
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"Encryption Exception: {e.ToString()}");
            }
        }
Beispiel #50
0
    public static byte[] DecryptBytesFromBytes(byte[] cipherBytes, byte[] key, byte[] iv)
    {
        string s = Encryption.DecryptStringFromBytes(cipherBytes, key, iv);

        return(Convert.FromBase64String(s));
    }
Beispiel #51
0
 internal SnapshotData(ResourceIdentifier id, string name, ResourceType type, IDictionary <string, string> tags, AzureLocation location, string managedBy, SnapshotSku sku, ExtendedLocation extendedLocation, DateTimeOffset?timeCreated, OperatingSystemTypes?osType, HyperVGeneration?hyperVGeneration, PurchasePlanAutoGenerated purchasePlan, CreationData creationData, int?diskSizeGB, long?diskSizeBytes, DiskState?diskState, string uniqueId, EncryptionSettingsCollection encryptionSettingsCollection, string provisioningState, bool?incremental, Encryption encryption, NetworkAccessPolicy?networkAccessPolicy, string diskAccessId, bool?supportsHibernation) : base(id, name, type, tags, location)
 {
     ManagedBy                    = managedBy;
     Sku                          = sku;
     ExtendedLocation             = extendedLocation;
     TimeCreated                  = timeCreated;
     OsType                       = osType;
     HyperVGeneration             = hyperVGeneration;
     PurchasePlan                 = purchasePlan;
     CreationData                 = creationData;
     DiskSizeGB                   = diskSizeGB;
     DiskSizeBytes                = diskSizeBytes;
     DiskState                    = diskState;
     UniqueId                     = uniqueId;
     EncryptionSettingsCollection = encryptionSettingsCollection;
     ProvisioningState            = provisioningState;
     Incremental                  = incremental;
     Encryption                   = encryption;
     NetworkAccessPolicy          = networkAccessPolicy;
     DiskAccessId                 = diskAccessId;
     SupportsHibernation          = supportsHibernation;
 }
Beispiel #52
0
        /// <summary>
        /// Processes the content file request.
        /// </summary>
        /// <param name="context">The context.</param>
        private void ProcessContentFileRequest(HttpContext context)
        {
            // Don't trust query strings
            string untrustedFilePath   = context.Request.QueryString["fileName"];
            string encryptedRootFolder = context.Request.QueryString["rootFolder"];

            // Make sure a filename was provided
            if (string.IsNullOrWhiteSpace(untrustedFilePath))
            {
                SendBadRequest(context, "fileName must be specified");
                return;
            }

            // Count of query parameters used. Start at 2 since "isBinaryFile" and "fileName" are required to get here.
            var queryCount = 2;

            string trustedRootFolder = string.Empty;

            // If a rootFolder was specified in the URL
            if (!string.IsNullOrWhiteSpace(encryptedRootFolder))
            {
                // Bump query count
                queryCount++;

                // Decrypt it (It is encrypted to help prevent direct access to filesystem).
                trustedRootFolder = Encryption.DecryptString(encryptedRootFolder);
            }

            // If we don't have a rootFolder, default to the ~/Content folder.
            if (string.IsNullOrWhiteSpace(trustedRootFolder))
            {
                trustedRootFolder = "~/Content";
            }

            // Get the absolute path for our trusted root.
            string trustedPhysicalRootFolder = Path.GetFullPath(context.Request.MapPath(trustedRootFolder));

            // Treat rooted file paths as relative
            string untrustedRelativeFilePath = untrustedFilePath.TrimStart(Path.GetPathRoot(untrustedFilePath).ToCharArray());

            // Get the absolute path for our untrusted file.
            string untrustedPhysicalFilePath = Path.GetFullPath(Path.Combine(trustedPhysicalRootFolder, untrustedRelativeFilePath));

            // Make sure the untrusted file is inside our trusted root folder.
            string trustedPhysicalFilePath = string.Empty;

            if (untrustedPhysicalFilePath.StartsWith(trustedPhysicalRootFolder))
            {
                // If so, then we can trust it.
                trustedPhysicalFilePath = untrustedPhysicalFilePath;
            }
            else
            {
                // Otherwise, say the file doesn't exist.
                SendNotFound(context);
                return;
            }

            // Try to open a file stream
            try
            {
                using (Stream fileContents = File.OpenRead(trustedPhysicalFilePath))
                {
                    if (fileContents != null)
                    {
                        string mimeType = MimeMapping.GetMimeMapping(trustedPhysicalFilePath);
                        context.Response.AddHeader("content-disposition", string.Format("inline;filename={0}", Path.GetFileName(trustedPhysicalFilePath)));
                        context.Response.ContentType = mimeType;

                        // If extra query string params are passed in and it isn't an SVG file, assume resize is needed
                        if ((context.Request.QueryString.Count > queryCount) && (mimeType != "image/svg+xml"))
                        {
                            using (var resizedStream = GetResized(context.Request.QueryString, fileContents))
                            {
                                resizedStream.CopyTo(context.Response.OutputStream);
                            }
                        }
                        else
                        {
                            fileContents.CopyTo(context.Response.OutputStream);
                        }

                        context.Response.Flush();
                        context.ApplicationInstance.CompleteRequest();
                    }
                    else
                    {
                        SendNotFound(context);
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex is ArgumentException || ex is ArgumentNullException || ex is NotSupportedException)
                {
                    SendBadRequest(context, "fileName is invalid.");
                }
                else if (ex is DirectoryNotFoundException || ex is FileNotFoundException)
                {
                    SendNotFound(context);
                }
                else if (ex is UnauthorizedAccessException)
                {
                    SendNotAuthorized(context);
                }
                else
                {
                    throw ex;
                }
            }
        }
        public void Execute(object requestMessage, ref object responseMessage, TransactionHeader transactionHeader)
        {
            GenerateSoftTokenRequest  request  = requestMessage as GenerateSoftTokenRequest;
            GenerateSoftTokenResponse response = responseMessage as GenerateSoftTokenResponse;
            VpOtpHistory otpHistory            = null;

            string hashedPassword = string.Empty;

            using (VeriBranchDataEntities context = new VeriBranchDataEntities())
            {
                var device = context.VpOtpDevice.Where(obj => obj.SerialNumber == request.DeviceId).FirstOrDefault();
                if (device == null)
                {
                    throw new VPBusinessException("DeviceNotExistException");
                }
                long userId = Convert.ToInt32(device.CreateBy);

                if (!string.IsNullOrEmpty(request.Password))
                {
                    hashedPassword = HashHelper.Hash(request.Password, string.Empty, HashTypeEnum.Md5);
                    if (context.VPSoftTokenRegistration.Where(obj => obj.UserId == userId && obj.Password == hashedPassword).FirstOrDefault() != null)
                    {
                        otpHistory = context.VpOtpHistory.Where(obj => obj.UserID == userId && obj.ExpireTime >= DateTime.Now).OrderByDescending(obj => obj.ID).FirstOrDefault();
                    }
                    else
                    {
                        throw new VPBusinessException("WrongPassword");
                    }
                }
                else if (string.IsNullOrEmpty(request.Password) && request.IsAuthenticatedWithFingerPrint)
                {
                    string autoPass = request.DeviceId + "true" + request.DeviceId; // 1 because AutoPassword should have set IsAuthenticatedWithFingerPrint
                    if (autoPass.Equals(request.AutoPassword))
                    {
                        otpHistory = context.VpOtpHistory.Where(obj => obj.UserID == userId && obj.ExpireTime >= DateTime.Now).OrderByDescending(obj => obj.ID).FirstOrDefault();
                    }
                    else
                    {
                        throw new VPBusinessException("WrongPassword");
                    }
                }
                else
                {
                    throw new VPBusinessException("WrongPassword");
                }
            }
            if (otpHistory != null || string.IsNullOrEmpty(otpHistory.EncryptedOTP))
            {
                string decryptedOTP = string.Empty;
                if (ConfigurationParametersPresenter.GetParameter(LoginConstants.FlowItemType.OTPEncryptionEnabledKey) != null)
                {
                    // these must be replaced by fetching certificate from store
                    string privateKey = Convert.ToString(ConfigurationParametersPresenter.GetParameter(LoginConstants.FlowItemType.EncryptionPrivateKey));
                    int    keySize    = Convert.ToInt32(ConfigurationParametersPresenter.GetParameter(LoginConstants.FlowItemType.EncryptionKeySizeKey));
                    decryptedOTP = Encryption.DecryptString(otpHistory.EncryptedOTP, privateKey);
                }
                response.OTP = decryptedOTP;
            }
            else
            {
                response.OTP = VeriBranch.Utilities.ConfigurationUtilities.ResourceHelper.GetGeneralMessage("NoOTPAvailable");
            }
        }
Beispiel #54
0
    protected void gvwEvaluations_InitializeRow(object sender, Infragistics.WebUI.UltraWebGrid.RowEventArgs e)
    {
        DataSet Ds = new DataSet( );

        Ds = SQLHelper.ExecuteDataset(Cache["ApplicationDatabase"].ToString( ), "GetEvaluatorbyEvaluated", new object[] { e.Row.Cells[e.Row.Cells.IndexOf("Legajo Evaluado")].ToString( ) });
        string evaluador = Ds.Tables[0].Rows[0].ItemArray[0].ToString( );
        string groupid   = Ds.Tables[0].Rows[0].ItemArray[1].ToString( );
        string url       = string.Empty;

        if ((e.Row.Cells.All[0] != null))
        {
            url = Server.HtmlEncode("./EvaluationFormLink.aspx?.=" + Server.UrlEncode(Encryption.Encrypt(groupid + ".2." + evaluador)));
        }

        Ds = SQLHelper.ExecuteDataset(Cache["ApplicationDatabase"].ToString( ), "GetEvaluationIdByEvaluated", new object[] { e.Row.Cells[e.Row.Cells.IndexOf("Legajo Evaluado")].ToString( ) });


        if (e.Row.Cells[e.Row.Cells.IndexOf("Estado")].ToString() != "Pendiente")
        {
            e.Row.Cells.FromKey("Link").Text      = "Visualización";
            e.Row.Cells.FromKey("Link").TargetURL = url;
        }
        else
        {
            e.Row.Cells.FromKey("Link").Text = "No disponible";
        }

        if (UserHelper.IsViewReport(Request.LogonUserIdentity.Name))
        {
            e.Row.Cells.FromKey("Reporte").Text      = "Ver Impresión";
            e.Row.Cells.FromKey("Reporte").TargetURL = Server.HtmlEncode("./PrintReport.aspx?EvaluationId=" + Ds.Tables[0].Rows[0].ItemArray[0].ToString());
        }
        else
        {
            e.Row.Cells.FromKey("Reporte").Text = "No disponible";
        }
    }
 /// <summary>
 /// You often implement utility methods that perform actions on
 /// that are associated with the current bus object.
 ///
 /// Not the best example - this is probably a better candidate
 /// for a app level utility function but used here to demonstrate
 /// </summary>
 /// <param name="plainPasswordText"></param>
 /// <returns></returns>
 public string EncodePassword(string plainPasswordText)
 {
     return(Encryption.EncryptString(plainPasswordText, "seeekret1092") + "~~");
 }
Beispiel #56
0
    public static bool Login(string username, string password)
    {
        if (!Constants.Initialized)
        {
            System.Windows.Forms.MessageBox.Show("Please initialize your application first!", OnProgramStart.Name, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
            Process.GetCurrentProcess().Kill();
        }
        if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
        {
            System.Windows.Forms.MessageBox.Show("Missing user login information!", ApplicationSettings.Name, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
            Process.GetCurrentProcess().Kill();
        }
        string[] response = new string[] { };
        using (WebClient wc = new WebClient())
        {
            try
            {
                Security.Start();
                wc.Proxy = null;
                response = (Encryption.DecryptService(Encoding.Default.GetString(wc.UploadValues(Constants.ApiUrl, new NameValueCollection
                {
                    ["token"] = Encryption.EncryptService(Constants.Token),
                    ["timestamp"] = Encryption.EncryptService(DateTime.Now.ToString()),
                    ["aid"] = Encryption.APIService(OnProgramStart.AID),
                    ["session_id"] = Constants.IV,
                    ["api_id"] = Constants.APIENCRYPTSALT,
                    ["api_key"] = Constants.APIENCRYPTKEY,
                    ["username"] = Encryption.APIService(username),
                    ["password"] = Encryption.APIService(password),
                    ["hwid"] = Encryption.APIService(Constants.HWID()),
                    ["session_key"] = Constants.Key,
                    ["secret"] = Encryption.APIService(OnProgramStart.Secret),
                    ["type"] = Encryption.APIService("login")
                }))).Split("|".ToCharArray()));
                if (response[0] != Constants.Token)
                {
                    System.Windows.Forms.MessageBox.Show("Security error has been triggered!", OnProgramStart.Name, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                    Process.GetCurrentProcess().Kill();
                }
                if (Security.MaliciousCheck(response[1]))
                {
                    System.Windows.Forms.MessageBox.Show("Possible malicious activity detected!", OnProgramStart.Name, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
                    Process.GetCurrentProcess().Kill();
                }
                if (Constants.Breached)
                {
                    System.Windows.Forms.MessageBox.Show("Possible malicious activity detected!", OnProgramStart.Name, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
                    Process.GetCurrentProcess().Kill();
                }
                switch (response[2])
                {
                case "success":
                    User.ID           = response[3];
                    User.Username     = response[4];
                    User.Password     = response[5];
                    User.Email        = response[6];
                    User.HWID         = response[7];
                    User.UserVariable = response[8];
                    User.Rank         = response[9];
                    User.IP           = response[10];
                    User.Expiry       = response[11];
                    User.LastLogin    = response[12];
                    User.RegisterDate = response[13];
                    string Variables = response[14];
                    foreach (string var in Variables.Split('~'))
                    {
                        string[] items = var.Split('^');
                        try
                        {
                            App1.Variables.Add(items[0], items[1]);
                        }
                        catch
                        {
                            //If some are null or not loaded, just ignore.
                            //Error will be shown when loading the variable anyways
                        }
                    }
                    Security.End();
                    return(true);

                case "invalid_details":
                    System.Windows.Forms.MessageBox.Show("Sorry, your username/password does not match!", ApplicationSettings.Name, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                    Security.End();
                    return(false);

                case "time_expired":
                    System.Windows.Forms.MessageBox.Show("Your subscription has expired!", ApplicationSettings.Name, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
                    Security.End();
                    return(false);

                case "hwid_updated":
                    System.Windows.Forms.MessageBox.Show("New machine has been binded, re-open the application!", ApplicationSettings.Name, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
                    Security.End();
                    return(false);

                case "invalid_hwid":
                    System.Windows.Forms.MessageBox.Show("This user is binded to another computer, please contact support!", ApplicationSettings.Name, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                    Security.End();
                    return(false);
                }
            }
            catch
            {
                System.Windows.Forms.MessageBox.Show("Failed to establish a secure SSL tunnel with the server!", ApplicationSettings.Name, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                Security.End();
                Process.GetCurrentProcess().Kill();
            }
            return(false);
        }
    }
Beispiel #57
0
        /// <summary>
        /// Saves the current XML data to the specified file. All XML data in the file will be overwritten.
        /// </summary>
        /// <param name="strFilePath"> FilePath to save to. If "" is passed in for strFilePath, then m_strXMLFileName
        ///  will be used for the path. Otherwise the default file name will be appended to the strFilePath</param>
        /// <returns>Whether or not the save was successful.</returns>
        // Revision History
        // MM/DD/YY who Version Issue# Description
        // -------- --- ------- ------ ---------------------------------------------
        // 05/27/08 jrf 1.50.28        Created
        //
        public override bool SaveSettings(string strFilePath)
        {
            bool         bReturn             = false;
            string       strTemp             = strFilePath;
            XmlDocument  xmldocTemp          = new XmlDocument();
            MemoryStream DecryptedStream     = new MemoryStream();
            FileStream   EncryptedStream     = null;
            Rijndael     EncryptionAlgorithm = null;

            try
            {
                if (1 > strFilePath.Length)
                {
                    strTemp = m_strXMLFileName;
                }
                else
                {
                    strTemp = strFilePath;
                }

                EncryptedStream     = new FileStream(strTemp, FileMode.Create);
                EncryptionAlgorithm = Rijndael.Create();

                SecureDataStorage DataStorage = new SecureDataStorage(SecureDataStorage.DEFAULT_LOCATION);

                //Set the key and IV properties
                EncryptionAlgorithm.Key = DataStorage.RetrieveSecureData(SecureDataStorage.REPLICA_KEY_ID);
                EncryptionAlgorithm.IV  = DataStorage.RetrieveSecureData(SecureDataStorage.REPLICA_IV_ID);

                Save(DecryptedStream);

                //Need to rewind stream before encrypting
                DecryptedStream.Position = 0;

                //Encrypt the data and write to the file
                Encryption.EncryptData(EncryptionAlgorithm, DecryptedStream, EncryptedStream);

                if (null != xmldocTemp)
                {
                    //Need to rewind stream before loading
                    DecryptedStream.Position = 0;

                    xmldocTemp.Load(DecryptedStream);

                    if (null != xmldocTemp.SelectSingleNode(DEFAULT_XML_ROOT_NODE))
                    {
                        bReturn = true;
                    }

                    xmldocTemp = null;
                }
            }
            catch
            {
                bReturn = false;
            }
            finally
            {
                if (null != EncryptionAlgorithm)
                {
                    EncryptionAlgorithm.Dispose();
                }

                if (null != DecryptedStream)
                {
                    DecryptedStream.Close();
                }

                if (null != EncryptedStream)
                {
                    EncryptedStream.Close();
                }
            }

            return(bReturn);
        }
Beispiel #58
0
        private void ConfigureProtectFunctionValues(FunctionDesigner designer, FileAuthentication protectAuth, Encryption encryption, bool dontEncryptMetadata,
                                                    bool addDocumentRestrictions = false, Printing printing = Printing.None, Changes changes = Changes.None, bool allowCopy = false, bool allowScreenReaders = false)
        {
            designer.Properties[PropertyNames.Operation].Value = Operation.Protect;

            switch (protectAuth)
            {
            case FileAuthentication.None:
                designer.Properties[PropertyNames.ProtectProtection].Value = AuthenticationType.None;
                return;

            case FileAuthentication.Password:
                designer.Properties[PropertyNames.ProtectProtection].Value           = AuthenticationType.Password;
                designer.Properties[PropertyNames.ProtectDocumentOpenPassword].Value = this.authenticationManager.Password;
                designer.Properties[PropertyNames.ProtectPermissionsPassword].Value  = permissionsPassword;
                break;

            case FileAuthentication.CertificateFile:
                designer.Properties[PropertyNames.ProtectProtection].Value              = AuthenticationType.Certificate;
                designer.Properties[PropertyNames.ProtectCertificateSource].Value       = CertificateSource.File;
                designer.Properties[PropertyNames.ProtectCertificateFilePath].Value     = this.authenticationManager.CertificateFilePath;
                designer.Properties[PropertyNames.ProtectCertificateFilePassword].Value = this.authenticationManager.CertificateFilePassword;
                break;

            case FileAuthentication.CertificateStore:
                designer.Properties[PropertyNames.ProtectProtection].Value        = AuthenticationType.Certificate;
                designer.Properties[PropertyNames.ProtectCertificateSource].Value = CertificateSource.Store;
                designer.Properties[PropertyNames.ProtectCertificate].Value       = this.authenticationManager.StoredCertificate;
                break;
            }

            designer.Properties[PropertyNames.ProtectEncryption].Value          = encryption;
            designer.Properties[PropertyNames.ProtectDontEncryptMetadata].Value = dontEncryptMetadata;

            designer.Properties[PropertyNames.ProtectAddDocumentRestrictions].Value = addDocumentRestrictions;
            designer.Properties[PropertyNames.ProtectAllowPrinting].Value           = printing;
            designer.Properties[PropertyNames.ProtectAllowChanges].Value            = changes;
            designer.Properties[PropertyNames.ProtectAllowCopying].Value            = allowCopy;
            designer.Properties[PropertyNames.ProtectAllowScreenReaders].Value      = allowScreenReaders;
        }