Inheritance: IDisposable
        public ActionResult CheckOut(CheckOutViewModel model)
        {
            if (ModelState.IsValid)
            {
                var order            = ProcessCheckOut(model, cartManager.MyCart);
                var orderNo          = orderProvider.CreateOrderFromCart(order);
                var encryptedOrderNo = RijndaelHelper.Encrypt(orderNo,
                                                              ConfigurationInstance[ConfigurationKeys.CryptographyKey]);
                string returnUrl = String.Format("{0}?o={1}", Url.Action("CheckOutSuccess"), encryptedOrderNo);

                return(Json(new
                {
                    Error = false,
                    OrderNo = orderNo,
                    ReturnUrl = returnUrl
                }));
            }

            var allErrors = ModelState.Values.SelectMany(v => v.Errors).Select(o => o.ErrorMessage);

            return(Json(new
            {
                Error = true,
                Errors = allErrors
            }));
        }
Esempio n. 2
0
        public User ValidateLogin(LoginViewModel model)
        {
            string encryptedPassword = RijndaelHelper.Encrypt(model.Password, cryptographyKey);

            var user = new User();
            //get username with loginname
            var currentUser = AllUsers.SingleOrDefault(us => us.LoginName == model.LoginName && !us.DelDate.HasValue);

            if (currentUser != null)
            {
                if (currentUser.Password == encryptedPassword)
                {
                    user = AllUsers.SingleOrDefault(x => x.UserName == currentUser.UserName && x.Password == encryptedPassword);
                }
                else
                {
                    return(null);
                }
            }
            else
            {
                return(null);
            }
            return(user);
        }
        public ActionResult PaymentConfirmation(FormCollection form, PaymentConfirmationViewModel model)
        {
            if (ModelState.IsValid)
            {
                bool paymentConfirmationIsValid = orderProvider.ValidateOrderPayment(
                    model.OrderNo,
                    model.PayAmount);
                if (paymentConfirmationIsValid)
                {
                    if (!orderProvider.IsOrderPaymentConfirmed(model.OrderNo))
                    {
                        orderProvider.CreatePaymentConfirmation(model.OrderNo, model.BankId, 2, model.PaymentDate,
                                                                model.SenderName, model.PayAmount, null);
                        string encryptedOrderNo = RijndaelHelper.Encrypt(model.OrderNo, CryptographyKey);
                        return(RedirectToAction("PaymentConfirmationSuccess", new { token = encryptedOrderNo }));
                    }
                    ModelState.AddModelError(String.Empty,
                                             String.Format("Payment confirmation for order {0} has been created already.", model.OrderNo));
                    return(RedirectToAction("PaymentConfirmation"));
                }
                ModelState.AddModelError(String.Empty, String.Format("Invalid Payment for Order {0}", model.OrderNo));
                return(RedirectToAction("PaymentConfirmation"));
            }

            return(View(model));
        }
        public void AddOrUpdateEmployee(int id,
                                        string userName,
                                        string name,
                                        string gender,
                                        string email,
                                        int roleID,
                                        bool isAllowLogin,
                                        bool isActive,
                                        IDictionary <int, string> cellPhones)
        {
            var employee = id == 0 ? new Employee() : context.Employees.Single(emp => emp.ID == id);

            employee.UserName     = userName;
            employee.RoleID       = roleID;
            employee.Name         = name;
            employee.Gender       = gender;
            employee.Email        = email;
            employee.IsAllowLogin = isAllowLogin;
            employee.IsActive     = isActive;
            employee.CellPhone1   = cellPhones[1];
            employee.CellPhone2   = cellPhones[2];
            EntityHelper.SetAuditFields(id, employee, CurrentUserName);

            if (id == 0)
            {
                employee.Password = isAllowLogin ? RijndaelHelper.Encrypt("mustchange", cryptographyKey) : String.Empty;
                context.Employees.InsertOnSubmit(employee);
            }

            context.SubmitChanges();
        }
Esempio n. 5
0
        public virtual string GetProtocolUrl()
        {
            string json = SerializeObject();

            json = RijndaelHelper.Encrypt(json);

            return(string.Format("{0}://{1}", ProtocolName, json));
        }
        protected override void DoSetUp()
        {
            sender    = new Sender();
            receiver  = new Receiver();
            transport = new RijndaelEncryptionTransportDecorator(sender, receiver, KeyBase64);

            Console.WriteLine(RijndaelHelper.GenerateNewKey());
        }
Esempio n. 7
0
        public void ResetPassword(int employeeID)
        {
            var employee = repository.Single <Employee>(emp => emp.ID == employeeID);

            employee.Password = RijndaelHelper.Encrypt(ConfigurationManager.AppSettings[ApplicationSettingKeys.DefaultPassword],
                                                       ConfigurationManager.AppSettings[ApplicationSettingKeys.CryptographyKey]);
            repository.SetAuditFieldsForUpdate(employee, principal.Identity.Name);
            repository.UnitOfWork.SaveChanges();
        }
Esempio n. 8
0
        public static void CreateKeyVector_KeySize_OutOfRange(int keySize)
        {
            // Arrange

            // Act
            Assert.Throws <ArgumentOutOfRangeException>(()
                                                        => RijndaelHelper.CreateKeyVector("test", keySize));

            // Assert
        }
        public bool ValidateUser(string userName, string password, string cryptographyKey)
        {
            var employee = context.Employees.SingleOrDefault(emp => emp.UserName == userName && emp.IsAllowLogin);

            if (employee != null)
            {
                var clearPassword = RijndaelHelper.Decrypt(employee.Password, cryptographyKey);
                return(clearPassword == password);
            }
            return(false);
        }
Esempio n. 10
0
        public bool ValidateUser(string userName, string password, string cryptographyKey)
        {
            var employee = repository.FindOne <Employee>(emp => emp.UserName == userName && emp.IsAllowLogin);

            if (employee != null)
            {
                var clearPassword = RijndaelHelper.Decrypt(employee.Password, cryptographyKey);
                return(clearPassword == password);
            }
            return(false);
        }
        public void ChangePassword(string userName, string newPassword, string cryptographyKey)
        {
            var employee = context.Employees.SingleOrDefault(emp => emp.UserName == userName);

            if (employee != null)
            {
                employee.Password = RijndaelHelper.Encrypt(newPassword, cryptographyKey);
                EntityHelper.SetAuditFieldsForUpdate(employee, userName);
            }
            context.SubmitChanges();
        }
Esempio n. 12
0
        public void ChangePassword(string userName, string newPassword, string cryptographyKey)
        {
            var employee = repository.FindOne <Employee>(emp => emp.UserName == userName);

            if (employee != null)
            {
                employee.Password = RijndaelHelper.Encrypt(newPassword, cryptographyKey);
                repository.SetAuditFieldsForUpdate(employee, userName);
            }
            repository.UnitOfWork.SaveChanges();
        }
Esempio n. 13
0
        public static void CreateKeyVector(string key, string iv, int keySize, string passphrase)
        {
            // Arrange

            // Act
            var result = RijndaelHelper.CreateKeyVector(passphrase, keySize);

            // Assert
            Assert.Equal(key, Convert.ToBase64String(result.First));
            Assert.Equal(iv, Convert.ToBase64String(result.Second));
        }
 public void UseCase()
 {
     //These two values should not be hard coded in your code.
     byte[] key    = { 251, 9, 67, 117, 237, 158, 138, 150, 255, 97, 103, 128, 183, 65, 76, 161, 7, 79, 244, 225, 146, 180, 51, 123, 118, 167, 45, 10, 184, 181, 202, 190 };
     byte[] vector = { 214, 11, 221, 108, 210, 71, 14, 15, 151, 57, 241, 174, 177, 142, 115, 137 };
     using (var rijndaelHelper = new RijndaelHelper(key, vector))
     {
         var encrypt = rijndaelHelper.Encrypt("StringToEncrypt");
         var decrypt = rijndaelHelper.Decrypt(encrypt);
         Assert.AreEqual("StringToEncrypt", decrypt);
     }
 }
Esempio n. 15
0
        public static void CreateDecryptor()
        {
            // Arrange
            var provider = new RijndaelManaged();

            // Act
            var result = RijndaelHelper.CreateDecryptor(provider, "sdf2qw2@", 256);

            // Assert
            Assert.NotNull(result);
            result.Dispose();
            provider.Clear();
        }
Esempio n. 16
0
        private static bool Verify(byte[] signedaddon, out SignedAddonHeader header, out byte[] assembly)
        {
            using (var stream = new MemoryStream(signedaddon))
            {
                using (var reader = new BinaryReader(stream))
                {
                    using (var rsaProvider = new RSACryptoServiceProvider(new CspParameters {
                        ProviderType = 1
                    }))
                    {
                        using (var sha1 = new SHA1CryptoServiceProvider())
                        {
                            rsaProvider.ImportCspBlob(Convert.FromBase64String(PublicKey));

                            var headerBuffer   = reader.ReadBytes(Marshal.SizeOf(typeof(SignedAddonHeader)));
                            var assemblyBuffer = reader.ReadBytes(signedaddon.Length - headerBuffer.Length);
                            header = DeserializeStructure <SignedAddonHeader>(headerBuffer);

                            bool result;

                            switch (header.Data.SignatureVersion)
                            {
                            case "2":
                                const int signatureSize = 320;
                                var       verifyBuffer  = new byte[signedaddon.Length - signatureSize];
                                Array.Copy(signedaddon, signatureSize, verifyBuffer, 0, verifyBuffer.Length);

                                result = rsaProvider.VerifyData(verifyBuffer, sha1, header.Signature);
                                break;

                            default:
                                Log.Instance.DoLog("You are using an older version of the addon, support for older addons will be removed soon.");
                                result = rsaProvider.VerifyData(assemblyBuffer, sha1, header.Signature);
                                break;
                            }

                            if (result)
                            {
                                var key = CustomRsa.DecodeBlock(header.CryptoData.Key, new BigInteger(Exponent), new BigInteger(Modulus));
                                assembly = RijndaelHelper.Decrypt(assemblyBuffer, key, header.CryptoData.Salt, header.CryptoData.Iterations);

                                return(true);
                            }
                        }
                    }
                }
            }

            assembly = null;
            return(false);
        }
Esempio n. 17
0
        public static string CreateToken(int id, string name, IdentityType identityType)
        {
            //生成一个60分钟内有效的令牌
            var info = new TokenInfo
            {
                IdentityId     = id,
                IdentityName   = name,
                ExpirationTime = DateTime.Now.AddMinutes(60),
                IdentityType   = identityType
            };

            //将令牌序列化成字符串并加密
            return(RijndaelHelper.Encrypt(JsonConvert.SerializeObject(info)));
        }
        public ActionResult PaymentConfirmationSuccess(string token)
        {
            try
            {
                string decryptedOrderNo = RijndaelHelper.Decrypt(token, CryptographyKey);
                ViewBag.OrderNo = decryptedOrderNo;
                ModelState.Clear();
            }
            catch (Exception ex)
            {
                return(RedirectToAction("PaymentConfirmation"));
            }

            return(View());
        }
Esempio n. 19
0
        public void AddOrUpdateEmployee(int id,
                                        string userName,
                                        string name,
                                        string initial,
                                        string gender,
                                        string email,
                                        int roleID,
                                        bool isAllowLogin,
                                        bool isActive,
                                        bool isAllowBackdate,
                                        IDictionary <int, string> cellPhones,
                                        int backColor)
        {
            var employee = id == 0 ? new Employee() : repository.Single <Employee>(emp => emp.ID == id);

            employee.UserName        = userName;
            employee.RoleID          = roleID;
            employee.Name            = name;
            employee.Initial         = initial;
            employee.Gender          = gender;
            employee.Email           = email;
            employee.IsAllowLogin    = isAllowLogin;
            employee.IsActive        = isActive;
            employee.IsAllowBackdate = isAllowBackdate;
            employee.CellPhone1      = cellPhones[1];
            employee.CellPhone2      = cellPhones[2];
            employee.BackColor       = backColor;
            if (id == 0)
            {
                repository.Add(employee);
            }
            else
            {
                repository.Update(employee);
            }
            repository.SetAuditFields(id, employee, principal.Identity.Name);

            if (String.IsNullOrEmpty(employee.Password))
            {
                employee.Password = isAllowLogin
                    ? RijndaelHelper.Encrypt(ConfigurationManager.AppSettings[ApplicationSettingKeys.DefaultPassword],
                                             cryptographyKey)
                    : String.Empty;
            }

            repository.UnitOfWork.SaveChanges();
        }
        internal static byte[] VerifyAndDecrypt(byte[] signedaddon)
        {
            SignedAddonHeader header;

            byte[] encryptedAssembly = null;

            using (var stream = new MemoryStream(signedaddon))
            {
                using (var reader = new BinaryReader(stream))
                {
                    var headerBuffer   = reader.ReadBytes(Marshal.SizeOf(typeof(SignedAddonHeader)));
                    var assemblyBuffer = reader.ReadBytes(signedaddon.Length - headerBuffer.Length);

                    var gcHandle = GCHandle.Alloc(headerBuffer, GCHandleType.Pinned);
                    header = (SignedAddonHeader)Marshal.PtrToStructure(gcHandle.AddrOfPinnedObject(), typeof(SignedAddonHeader));
                    gcHandle.Free();

                    var cspParams = new CspParameters {
                        ProviderType = 1
                    };

                    using (var rsaProvider = new RSACryptoServiceProvider(cspParams))
                    {
                        rsaProvider.ImportCspBlob(Convert.FromBase64String(PublicKey));

                        using (var sha1 = new SHA1CryptoServiceProvider())
                        {
                            if (rsaProvider.VerifyData(assemblyBuffer, sha1, header.Signature))
                            {
                                encryptedAssembly = assemblyBuffer;
                            }
                        }
                    }
                }
            }

            if (encryptedAssembly != null)
            {
                var key = CustomRsa.DecodeBlock(header.CryptoData.Key, new BigInteger(Exponent), new BigInteger(Modulus));
                return(RijndaelHelper.Decrypt(encryptedAssembly, key, header.CryptoData.Salt, header.CryptoData.Iterations));
            }

            return(null);
        }
        public ActionResult CheckOutSuccess(string o)
        {
            cartManager.EmptyCart();

            var model = new CheckOutSuccessViewModel();

            try
            {
                string orderNo = RijndaelHelper.Decrypt(o, ConfigurationInstance[ConfigurationKeys.CryptographyKey]);
                var    order   = orderProvider.GetOrder(orderNo);
                model.SubmittedOrder = order;
            }
            catch (CryptographicException ex)
            {
                Logger.FatalException(ex.Message, ex);
                return(RedirectToAction("InvalidCheckOutProcess"));
            }
            return(View(model));
        }
Esempio n. 22
0
        /// <summary>
        /// 认证。
        /// </summary>
        /// <param name="filterContext">认证上下文实体对象。</param>
        public void OnAuthentication(AuthenticationContext filterContext)
        {
            try
            {
                var cipherText = TokenHelper.GetToken(filterContext.HttpContext.Request);
                if (string.IsNullOrWhiteSpace(cipherText))
                {
                    throw new Exception("令牌信息为空");
                }

                //验证令牌
                var decrypt = RijndaelHelper.Decrypt(cipherText);
                if (string.IsNullOrWhiteSpace(decrypt))
                {
                    throw new Exception("解密后的令牌为空");
                }

                var tokenInfo = JsonConvert.DeserializeObject <TokenInfo>(decrypt);
                if (tokenInfo.ExpirationTime < DateTime.Now)
                {
                    throw new Exception("令牌已经过期");
                }

                if (this.identityType != IdentityType.All && tokenInfo.IdentityType != this.identityType)
                {
                    throw new Exception("令牌身份类型不正确");
                }

                //当前请求上下文生命周期内注入会员信息
                Locator.Get <IPrincipal>().TokenInfo = tokenInfo;

                //每过10分钟重新颁发新的令牌
                if ((tokenInfo.ExpirationTime - DateTime.Now).Minutes < 10)
                {
                    TokenHelper.SetToken(tokenInfo.IdentityId, tokenInfo.IdentityName, tokenInfo.IdentityType,
                                         filterContext.HttpContext.Response);
                }
            }
            catch (Exception ex)
            {
                filterContext.Result = new JsonResult(new ResponseMessage(ResponseCode.Unauthorized, ex.Message));
            }
        }
Esempio n. 23
0
        public ActionResult Login([FromBody] LoginViewModel model)
        {
            var user = _userProvider.ValidateLogin(model);

            if (user == null)
            {
                return(BadRequest(new { IsSuccess = false, Data = "", BearerToken = "", message = "Username or password is incorrect" }));
            }


            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim("CurrentUserID", user.Id.ToString()),
                    new Claim("CurrentBusinessGrupID", user.CurrentBusinessGroupId.ToString()),
                    new Claim("CurrentEmail", user.Email.ToString()),
                    new Claim("LoginName", model.LoginName),
                    new Claim("Password", RijndaelHelper.Encrypt(model.Password, "IGLO2015"))
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token       = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);

            //var menuMapper = _mapper.Map<Database.Context.Models.Menu>(menu);
            var returnLogin = _mapper.Map <User>(user);

            // return basic user info (without password) and token to store client side
            return(Ok(new
            {
                IsSuccess = true,
                Data = returnLogin,
                BearerToken = tokenString,
                message = "Login Success"
            }));
        }
Esempio n. 24
0
        public static ProtocolObject DeserializeObject(string encryptJson)
        {
            int    index = encryptJson.IndexOf(":") + 3;
            string json  = encryptJson.Substring(index);

            //json = System.Web.HttpUtility.UrlDecode(json);
            try
            {
                json = RijndaelHelper.Decrypt(json);
            }
            catch {
                if (json[json.Length - 1] == '/')
                {
                    json = json.Substring(0, json.Length - 1);
                }
                json = RijndaelHelper.Decrypt(json);
            }
            logger.Info(json);
            JObject jso = JsonConvert.DeserializeObject(json) as JObject;

            return(ProtocolObjectConvertor.ConvertTo(jso));
        }
Esempio n. 25
0
        public ActionResult Create(CreateEditViewModel model)
        {
            var  jsonViewModel = new AjaxViewModel();
            bool IsValidEmail;

            try
            {
                var addr = new System.Net.Mail.MailAddress(model.Email);
                model.Email  = addr.ToString();
                IsValidEmail = true;
            }
            catch
            {
                IsValidEmail = false;
            }

            var Password = model.Password;
            int Number   = 0;
            int Text     = 0;

            for (int i = 0; i < Password.Length; i++)
            {
                int    value;
                string Character = Password.Substring(i, 1);
                if (int.TryParse(Character, out value))
                {
                    Number++;
                }
                else
                {
                    Text++;
                }
            }

            if (Password.Length < 8 || Number < 2 || !IsValidEmail || Text == 0)
            {
                if (!IsValidEmail)
                {
                    jsonViewModel.SetValues(false, null, String.Format("Email is invalid"));
                }
                else
                {
                    jsonViewModel.SetValues(false, null, String.Format("Password must be at least 8 characters with minimun 2 number"));
                }
            }
            else
            {
                try
                {
                    model.Password   = RijndaelHelper.Encrypt(model.Password, "IGLO2015");
                    model.LoginName  = model.UserName;
                    model.EmployeeID = EncryptionHelper.DecryptUrlParam(model.EmployeeID);
                    string json      = JsonConvert.SerializeObject(model);
                    var    checkCode = Utilities.RestAPIHelper <string>
                                       .Submit(json, Method.POST, url + "/UserValidateCombination");

                    if (!Convert.ToBoolean(checkCode))
                    {
                        var endpoint = url + Route.Add;
                        var content  = Utilities.RestAPIHelper <CreateEditViewModel>
                                       .Submit(json, Method.POST, endpoint);

                        jsonViewModel.SetValues(true, null, "Saved");
                    }
                    else
                    {
                        jsonViewModel.SetValues(false, null, String.Format("User has been added"));
                    }
                }
                catch (Exception ex)
                {
                    jsonViewModel.SetValues(false, null, String.Format("Failed\\nMessage: {0}", ex.GetBaseException().Message));
                }
            }


            return(Json(jsonViewModel));
        }
 public RijndaelKeyVectorProvider(string passphrase, int keySize)
     : base(RijndaelHelper.CreateKeyVector(passphrase, keySize))
 {
 }
Esempio n. 27
0
 protected override void DoSetUp()
 {
     helper = new RijndaelHelper(RijndaelHelper.GenerateNewKey());
 }