Exemplo n.º 1
0
        public JsonResult SignUpUser(SignUpModel signUpModel)
        {
            int result = 0;

            signUpModel.Password = CryptoServiceProvider.EncMD5(signUpModel.Password);

            //tblUser user = new tblUser
            //{
            //    Email= signUpModel.Email,
            //    FirstName= signUpModel.FirstName,
            //    LastName= signUpModel.LastName,
            //    Password = signUpModel.Password,

            //};

            tblUser user = _mapper.Map <tblUser>(signUpModel);

            result = _userService.Insert(user);

            if (result == 1)
            {
                FormsAuthentication.SetAuthCookie(signUpModel.Email, false);//RememberMe
                // return RedirectToAction("Index", "Home");
            }
            else
            {
                // return RedirectToAction("SignUp", "Account");
            }
            return(Json(result, JsonRequestBehavior.AllowGet));
        }
        public ActionResult Registration(string FirstName, string LastName, DateTime DateOfBirth, string EmailId, string PhoneNumber, string UserAddress, string UserId, string UserPassword, string ConfirmPassword, string Gender)
        {
            bool Validations(Codita modelToValidate)
            {
                if (FirstName != "" && LastName != "" && EmailId != "" && PhoneNumber != "" && UserAddress != "" && UserId != "" && UserPassword != "" && ConfirmPassword != "" && (UserPassword == ConfirmPassword))
                {
                    return(true);
                }
                return(false);
            }

            string             EncryptedUserPassword = CryptoServiceProvider.Encrypt(UserPassword);
            EmployeeDBEntities cs      = new EmployeeDBEntities();
            Codita             coditas = new Codita()
            {
                FirstName    = FirstName,
                LastName     = LastName,
                DateOfBirth  = DateOfBirth,
                EmailId      = EmailId,
                PhoneNumber  = PhoneNumber,
                UserAddress  = UserAddress,
                UserId       = UserId,
                UserPassword = EncryptedUserPassword,
                Gender       = Gender
            };
            var isSuccessful = Validations(coditas);

            if (isSuccessful)
            {
                cs.Coditas.Add(coditas);
                ViewBag.count = cs.SaveChanges();
            }
            return(View());
        }
Exemplo n.º 3
0
 public LoginService(
     BackofficeUserRepository backofficeUserRepository,
     CryptoServiceProvider cryptoServiceProvider,
     TokenHandler tokenHandler)
 {
     this.backofficeUserRepository = backofficeUserRepository;
     this.cryptoServiceProvider    = cryptoServiceProvider;
     this.tokenHandler             = tokenHandler;
 }
Exemplo n.º 4
0
 public string GetXML(bool withPrivateKey)
 {
     //Console.WriteLine("######################");
     //byte[] aar = CryptoServiceProvider.ExportParameters(false).Modulus;
     //for (int i = 0; i < aar.Length; i++)
     //{
     //    Console.Write(aar[i]);
     //}
     //Console.WriteLine();
     //Console.WriteLine("######################");
     return(CryptoServiceProvider.ToXmlString(withPrivateKey));
 }
Exemplo n.º 5
0
        public RngUInt32()
        {
            _chaCha8         = ChaCha.GetChaCha8Factory().Create(new ChaCha.Seed());
            _chaCha12        = ChaCha.GetChaCha12Factory().Create(new ChaCha.Seed());
            _chaCha20        = ChaCha.GetChaCha20Factory().Create(new ChaCha.Seed());
            _pcg32           = Rngs.Pcg32.Create(0, 0);
            _mt1993764       = Rngs.Mt1993764.Create(0);
            _xorShift        = Rngs.XorShift.Create(1, 1, 1, 1);
            _systemCryptoRng = Rngs.SystemCryptoRng.Create();
#pragma warning disable CS0618
            _cryptoServiceProvider = Rngs.CryptoServiceProvider.Create();
#pragma warning restore CS0618
            _random = new Random(42);
        }
        public ActionResult Login(Codita codita, string UserId, string UserPassword)
        {
            EmployeeDBEntities cs = new EmployeeDBEntities();
            string             userPassWordFromDb = (from emp in cs.Coditas where emp.UserId == UserId select emp.UserPassword).FirstOrDefault();
            string             userIdFromDb       = (from emp in cs.Coditas where emp.UserId == UserId select emp.UserId).FirstOrDefault();

            string decryptedUserPassWordFromDb = CryptoServiceProvider.Decrypt(userPassWordFromDb);

            if ((UserPassword).Equals(decryptedUserPassWordFromDb) && (UserId).Equals(userIdFromDb))
            {
                return(View("DashBord"));
            }
            return(View());
        }
Exemplo n.º 7
0
        protected void ReplaceOrEncodePasswords(JObject settings)
        {
            // Iterate through all server credentials in the json and examine the passwords.
            // If it is a GUID we set before, simply replace the original (already encoded)
            // password. If it is an unknown string (meaning a new password), encode it.
            if (settings == null)
            {
                return;
            }

            var servers = settings["Servers"] as JArray;

            if (servers == null)
            {
                return;
            }

            foreach (var server in servers)
            {
                var serverId = server.Value <string>("Id");
                if (string.IsNullOrEmpty(serverId))
                {
                    // this is a new server, it does not have an id yet
                    server["Id"] = serverId = Guid.NewGuid().ToString();
                }

                var credentials = server["LogonCredentials"];
                if (credentials == null)
                {
                    continue;
                }

                var pw = (string)credentials["Password"];
                if (!string.IsNullOrEmpty(pw))
                {
                    // the client provided a password, we have to encrypt it
                    credentials["Password"] = CryptoServiceProvider.Encrypt(pw);
                }
                else
                {
                    // empty password: try to find it in the cache
                    string cachedPassword;
                    if (_cachedPasswords != null && _cachedPasswords.TryGetValue(serverId, out cachedPassword))
                    {
                        // found the original encoded value, we have to inject it before saving the json
                        credentials["Password"] = cachedPassword;
                    }
                }
            }
        }
Exemplo n.º 8
0
        private string ExportPrivateKey()         //TextWriter outputStream)
        {
            StringBuilder pemPrivateKey = new StringBuilder();

            if (CryptoServiceProvider.PublicOnly)
            {
                throw new ArgumentException("CSP does not contain a private key", "csp");
            }
            var parameters = CryptoServiceProvider.ExportParameters(true);

            using (var stream = new MemoryStream()) {
                var writer = new BinaryWriter(stream);
                writer.Write((byte)0x30);                  // SEQUENCE
                using (var innerStream = new MemoryStream()) {
                    var innerWriter = new BinaryWriter(innerStream);
                    EncodeIntegerBigEndian(innerWriter, new byte[] { 0x00 });                   // Version
                    EncodeIntegerBigEndian(innerWriter, parameters.Modulus);
                    EncodeIntegerBigEndian(innerWriter, parameters.Exponent);
                    EncodeIntegerBigEndian(innerWriter, parameters.D);
                    EncodeIntegerBigEndian(innerWriter, parameters.P);
                    EncodeIntegerBigEndian(innerWriter, parameters.Q);
                    EncodeIntegerBigEndian(innerWriter, parameters.DP);
                    EncodeIntegerBigEndian(innerWriter, parameters.DQ);
                    EncodeIntegerBigEndian(innerWriter, parameters.InverseQ);
                    var length = (int)innerStream.Length;
                    EncodeLength(writer, length);
                    writer.Write(innerStream.GetBuffer(), 0, length);
                }

                var base64 = Convert.ToBase64String(stream.GetBuffer(), 0, (int)stream.Length).ToCharArray();
                //            outputStream.WriteLine("-----BEGIN RSA PRIVATE KEY-----");
                pemPrivateKey.AppendLine("-----BEGIN RSA PRIVATE KEY-----");
                // Output as Base64 with lines chopped at 64 characters
                for (var i = 0; i < base64.Length; i += 64)
                {
                    //                  outputStream.WriteLine(base64, i, Math.Min(64, base64.Length - i));
                    pemPrivateKey.AppendLine(new String(base64, i, Math.Min(64, base64.Length - i)));
                }
                //            outputStream.WriteLine("-----END RSA PRIVATE KEY-----");
                pemPrivateKey.AppendLine("-----END RSA PRIVATE KEY-----");
            }
            return(pemPrivateKey.ToString());
        }
Exemplo n.º 9
0
 public Storage ConfirmPassword(string guid, string password)
 {
     try
     {
         using var sql = new SqliteContext();
         var store = sql.Storages.FirstOrDefault(x => x.Guid == guid);
         if (store != null)
         {
             if (CryptoServiceProvider.VerifyHashString(password, store.ProtectedPassword))
             {
                 return(store);
             }
         }
         return(null);
     }
     catch (Exception ex)
     {
         Debug.WriteLine(ex);
         return(null);
     }
 }
Exemplo n.º 10
0
 public Storage Store(Storage store)
 {
     try
     {
         using var sql = new SqliteContext();
         store.Guid    = Guid.NewGuid().ToString();
         if (store.IsPasswordProtected)
         {
             var csp = new CryptoServiceProvider();
             store.ProtectedPassword = csp.CreatePasswordHash(store.ProtectedPassword);
         }
         sql.Storages.Add(store);
         sql.SaveChanges();
         return(store);
     }
     catch (Exception ex)
     {
         Debug.WriteLine(ex);
         return(null);
     }
 }
Exemplo n.º 11
0
            //Devuelve la cadena cifrada.
            public string CryptoDecryptor(string cadenaOriginal, CryptoAction accion)
            {
                //creamos el flujo tomando la memoria como respaldo.
                MemoryStream memStream;

                try
                {
                    //verificamos que la llave y el VI han sido proporcionados.
                    if (_key != null && _IV != null)
                    {
                        //obtenemos el arreglo de bytes correspondiente a la llave
                        //y al vector de inicialización.
                        byte[] key = MakeKeyByteArray();
                        byte[] IV  = MakeIVByteArray();
                        //convertimos el mensaje original en sus correspondiente
                        //arreglo de bytes.
                        byte[] textoplano = (accion == CryptoAction.Encrypt ? Encoding.UTF8.GetBytes(cadenaOriginal) : Convert.FromBase64String(cadenaOriginal));

                        //creamos el flujo
                        memStream = new MemoryStream(cadenaOriginal.Length * (accion == CryptoAction.Encrypt ? 2 : 1));
                        //obtenemos nuestro objeto cifrador, usando la clase
                        //CryptoServiceProvider codificada anteriormente.
                        CryptoServiceProvider cryptoProvider = new CryptoServiceProvider((CryptoServiceProvider.CryptoProvider) this.algorithm, (CryptoServiceProvider.CryptoAction)accion);
                        ICryptoTransform      transform      = cryptoProvider.GetServiceProvider(key, IV);
                        //creamos el flujo de cifrado, usando el objeto cifrador creado y almancenando
                        //el resultado en el flujo MemoryStream.
                        CryptoStream cryptoStream = new CryptoStream(memStream, transform, CryptoStreamMode.Write);
                        //ciframos el mensaje.
                        cryptoStream.Write(textoplano, 0, textoplano.Length);
                        //cerramos el flujo de cifrado.
                        cryptoStream.Close();
                    }
                    else
                    {
                        throw new Exception("Error al inicializar la clave y el vector");
                    }
                }
                catch { throw; }
                return(accion == CryptoAction.Encrypt ? Convert.ToBase64String(memStream.ToArray()) : Encoding.UTF8.GetString(memStream.ToArray()));
            }
Exemplo n.º 12
0
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            try
            {
                var user = _userService.Get(model.UserID);
                if (user == null)
                {
                    ViewBag.Error = "invalidUser";

                    return(View(model));
                }
                else
                {
                    string password = CryptoServiceProvider.EncMD5(model.Password);
                    if (user.Password != password)
                    {
                        ViewBag.Error = "invalidPassword";

                        return(View(model));
                    }
                }

                FormsAuthentication.SetAuthCookie(model.UserID, false);//RememberMe
                if (this.Url.IsLocalUrl(returnUrl))
                {
                    return(Redirect(returnUrl));
                }
                else
                {
                    // return RedirectToAction("Index", "PMS/ProjectMaster");
                    return(RedirectToAction("Index", "Home"));
                }
            }
            catch (Exception ex)
            {
                ViewBag.Error = "error";

                return(View(model));
            }
        }
Exemplo n.º 13
0
        public static Func <RedirectContext, Task> OnRedirectToIdentityProviderEvent(this Func <RedirectContext, Task> redirectContext)
        {
            string codeVerifier = CryptoServiceProvider.Create();

            return(context =>
            {
                if (context.ProtocolMessage.RequestType != OpenIdConnectRequestType.Authentication)
                {
                    return Task.CompletedTask;
                }
                context.Properties.Items.Add("code_verifier", codeVerifier);
                string codeChallenge;
                using (var sha256 = SHA256.Create())
                {
                    var challengeBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(codeVerifier));
                    codeChallenge = CryptoServiceProvider.Encode(challengeBytes);
                }
                context.ProtocolMessage.Parameters.Add("code_challenge", codeChallenge);
                context.ProtocolMessage.Parameters.Add("code_challenge_method", "S256");
                return Task.CompletedTask;
            });
        }
Exemplo n.º 14
0
        public Task <List <User> > GetAllUsers()
        {
            using var sql = new SqliteContext();
            if (!sql.Users.Any())
            {
                CryptoServiceProvider csp   = new CryptoServiceProvider();
                List <User>           users = new List <User>
                {
                    new User {
                        FirstName = "Michael", LastName = "Rinderle", Email = "*****@*****.**", PasswordHash = csp.CreatePasswordHash("Password01")
                    },
                };

                sql.Users.AddRange(users);
                sql.SaveChanges();
                return(Task.FromResult(users));
            }
            else
            {
                return(Task.FromResult(sql.Users.ToList()));
            }
        }
Exemplo n.º 15
0
        private String ExportPublicKeyToPemFormat(TextWriter outputStream)
        {
            var parameters = CryptoServiceProvider.ExportParameters(false);

            using (var stream = new MemoryStream()) {
                var writer = new BinaryWriter(stream);
                writer.Write((byte)0x30);                  // SEQUENCE
                using (var innerStream = new MemoryStream()) {
                    var innerWriter = new BinaryWriter(innerStream);
                    EncodeIntegerBigEndian(innerWriter, new byte[] { 0x00 });                   // Version
                    EncodeIntegerBigEndian(innerWriter, parameters.Modulus);
                    EncodeIntegerBigEndian(innerWriter, parameters.Exponent);

                    //All Parameter Must Have Value so Set Other Parameter Value Whit Invalid Data  (for keeping Key Structure  use "parameters.Exponent" value for invalid data)
                    EncodeIntegerBigEndian(innerWriter, parameters.Exponent);                     // instead of parameters.D
                    EncodeIntegerBigEndian(innerWriter, parameters.Exponent);                     // instead of parameters.P
                    EncodeIntegerBigEndian(innerWriter, parameters.Exponent);                     // instead of parameters.Q
                    EncodeIntegerBigEndian(innerWriter, parameters.Exponent);                     // instead of parameters.DP
                    EncodeIntegerBigEndian(innerWriter, parameters.Exponent);                     // instead of parameters.DQ
                    EncodeIntegerBigEndian(innerWriter, parameters.Exponent);                     // instead of parameters.InverseQ

                    var length = (int)innerStream.Length;
                    EncodeLength(writer, length);
                    writer.Write(innerStream.GetBuffer(), 0, length);
                }

                var base64 = Convert.ToBase64String(stream.GetBuffer(), 0, (int)stream.Length).ToCharArray();
                outputStream.WriteLine("-----BEGIN PUBLIC KEY-----");
                // Output as Base64 with lines chopped at 64 characters
                for (var i = 0; i < base64.Length; i += 64)
                {
                    outputStream.WriteLine(base64, i, Math.Min(64, base64.Length - i));
                }
                outputStream.WriteLine("-----END PUBLIC KEY-----");

                return(outputStream.ToString());
            }
        }