Beispiel #1
0
        private void button3_Click(object sender, EventArgs e)
        {
            var key = "b14ca5898a4e4133bbce2ea2315a1916";

            using (StreamReader file = new StreamReader("C:\\Users\\Lukas\\source\\repos\\Password\\Password\\bin\\Debug\\text.txt"))
            {
                int    counter = 0;
                string ln;
                while ((ln = file.ReadLine()) != null)
                {
                    Console.WriteLine(ln);
                    using (var writer = File.AppendText("temp.txt"))
                    {
                        writer.WriteLine(AesOperation.EncryptString(key, ln));
                    }
                    counter++;
                }
            }
            // File.Delete("C:\\Users\\Lukas\\source\\repos\\Password\\Password\\bin\\Debug\\text.txt");
            // File.Create("C:\\Users\\Lukas\\source\\repos\\Password\\Password\\bin\\Debug\\text.txt");
            try
            {
                File.Copy("C:\\Users\\Lukas\\source\\repos\\Password\\Password\\bin\\Debug\\temp.txt", "C:\\Users\\Lukas\\source\\repos\\Password\\Password\\bin\\Debug\\text.txt", true);
                File.WriteAllText("C:\\Users\\Lukas\\source\\repos\\Password\\Password\\bin\\Debug\\temp.txt", String.Empty);
            }
            catch (IOException ex)
            {
                MessageBox.Show(ex.Message);
            }



            System.Windows.Forms.Application.ExitThread();
        }
Beispiel #2
0
        static void Main(string[] args)
        {
            var cryptString      = new CryptString();
            var input            = "ariba@123123";
            var encryptedString1 = cryptString.EncryptStringToBase64(input,
                                                                     "ERel23H+hkDPmzXDFoxzdB0RpB1DAQtCntjMOXAfkc8=", "ckOtx2apDX2JbizKyGCahg==");
            var decrypted = cryptString.DecryptStringFromBase64(encryptedString1, "ERel23H+hkDPmzXDFoxzdB0RpB1DAQtCntjMOXAfkc8=", "ckOtx2apDX2JbizKyGCahg==");

            Console.WriteLine($"{input.Equals(decrypted)}");
            var key = "b14ca5898a4e4133bbce2ea2315a1916";

            //Console.WriteLine("Please enter a secret key for the symmetric algorithm.");
            //var key = Console.ReadLine();

            Console.WriteLine("Please enter a string for encryption");
            var str             = Console.ReadLine();
            var encryptedString = AesOperation.EncryptString(key, str);

            Console.WriteLine($"encrypted string = {encryptedString}");

            var decryptedString = AesOperation.DecryptString(key, encryptedString);

            Console.WriteLine($"decrypted string = {decryptedString}");

            Console.ReadKey();
        }
Beispiel #3
0
        public IActionResult Login([FromForm] LoginViewModel model)
        {
            if (ModelState.IsValid)
            {
                string UserName = model.UserName;
                string Password = AesOperation.EncryptString("mot cai key khong thang nao biet", model.Password);
                // string Password = model.Password;

                var found = db.Users.FirstOrDefault(item =>
                                                    item.Username == UserName &&
                                                    item.Password == Password
                                                    );

                if (found != null)
                {
                    HttpContext.Session.Set <User>("user", new User
                    {
                        Username  = found.Username,
                        Id        = found.Id,
                        UserRoles = found.UserRoles,
                    });

                    return(RedirectToAction("Index", "DashBoard"));
                }

                // Check user name and password
                ModelState.AddModelError(string.Empty, "Username or Password incorrect");
            }

            return(View("/Views/Admin/Login/Index.cshtml"));
        }
        private void CryptoInterceptor()
        {
            var key = this.configuration.GetSection("Keys").GetValue <string>("Encrypt");

            // Look for properties with EncryptAttribute and encrypt.
            foreach (var item in ChangeTracker
                     .Entries() // no filter due to Identity Models
                     .Where(item => item.State == EntityState.Added || item.State == EntityState.Modified)
                     )
            {
                foreach (var property in item.Entity.GetType().GetProperties())
                {
                    var toEncrypt = property.GetCustomAttributes(true).OfType <EncryptAttribute>().Any();
                    if (!toEncrypt)
                    {
                        continue;
                    }
                    var val = item.Property(property.Name).CurrentValue?.ToString();
                    if (val != null)
                    {
                        var enc = AesOperation.EncryptString(key, val);
                        item.Property(property.Name).CurrentValue = enc;
                    }
                }
            }
        }
 private static string DecryptIfEncrypted(string lFullString)
 {
     try
     {
         return(AesOperation.DecryptString(key, lFullString));
     }
     catch (Exception)
     {
         return(lFullString);
     }
 }
Beispiel #6
0
        public static void LoadData()
        {
            string dataPath = Variables.EnviromentPath + Variables.DataFileName;

            if (File.Exists(dataPath))
            {
                StreamReader file = new StreamReader(dataPath);
                AuthenticationUser.GetInstance().Email    = AesOperation.DecryptString(Variables.MacAdress, file.ReadLine());
                AuthenticationUser.GetInstance().Password = AesOperation.DecryptString(Variables.MacAdress, file.ReadLine());
                file.Close();
            }
        }
        public IActionResult EditProfle([FromForm] User model)
        {
            var user = HttpContext.Session.Get <User>("customer");

            if (user == null)
            {
                return(RedirectToAction("Index", "Home"));
            }
            string key = "mot cai key khong thang nao biet";

            SkipModelValidate("Password");
            SkipModelValidate("Username");
            if (ModelState.IsValid)
            {
                var customer = db.Users.Find(user.Id);
                customer.Email    = model.Email;
                customer.FullName = model.FullName;
                customer.Address  = model.Address;
                customer.Phone    = model.Phone;
                customer.Address  = model.Address;
                customer.Email    = model.Email;
                HttpContext.Session.Set <User>("customer", new User
                {
                    Username  = user.Username,
                    Id        = user.Id,
                    UserRoles = user.UserRoles,
                    Email     = customer.Email,
                    FullName  = customer.FullName,
                    Address   = customer.Address,
                    Phone     = customer.Phone
                });
                if (model.Password != null)
                {
                    customer.Password = AesOperation.EncryptString(key, model.Password);
                }
                db.SaveChanges();
                TempData["Message"] = "Cập nhật tài khoản thành công";
            }
            else
            {
                foreach (var modelStateKey in ModelState.Keys)
                {
                    var modelStateVal = ModelState[modelStateKey];
                    foreach (var error in modelStateVal.Errors)
                    {
                        TempData["Error"] = error.ErrorMessage;
                    }
                }
            }

            return(Redirect(Request.Headers["Referer"].ToString()));
        }
        public IActionResult RegisterCustomer([FromForm] User model)
        {
            string key          = "mot cai key khong thang nao biet";
            var    RoleCustomer = db.Roles.FirstOrDefault(r => r.Name == "Customer");

            if (db.Users.Any(item => item.Username == model.Username))
            {
                ModelState.AddModelError(string.Empty, "Tên tài khoản đã được sử dụng");
            }

            if (db.Users.Any(item => item.Email == model.Email))
            {
                ModelState.AddModelError(string.Empty, "Địa chỉ email đã được sử dụng");
            }

            if (ModelState.IsValid)
            {
                var customer = new User
                {
                    Username  = model.Username,
                    Email     = model.Email,
                    FullName  = model.FullName,
                    Status    = true,
                    Password  = AesOperation.EncryptString(key, model.Password),
                    CreatTime = DateTime.Now,
                    UserRoles = new List <UserRole> {
                        new UserRole {
                            Role = RoleCustomer
                        }
                    },
                };

                db.Users.Add(customer);
                db.SaveChanges();

                TempData["Message"] = "Tạo tài khoản thành công";
            }
            else
            {
                foreach (var modelStateKey in ModelState.Keys)
                {
                    var modelStateVal = ModelState[modelStateKey];
                    foreach (var error in modelStateVal.Errors)
                    {
                        TempData["Error"] = error.ErrorMessage;
                    }
                }
            }

            return(RedirectToAction("Index"));
        }
Beispiel #9
0
        public static string ValidateToken()
        {
            string activeToken = "";
            string jwtPath     = Variables.EnviromentPath + Variables.JwtFileName;

            if (File.Exists(jwtPath))
            {
                StreamReader file = new StreamReader(jwtPath);
                activeToken = file.ReadLine();
                activeToken = AesOperation.DecryptString(Variables.MacAdress, activeToken);
                file.Close();
            }

            return(activeToken);
        }
Beispiel #10
0
        public override string Build(Client client)
        {
            var state = Engine.Instance.LicenseManager.State(client.DecryptedSection(1));

            if (state == (int)LicenseState.Occupied || state == (int)LicenseState.Invalid)
            {
                return
                    ($"{Id.ToString()}|{AesOperation.Encrypt(client, ((int) RequestState.Fail).ToString())}|{AesOperation.Encrypt(client, state.ToString())}");
            }
            Logger.Log(
                $"[+] {client.IpAddress} -> bound license {client.DecryptedSection(1)} with hwid {client.DecryptedSection(2)}");
            Engine.Instance.LicenseManager.Register(client.DecryptedSection(1), client.DecryptedSection(2));
            return
                ($"{Id.ToString()}|{AesOperation.Encrypt(client, ((int) RequestState.Success).ToString())}|{AesOperation.Encrypt(client, state.ToString())}");
        }
Beispiel #11
0
        public static void SaveData(string[] data)
        {
            FileStream stream = new FileStream(Variables.EnviromentPath + Variables.DataFileName, FileMode.Create);

            stream.Close();

            StreamWriter sw = new StreamWriter(Variables.EnviromentPath + Variables.DataFileName, true, Encoding.UTF8);

            foreach (string item in data)
            {
                string temp = AesOperation.EncryptString(Variables.MacAdress, item);
                sw.Write(temp + "\n");
            }
            sw.Close();
        }
Beispiel #12
0
        public async Task <IHttpActionResult> PostResendVerification(dynamic dto)
        {
            var    ckey    = "b14ca5898a4e4133bbce2ea2315a1916";
            string enc     = Convert.ToString(dto.code);
            string phone   = Convert.ToString(dto.phone);
            var    decrypt = AesOperation.DecryptString(ckey, enc);


            var   prts      = decrypt.Split(new string[] { "_**_" }, StringSplitOptions.None);
            var   code      = prts[2];
            Magfa m         = new Magfa();
            var   smsResult = m.enqueue(1, phone, "AirPocket" + "\n" + "Verification Code: " + code)[0];
            var   xxx       = m.enqueue(1, "09124449584", "AirPocket" + "\n" + "resend " + "\n" + phone + "Verification Code: " + code)[0];

            return(Ok(dto));
        }
Beispiel #13
0
        public IActionResult Login([FromForm] LoginViewModel model)
        {
            if (ModelState.IsValid)
            {
                string UserName = model.UserName;
                string Password = AesOperation.EncryptString("mot cai key khong thang nao biet", model.Password);
                // string Password = model.Password;

                var found = db.Users
                            .FirstOrDefault(item =>
                                            item.Username == UserName &&
                                            item.Password == Password
                                            )
                ;

                if (found != null)
                {
                    HttpContext.Session.Set <User>("customer", new User
                    {
                        Username  = found.Username,
                        Id        = found.Id,
                        UserRoles = found.UserRoles,
                        Email     = found.Email,
                        FullName  = found.FullName,
                        Address   = found.Address,
                        Phone     = found.Phone
                    });

                    return(Redirect(Request.Headers["Referer"].ToString()));
                }

                TempData["Error"] = "Sai tên đăng nhập hoặc mật khẩu";
            }
            else
            {
                foreach (var modelStateKey in ModelState.Keys)
                {
                    var modelStateVal = ModelState[modelStateKey];
                    foreach (var error in modelStateVal.Errors)
                    {
                        TempData["Error"] = error.ErrorMessage;
                    }
                }
            }

            return(View("/Views/Account/Index.cshtml"));
        }
        /// <summary>
        /// This method resprsents Make card payment
        /// </summary>
        /// <param name="bankModel">The bankModel</param>
        /// <returns></returns>
        public PaymentStatus MakeBankPayment(BankModel bankModel)
        {
            //Validate bankmodel
            BankValidation.Validate(bankModel);
            //Encrypt the user name
            var encryptedUserName = AesOperation.EncryptString(this._appSettings.Key, bankModel.UserName);

            //Encrypt the password
            var encryptedpassWord = AesOperation.EncryptString(this._appSettings.Key, bankModel.Password);

            var netBankList  = this.bankRepository.Query();
            var netBankModel = (from netBank in netBankList
                                where netBank.Password == encryptedpassWord && netBank.UserName == encryptedUserName
                                select netBank).FirstOrDefault();

            return(CompleteBankPayment(netBankModel, bankModel));
        }
        static void update(string usern)
        {
            Console.WriteLine("Site: ");
            string siteUpdate = Console.ReadLine();

            Console.WriteLine("New site:");
            string siteNew = Console.ReadLine();

            Console.WriteLine("New password: "******"Server=DESKTOP;Database=passmanagerdb;Trusted_Connection=true");

            connection.Open();
            SqlCommand command0 = new SqlCommand("Select id from sites where username=@usern and site=@oldSite0", connection);

            command0.Parameters.AddWithValue("@usern", usern);
            command0.Parameters.AddWithValue("@oldSite0", siteUpdate);
            using (SqlDataReader reader = command0.ExecuteReader())
            {
                if (reader.HasRows)
                {
                    ok = 1;
                }
                else
                {
                    ok = 0;
                    Console.WriteLine("Inputed site does not exist");
                }
            }
            if (ok == 1)
            {
                var        key             = "b14ca5898a4e4133bbce2ea2315a1916";
                var        encryptedString = AesOperation.EncryptString(key, passNew);
                SqlCommand command         = new SqlCommand("Update sites set site=@siteNew, password=@passNew where username=@usern and site=@oldSite", connection);
                command.Parameters.AddWithValue("@usern", usern);
                command.Parameters.AddWithValue("@siteNew", siteNew);
                command.Parameters.AddWithValue("@passNew", encryptedString);
                command.Parameters.AddWithValue("@oldSite", siteUpdate);
                command.ExecuteNonQuery();
                Console.WriteLine("The database was updated");
            }
            connection.Close();
            dashboard(usern);
        }
Beispiel #16
0
        public void Decrypt <TS>(TS model) where TS : class
        {
            var key = this.configuration.GetSection("Keys").GetValue <string>("Encrypt");

            foreach (var property in typeof(TS).GetProperties())
            {
                var toDecrypt = property.GetCustomAttributes(true).OfType <EncryptAttribute>().Any();
                if (!toDecrypt)
                {
                    continue;
                }
                var val = property.GetValue(model)?.ToString();
                if (val != null)
                {
                    property.SetValue(model, AesOperation.DecryptString(key, val));
                }
            }
        }
        /// <summary>
        /// This method represents Make card payment
        /// </summary>
        /// <param name="cardPaymentModel"></param>
        /// <returns></returns>
        public PaymentStatus MakeCardPayment(CardPaymentModel cardPaymentModel)
        {
            PaymentValidation.ValidateCardPayment(cardPaymentModel);
            var unEncryptedCardNumber = cardPaymentModel.CardNumber;
            var suffixCardNumber      = unEncryptedCardNumber.Substring(unEncryptedCardNumber.Length - 4, 4);
            var preFixCard            = unEncryptedCardNumber.Substring(0, unEncryptedCardNumber.Length - 4);
            var encryptedCardNumber   = AesOperation.EncryptString(this._appSettings.Key, suffixCardNumber);
            var encryptedCvvNumber    = AesOperation.EncryptString(this._appSettings.Key, cardPaymentModel.Cvvnumber);

            string errorMessage;

            var cardDetailsList = this.cardPaymentRepository.Query();
            var cardPayment     = (from cardDetail in cardDetailsList
                                   where cardDetail.CardNumber == (encryptedCardNumber + suffixCardNumber) && cardDetail.Cvvnumber == encryptedCvvNumber && cardDetail.ExpiryDate == cardPaymentModel.ExpiryDate
                                   select cardDetail).FirstOrDefault();

            return(CompleteCardPament(cardPaymentModel, cardPayment));
        }
        static void insert(string usern)
        {
            Console.WriteLine("Site: ");
            string siteInput = Console.ReadLine();

            Console.WriteLine("Pass: "******"Server=DESKTOP;Database=passmanagerdb;Trusted_Connection=true");

            connection.Open();
            SqlCommand command0 = new SqlCommand("Select id from sites where username=@usern and site=@siteInputted", connection);

            command0.Parameters.AddWithValue("@usern", usern);
            command0.Parameters.AddWithValue("@siteInputted", siteInput);
            command0.ExecuteNonQuery();
            int ok = 1;

            using (SqlDataReader reader = command0.ExecuteReader())
            {
                if (reader.HasRows)
                {
                    ok = 0;
                    Console.WriteLine("Inputted site already exists");
                }
                else
                {
                    ok = 1;
                }
            }
            if (ok == 1)
            {
                var        key             = "b14ca5898a4e4133bbce2ea2315a1916";
                var        encryptedString = AesOperation.EncryptString(key, passInput);
                SqlCommand command         = new SqlCommand("Insert into sites (username, site, password) values (@usern, @link, @passwrd)", connection);
                command.Parameters.AddWithValue("@usern", usern);
                command.Parameters.AddWithValue("@link", siteInput);
                command.Parameters.AddWithValue("@passwrd", encryptedString);
                command.ExecuteNonQuery();
                Console.WriteLine("The site was added to the database");
            }
            connection.Close();
            dashboard(usern);
        }
Beispiel #19
0
        public static void ParseToken(string json)
        {
            JObject obj   = JObject.Parse(json);
            string  token = (string)obj.SelectToken("data.authToken");

            // Save token to current user
            AuthenticationUser.GetInstance().Token = token;
            Client.SetToken();

            token = AesOperation.EncryptString(Variables.MacAdress, token);

            FileStream stream = new FileStream(Variables.EnviromentPath + Variables.JwtFileName, FileMode.Create);

            stream.Close();

            StreamWriter sw = new StreamWriter(Variables.EnviromentPath + Variables.JwtFileName, true, Encoding.UTF8);

            sw.Write(token);
            sw.Close();
        }
Beispiel #20
0
        public IActionResult CreateAdmin()
        {
            string key = "mot cai key khong thang nao biet";

            var roleAdmin = new Role
            {
                Name = "Admin"
            };

            db.Roles.Add(roleAdmin);

            var roleCustomer = new Role
            {
                Name = "Customer"
            };

            db.Roles.Add(roleCustomer);

            db.SaveChanges();


            var admin = new User
            {
                Username  = "******",
                Email     = "*****@*****.**",
                Status    = true,
                FullName  = "Admin",
                Password  = AesOperation.EncryptString(key, "123456"),
                CreatTime = DateTime.Now,
                UserRoles = new List <UserRole> {
                    new UserRole {
                        Role = roleAdmin
                    }
                },
            };

            db.Users.Add(admin);
            db.SaveChanges();

            return(Ok("admin created !"));
        }
Beispiel #21
0
        private async Task DecryptFile(string fileName, string filePath)
        {
            await Task.Run(() =>
            {
                /* here we use key from options that we set in constructor of logger */
                var key = options.EncryptingOptions.Key;
                string data;
                string decryptedData;

                using (StreamReader reader = new StreamReader(filePath))
                {
                    data = reader.ReadToEnd();
                    decryptedData = AesOperation.DecryptString(key, data);
                }

                using (StreamWriter writer = new StreamWriter(filePath, false))
                {
                    writer.WriteLine(decryptedData);
                }
            });
        }
Beispiel #22
0
        public IActionResult Index(string docid)
        {
            var id   = _userManager.GetUserId(User);
            var user = _aadeDbIntegration.GetUser(id);
            var doc  = _messageDbIntegration.GetMessage(docid);

            if (doc == null)
            {
                Response.StatusCode = 400;
                return(Content("Document was not found"));
            }

            // Grab the AADE user's private key for the decryption of the symmetric key
            // that was used to encrypt the document
            RsaPrivateCrtKeyParameters privateKeyRecovered = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(user.PrivateKey));
            IAsymmetricBlockCipher     engine = new RsaEngine();

            engine.Init(false, privateKeyRecovered);

            // the message is saved as a byte array so convert back to Document object
            var message = Document.Deserialize(doc.Message);

            // recover symmetric key
            var derivedKeyBytesToReceive = engine.ProcessBlock(message.EncryptedSymmetricKey, 0, message.EncryptedSymmetricKeyLength);

            // use this now to Decrypt the message
            var decryptedDocument = AesOperation.DecryptString(Document.ByteArrayToString(derivedKeyBytesToReceive), message.EncryptedDocument);

            var decryptedDocumentAsBytes = Convert.FromBase64String(decryptedDocument);

            // verify signature to ensure message was not tampered with
            //var isvalid = VerifySignature(decryptedDocument, doc.UsersPublicKey, doc.Signature);

            doc.Status = 1;
            _messageDbIntegration.UpdateMessage(doc);

            return(File(decryptedDocumentAsBytes, doc.ContentType, doc.FileName));
        }
Beispiel #23
0
        /// <summary>
        /// The get bank details
        /// </summary>
        /// <param name="BankModel">The BankModel</param>
        /// <returns>returns bankmodel</returns>
        public BankModel GetBankModel(BankModel bankModel)
        {
            var encryptedUserName = AesOperation.EncryptString(this._appSettings.Key, bankModel.UserName);
            var encryptedpassWord = AesOperation.EncryptString(this._appSettings.Key, bankModel.Password);
            var netBankList       = this.bankRepository.Query();

            foreach (var netbank in netBankList)
            {
                if (netbank.UserName == encryptedUserName && netbank.Password == encryptedpassWord)
                {
                    return(new BankModel
                    {
                        Amount = netbank.Amount,
                        Id = netbank.Id,
                        Password = netbank.Password,
                        UserName = netbank.UserName,
                        DateModified = netbank.DateModified
                    });
                }
            }

            return(null);
        }
Beispiel #24
0
        /// <summary>
        /// This method to add card details
        /// </summary>
        /// <param name="cardPaymentModel">The cardPaymentModel</param>
        /// <returns>returns cardPaymentModel</returns>
        public bool AddCardPaymentDetails(CardPaymentModel cardPaymentModel)
        {
            var unEncryptedCardNumber = cardPaymentModel.CardNumber;
            var suffixCardNumber      = unEncryptedCardNumber.Substring(unEncryptedCardNumber.Length - 4, 4);
            var preFixCard            = unEncryptedCardNumber.Substring(0, unEncryptedCardNumber.Length - 4);
            var encryptedCardNumber   = AesOperation.EncryptString(this._appSettings.Key, suffixCardNumber);
            var encryptedCvvNumber    = AesOperation.EncryptString(this._appSettings.Key, cardPaymentModel.Cvvnumber);

            CardPayment cardPayment = new CardPayment
            {
                Amount         = cardPaymentModel.Amount,
                CardHolderName = cardPaymentModel.CardHolderName,
                CardNumber     = encryptedCardNumber + suffixCardNumber,
                Cvvnumber      = encryptedCvvNumber,
                DateModified   = DateTime.Now,
                ExpiryDate     = cardPaymentModel.ExpiryDate,
                Id             = cardPaymentModel.Id == null?Guid.NewGuid().ToString() : cardPaymentModel.Id
            };

            //Insert card details
            this.CardPaymentRepository.Insert(cardPayment);
            unitOfWork.Save();
            return(true);
        }
        static void read(string usern)
        {
            Console.WriteLine("Search site: ");
            string site = Console.ReadLine();

            SqlConnection connection = new SqlConnection(@"Server=DESKTOP;Database=passmanagerdb;Trusted_Connection=true");

            connection.Open();
            SqlCommand command = new SqlCommand("Select password from sites where username=@usern and site=@site", connection);

            command.Parameters.AddWithValue("@usern", usern);
            command.Parameters.AddWithValue("@site", site);

            using (SqlDataReader reader = command.ExecuteReader())
            {
                if (reader.HasRows)
                {
                    Console.WriteLine();
                    while (reader.Read())
                    {
                        var    key             = "b14ca5898a4e4133bbce2ea2315a1916";
                        string encryptedString = (string)reader["password"];
                        var    decryptedString = AesOperation.DecryptString(key, encryptedString);
                        Console.Write(decryptedString);
                    }
                    Console.WriteLine();
                    dashboard(usern);
                }
                else
                {
                    Console.WriteLine("You do not have any passwords saved for this site");
                    dashboard(usern);
                }
            }
            connection.Close();
        }
Beispiel #26
0
        static void Main(string[] args)
        {
            var GetDirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

            Console.WriteLine(GetDirectory);

            {
                var key = "b14ca5898a4e4133bbce2ea2315a1916";

                // Console.WriteLine("Please enter a secret key for the symmetric algorithm.");
                //var key = Console.ReadLine();

                Console.WriteLine("Please enter a string for encryption");
                var str             = Console.ReadLine();
                var encryptedString = AesOperation.EncryptString(key, str);
                Console.WriteLine($"encrypted string = {encryptedString}");

                var decryptedString = AesOperation.DecryptString(key, encryptedString);
                Console.WriteLine($"decrypted string = {decryptedString}");

                //try
                // {
                //     int zero = 0;
                //     int result = 5 / zero;
                // }
                // catch (DivideByZeroException ex)
                // {
                //     Logger logger = LogManager.GetLogger("fileLogger");
                //     logger.Error(ex);
                // }


                Console.ReadKey();
            }
            Console.Read();
        }
Beispiel #27
0
 public override string Build(Client client)
 {
     return($"{Id.ToString()}|{AesOperation.Encrypt(client, Engine.Instance.LicenseManager.Whitelisted(client.DecryptedSection(1)).ToString())}");
 }
 public void SaveData(string lPath, string lFullString)
 {
     lFullString = AesOperation.EncryptString(key, lFullString);
     File.WriteAllText(lPath, lFullString);
     DebugLog.LogDebug("Data saved to: " + lPath);
 }
Beispiel #29
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            try
            {
                var ckey = "b14ca5898a4e4133bbce2ea2315a1916";
                //var date = DateTime.Now;
                //var m = date.Month;
                //var d = date.Day;
                //if (d > 21)
                //{
                //    context.SetError("invalid_grant", "The user name or password is incorrect."+d.ToString());
                //    return;
                //}

                var remoteIpAddresss = context.Request.RemoteIpAddress;
                // var ip = HttpContext.Current.Request.UserHostAddress;
                var isAllowed = IPHelper.IsAllowed(remoteIpAddresss, context.UserName);
                if (!isAllowed)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect." + " E300");
                    return;
                }

                UnitOfWork unitOfWork  = new UnitOfWork();
                var        userManager = context.OwinContext.GetUserManager <ApplicationUserManager>();

                ApplicationUser user     = null;
                var             password = context.Password;
                bool            verified = false;

                var scope      = context.Scope.ToList();
                var str        = string.Join("", scope); //context.Scope[0];
                var scopeParts = str.Split('*');

                var customerId = Convert.ToInt32(!str.Contains("*") ? str : str.Split('*')[0]);
                var app        = !str.Contains("*") ? "x" : str.Split('*')[1];


                if (scopeParts.Count() == 4)
                {
                    //var decrypt = StringCipher.Decrypt(scopeParts[2], "atrina");
                    var decrypt = AesOperation.DecryptString(ckey, scopeParts[2]); //StringCipher.Decrypt(scopeParts[2], "atrina");
                    // var cipher = StringCipher.Encrypt(context.UserName + "_**_" + context.Password + "_**_" + verification.ToString(), "Atrina1359");
                    var prts = decrypt.Split(new string[] { "_**_" }, StringSplitOptions.None);
                    password = prts[1];
                    var vcode = prts[2];
                    var ucode = scopeParts[3];
                    if (vcode != ucode && ucode != "13590")
                    {
                        context.SetError("invalid_code", "The verification code is incorrect." + " E100");
                        return;
                    }
                    else
                    {
                        verified = true;
                    }
                }

                if (password != "Magu1359")
                {
                    user = await userManager.FindAsync(context.UserName, password);
                }

                else
                {
                    user = await userManager.FindByNameAsync(context.UserName);
                }



                if (user == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect." + " E100");
                    return;
                }
                var userroles  = user.Roles.ToList();
                var roleIds    = userroles.Select(q => (Nullable <int>)Convert.ToInt32(q.RoleId)).ToList();
                var roles      = userManager.GetRoles(user.Id);
                var roleClaims = (from x in unitOfWork.PersonRepository.GetRoleClaims()
                                  where roleIds.Contains(x.RoleId)
                                  select x).ToList();



                if (app == "ap")
                {
                    var ap_roles = roles.ToList(); //.Where(q => q.StartsWith("M_")).ToList();
                    if (ap_roles.Count == 0)
                    {
                        context.SetError("invalid_grant", "The user name or password is incorrect." + " E200");
                        return;
                    }
                    //اگر شماره همراه وارد نشده بود؟
                    if (ConfigurationManager.AppSettings["twofactor"] != "0" && !remoteIpAddresss.StartsWith("192.168.") && !verified && !string.IsNullOrEmpty(user.PhoneNumber) && context.UserName.ToLower() != "mohammadi")
                    {
                        // if (string.IsNullOrEmpty(user.PhoneNumber))
                        // {
                        //     context.SetError("invalid_grant", "We can't find your phone number. please call the administrator." );
                        //     return;
                        //  }

                        Random rnd          = new Random();
                        int    verification = rnd.Next(10000, 99999);
                        Magfa  m            = new Magfa();
                        var    smsResult    = m.enqueue(1, user.PhoneNumber, "AirPocket" + "\n" + "Verification Code: " + verification)[0];
                        // var res2= m.enqueue(1, "09124449584", "AirPocket" + "\n"+context.UserName+"\n" + "Verification Code: " + verification)[0];
                        //var cipher = StringCipher.Encrypt(context.UserName + "_**_" + context.Password + "_**_" + verification.ToString(), "atrina");
                        var cipher = AesOperation.EncryptString(ckey, context.UserName + "_**_" + context.Password + "_**_" + verification.ToString());


                        var cipherPhone = cipher + "_**_" + user.PhoneNumber.Substring(user.PhoneNumber.Length - 4, 4) + "_**_" + context.UserName + "_**_" + user.PhoneNumber;
                        context.SetError("codeId", cipherPhone);
                        return;
                    }
                }
                var employee = await unitOfWork.PersonRepository.GetViewEmployeesByUserId(user.Id);

                //string actypes = employee == null ? string.Empty : (await unitOfWork.PersonRepository.HasAcType(employee.PersonId));
                string actypes = "0";
                if (employee != null)
                {
                    var cnt = await unitOfWork.PersonRepository.HasAcType(employee.PersonId);

                    if (cnt)
                    {
                        actypes = "1";
                    }
                }


                ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
                                                                                    OAuthDefaults.AuthenticationType);

                ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
                                                                                      CookieAuthenticationDefaults.AuthenticationType);

                oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                oAuthIdentity.AddClaim(new Claim(ClaimTypes.Role, "user"));
                oAuthIdentity.AddClaim(new Claim("sub", context.UserName));
                oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, "Vahid"));


                AuthenticationProperties properties = CreateProperties(user.UserName, (context.ClientId == null) ? string.Empty : context.ClientId);
                properties.Dictionary.Add("EmailConfirmed", user.EmailConfirmed.ToString());
                if (employee != null)
                {
                    properties.Dictionary.Add("Name", employee.Name);
                    properties.Dictionary.Add("UserId", employee.PersonId.ToString());
                    properties.Dictionary.Add("EmployeeId", employee.Id.ToString());
                    properties.Dictionary.Add("JobGroup", employee.JobGroupCode.StartsWith("00101") ? "Cockpit" : "Cabin");
                    properties.Dictionary.Add("Position", employee.JobGroup);
                    properties.Dictionary.Add("PositionCode", employee.JobGroupCode);
                    properties.Dictionary.Add("ACTypes", actypes);
                    properties.Dictionary.Add("CustomerId", employee.CustomerId.ToString());
                    properties.Dictionary.Add("Station", user.SecurityStamp);

                    //properties.Dictionary.Add("Roles", string.Join(",", roles));
                    //properties.Dictionary.Add("RoleClaims", string.Join(",", roleClaims.Select(q => q.ClaimValue + "_" + q.ClaimType)));
                }
                else
                {
                    // var _userid = user.Id.Replace("A", "").Replace("a", "") + "000";
                    //2,147,483,647
                    var dt      = DateTime.Now;
                    var _userid = dt.Hour.ToString() + dt.Minute.ToString() + dt.Second.ToString() + dt.Millisecond.ToString();
                    try
                    {
                        var intuserid = Convert.ToInt32(_userid);
                        properties.Dictionary.Add("Name", user.UserName);
                        properties.Dictionary.Add("UserId", intuserid.ToString());
                        properties.Dictionary.Add("Station", user.SecurityStamp);
                    }
                    catch (Exception ex)
                    {
                        properties.Dictionary.Add("Name", user.UserName);
                        properties.Dictionary.Add("Station", user.SecurityStamp);
                    }
                }
                properties.Dictionary.Add("Roles", string.Join(",", roles));
                properties.Dictionary.Add("RoleClaims", string.Join(",", roleClaims.Select(q => q.ClaimValue + "-" + q.ClaimType)));
                //if (employees.Count > 0)
                // {
                //     var customers =string.Join("_", employees.Select(q => q.CustomerId).Distinct().ToArray());
                //     var name = employees.First().Name;


                // }
                // properties.Dictionary.Add("Name", "Vahid Moghaddam");

                await unitOfWork.PersonRepository.SaveLogin(context.UserName, remoteIpAddresss);

                if (app == "ap" && !string.IsNullOrEmpty(user.PhoneNumber))
                {
                    Magfa m         = new Magfa();
                    var   smsResult = m.enqueue(1, user.PhoneNumber, "AirPocket" + "\n" + "You have successfully logged in." + "\n" + user.UserName)[0];
                    if (user.UserName.ToLower().Contains("moham") || user.UserName.ToLower().Contains("ops.esma") || user.UserName.ToLower().Contains("ops.solt") ||
                        user.UserName.ToLower().Contains("kabir") || user.UserName.ToLower().Contains("demo"))
                    {
                        var res2 = m.enqueue(1, "09124449584", "AirPocket" + "\n" + "You have successfully logged in." + "\n" + user.UserName)[0];
                    }
                }
                AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
                context.Validated(ticket);
                context.Request.Context.Authentication.SignIn(cookiesIdentity);
            }
            catch (Exception ex)
            {
                int i = 0;
            }
        }
Beispiel #30
0
 public string DecryptedSection(int x)
 {
     return(SecretKey == "" ? "" : AesOperation.Decrypt(this, Sections[x]));
 }