Exemplo n.º 1
0
 public static void GetPasswordHash(string password, out byte[] passwordSalt, out byte[] passwordHash)
 {
     using (var hmac = new System.Security.Cryptography.HMACSHA512())
     {
         passwordSalt = hmac.Key;
         passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
     }
 }
        internal static string Hash(string value, string key)
        {
            if (String.IsNullOrWhiteSpace(value)) throw new ArgumentNullException("value");
            if (String.IsNullOrWhiteSpace(key)) throw new ArgumentNullException("key");

            var valueBytes = System.Text.Encoding.UTF8.GetBytes(key);
            var keyBytes = System.Text.Encoding.UTF8.GetBytes(key);
            
            var alg = new System.Security.Cryptography.HMACSHA512(keyBytes);
            var hash = alg.ComputeHash(valueBytes);
            
            var result = Crypto.BinaryToHex(hash);
            return result;
        }
        public override void AuthenticatePostRequest(HttpWebRequest request, string messageBody)
        {
            doAuthentication(request);
            #if TEMP_FIX
            // _dch temp fix for temp keys not being able to POST content
            Nonce nonce = _nonceClient.GetNonce("PsaonlV2MnSheEd4QXub");

            var key = System.Text.Encoding.UTF8.GetBytes("E0sNkz0TbcmlNXSrXknLPi0Npn0fuVMGOguUTjfx");
            var messageBytes = System.Text.Encoding.UTF8.GetBytes(nonce.NonceValue);
            var hmacsha512 = new System.Security.Cryptography.HMACSHA512(key);
            var signedValue = hmacsha512.ComputeHash(messageBytes);

            this.WriteAuthenticationHeader(request, nonce.POSTAuthenticationHeaderValue("PsaonlV2MnSheEd4QXub", Convert.ToBase64String(signedValue)));
            #endif
        }
Exemplo n.º 4
0
        private bool VerifyPasswordHash(string password, byte[] passwordHash, byte[] passwordSalt)
        {
            using (var hmac = new System.Security.Cryptography.HMACSHA512(passwordSalt))
            {
                var computeHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));

                for (int i = 0; i < computeHash.Length; i++)
                {
                    if (computeHash[i] != passwordHash[i])
                    {
                        return(false);
                    }
                }
            }
            return(true);
        }
Exemplo n.º 5
0
        private string CalculateHmac(string signature)
        {
            string encodedKey = Configuration.AuthenticationKey;

            while (encodedKey.Length % 4 != 0)
            {
                encodedKey += "=";
            }
            byte[] keyBytes = System.Convert.FromBase64String(encodedKey);
            using (var hmac = new System.Security.Cryptography.HMACSHA512(keyBytes))
            {
                byte[] signatureBytes = System.Text.Encoding.UTF8.GetBytes(signature);
                byte[] hashBytes      = hmac.ComputeHash(signatureBytes);
                return(System.Convert.ToBase64String(hashBytes));
            }
        }
Exemplo n.º 6
0
        // private helper methods
        private static void CreatePasswordHash(string password, out byte[] passwordHash, out byte[] passwordSalt)
        {
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }
            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentException("Value cannot be empty or whitespace only string.", "password");
            }

            using (var hmac = new System.Security.Cryptography.HMACSHA512()) {
                passwordSalt = hmac.Key;
                passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
            }
        }
Exemplo n.º 7
0
 // la clé de cryptage est passée pour contrôler
 private bool VerifyPasswordHash(string password, byte[] passwordHash, byte[] passwordSalt)
 {
     using (var hmac = new System.Security.Cryptography.HMACSHA512(passwordSalt)){
         //transorme chq caractère de password en crypté
         var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
         for (int i = 0; i < computedHash.Length; i++)
         {
             //comparer chq caractère du tableau de byte
             if (computedHash[i] != passwordHash[i])
             {
                 return(false);
             }
         }
         return(true);
     }
 }
Exemplo n.º 8
0
        private bool passwordChecks(User user, string password)
        {
            using (var hmac = new System.Security.Cryptography.HMACSHA512(user.PasswordSalt))
            {
                var calcPassword = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
                for (int i = 0; i < calcPassword.Length; i++)
                {
                    if (calcPassword[i] != user.PasswordHash[i])
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
Exemplo n.º 9
0
        private bool VerificarPassword(string password, byte[] passwordHash, byte[] passwordSalt)
        {
            using (var hmac = new System.Security.Cryptography.HMACSHA512(passwordSalt)){
                var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(password)); //gera o hash usando o key armazenado

                //Verificação do array do hash
                for (int i = 0; i < hash.Length; i++)
                {
                    if (hash[i] != passwordHash[i])
                    {
                        return(false);
                    }
                }
            }
            return(true);
        }
Exemplo n.º 10
0
        public static bool VerifyPasswordHash(string password, byte[] passwordHash, byte[] passwordSalt) //kullanıcının verdiği şifrenin hashının bizim hash ile eşleşip eşleşmediğini ontrol ettiğimiz yer
        {
            using (var hmac = new System.Security.Cryptography.HMACSHA512(passwordSalt))
            {
                var computedHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(password));
                for (int i = 0; i < computedHash.Length; i++)
                {
                    if (computedHash[i] != passwordHash[i])
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
Exemplo n.º 11
0
        private bool VarifyHashPassword(string password, byte[] userPasswordHash, byte[] userPasswordKey)
        {
            using (var hashMap = new System.Security.Cryptography.HMACSHA512(userPasswordKey))
            {
                var computedPasswordHash = hashMap.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));

                for (int i = 0; i < computedPasswordHash.Length; i++)
                {
                    if (userPasswordHash[i] != computedPasswordHash[i])
                    {
                        return(false);
                    }
                }
            }
            return(true);
        }
Exemplo n.º 12
0
        private bool VerifyPasswordHash(string password, SaltyHash saltyHash)
        {
            using (var hmac = new System.Security.Cryptography.HMACSHA512(saltyHash.salt))
            {
                var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));

                for (var x = 0; x < saltyHash.hash.Length; x++)
                {
                    if (computedHash[x] != saltyHash.hash[x])
                    {
                        return(false);
                    }
                }
            }
            return(true);
        }
Exemplo n.º 13
0
        public bool IsPassword(string password, byte[] passwordHash, byte[] passwordSalt)
        {
            using (var hashedPasswordFromDb = new System.Security.Cryptography.HMACSHA512(passwordSalt))
            {
                var enteredPasswordHash = hashedPasswordFromDb.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));

                for (int i = 0; i < enteredPasswordHash.Length; i++)
                {
                    if (passwordHash[i] != enteredPasswordHash[i])
                    {
                        return(false);
                    }
                }
            }
            return(true);
        }
Exemplo n.º 14
0
 //sonrada sisteme girmek isteyen kişinin verdiği password'un ,
 //bizim veritabanındaki passwordHash ile ilgli passwordSalt'a göre eşleşip eşleşmediğini verdiğmiz metot:
 public static bool VerifyPasswordHash
     (string password, byte[] passwordHash, byte[] passwordSalt) // pass işini doğrula
 {
     using (var hmac = new System.Security.Cryptography.HMACSHA512(passwordSalt))
     {
         var computedHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(password)); //oluşan array byte array dir. //hesaplanan hash salt kullanarak yapılıyor.
         for (int i = 0; i < computedHash.Length; i++)                          // iki arrayin değerleri aynı mı, hesaplanan hash in tüm değerlerini tek tek dolaş
         {
             if (computedHash[i] != passwordHash[i])                            //ikisi karşılaştırılıyor
             {
                 return(false);                                                 //eşleşmezse
             }
         }
         return(true); //eşleşirse
     }
 }
Exemplo n.º 15
0
        public static bool VerifyPasswordHash(string sifre, byte[] sifrele, byte[] sifrecoz)
        {
            using (var hmac = new System.Security.Cryptography.HMACSHA512(sifrecoz))
            {
                var computedHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(sifre));
                for (int i = 0; i < computedHash.Length; i++)
                {
                    if (computedHash[i] != sifrele[i])
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
Exemplo n.º 16
0
 private bool VerifyPasswordHash(string password, byte[] passwordHash, byte[] passwordSalt)
 {
     using (var hmac = new System.Security.Cryptography.HMACSHA512(passwordSalt)){
         //aqui arriba se le pone la key del passwordsalt y con esa key se generara un passwordhash aqui abajo
         //se tendra que comparar el passwordhash de aqui abajo con el que esta guardado con el usuario para saber si es la contraseña correcta
         var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
         for (int i = 0; i < computedHash.Length; i++)
         {
             if (computedHash[i] != passwordHash[i])
             {
                 return(false);
             }
         }
     }
     return(true);
 }
Exemplo n.º 17
0
        internal bool VerifyPasswordHash(string strPassword, byte[] passwordHash, byte[] passwordSalt)
        {
            using (var hmac = new System.Security.Cryptography.HMACSHA512(passwordSalt))
            {
                var strComputedPassword = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(strPassword));

                for (int i = 0; i < strComputedPassword.Length; i++)
                {
                    if (passwordHash[i] != strComputedPassword[i])
                    {
                        return(false);
                    }
                }
            }
            return(true);
        }
Exemplo n.º 18
0
 public static bool VerifyPasswordHash(string password, byte[] passwordHash, byte[] passwordSalt) //şifre esleşirse true eslesmezse flase
 {
     using (var hmac = new System.Security.Cryptography.HMACSHA512(passwordSalt))                 //bunları ezberlemene gerek yok
                                                                                                  //burada sana kullandıgın key anahtarını soruyor
     {
         var computedHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(password));                   //burada hesaplanan hash bu salt hesaplanarak yapılıyor
         for (int i = 0; i < computedHash.Length; i++)
         {
             if (computedHash[i] != passwordHash[i])
             {
                 return(false);    //eşleşmezse false
             }
         }
     }
     return(true);   //eşleşirse true
 }
Exemplo n.º 19
0
 private bool VerifyPasswordHash(string password, byte[] passwordHash, byte[] passwordSalt)
 {
     using (var hmac = new System.Security.Cryptography.HMACSHA512(passwordSalt))
     {
         //Anything in here will be disposed of once we're done using it
         var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
         for (int i = 0; i > computedHash.Length; i++)
         {
             if (computedHash[i] != passwordHash[1])
             {
                 return(false);
             }
         }
     }
     return(true);
 }
        private static void CreatePasswordHash(string wachtwoord, out byte[] wachtwoordHash, out byte[] wachtwoordSalt)
        {
            if (wachtwoord == null)
            {
                throw new ArgumentNullException("wachtwoord");
            }
            if (string.IsNullOrWhiteSpace(wachtwoord))
            {
                throw new ArgumentException("Value mag niet leeg zijn", "wachtwoord");
            }

            using (var hmac = new System.Security.Cryptography.HMACSHA512())
            {
                wachtwoordSalt = hmac.Key;
                wachtwoordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(wachtwoord));
            }
        }
Exemplo n.º 21
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, DataContext dataContext)
        {
            dataContext.Database.Migrate();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseCors(x => x
                        .AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader());

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            bool defaultUserExists = dataContext.Users.Any(e => e.Username.Equals("PotatoDotJar"));

            if (!defaultUserExists)
            {
                Debug.WriteLine("Creating new default user.");
                using (var hmac = new System.Security.Cryptography.HMACSHA512())
                {
                    byte[] passwordSalt = hmac.Key;
                    byte[] passwordHash = hmac.ComputeHash(Encoding.UTF8.GetBytes("Abcd1234"));

                    dataContext.Users.Add(new User()
                    {
                        FirstName    = "John",
                        LastName     = "Doe",
                        Username     = "******",
                        PasswordHash = passwordHash,
                        PasswordSalt = passwordSalt
                    });
                    dataContext.SaveChanges();
                }
            }
        }
Exemplo n.º 22
0
        private bool VerifyHashPassword(string password, User user)
        {
            using (var hmac = new System.Security.Cryptography.HMACSHA512(user.PasswordSalt))
            {
                var inputPasswordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));

                for (int i = 0; i < user.PasswordHash.Length; i++)
                {
                    if (inputPasswordHash[i] != user.PasswordHash[i])
                    {
                        bool blnresult = false;
                        return(blnresult);
                    }
                }
                return(true);
            }
        }
Exemplo n.º 23
0
        /// <summary>
        /// Băm password
        /// </summary>
        /// <param name="password">password dạng string</param>
        /// <param name="passwordHash">password được băm</param>
        /// <param name="passwordSalt">key để giải mã</param>
        private void CreatePasswordHash(string password, out byte[] passwordHash, out byte[] passwordSalt)
        {
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }
            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentException("Password không thể trống hoặc chỉ chứa khoảng trắng.", "password");
            }

            // băm sử dụng thuật toán PBKDF2
            // thêm một chuỗi byte ngẫu nhiên vào mật khẩu của người dùng tránh trường hợp trùng email password
            using var hmac = new System.Security.Cryptography.HMACSHA512();
            passwordSalt   = hmac.Key;
            passwordHash   = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
        }
Exemplo n.º 24
0
        private bool VerifyPasswordHash(string password, byte[] passwordHash, byte[] passwordSalt)
        {
            using (var hmac = new System.Security.Cryptography.HMACSHA512(passwordSalt))
            {
                var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password)); // password user dijadikan hash

                for (int i = 0; i < computedHash.Length; i++)                                      // cek setiap karakter password hash
                {
                    if (computedHash[i] != passwordHash[i])                                        // jika computed hash tidak cocok dengan passwordHast(yang ada di database)
                    {
                        return(false);                                                             // jika tidak cocok return false
                    }
                }

                return(true);
            }
        }
Exemplo n.º 25
0
        private void CreatePasswordHash(string password, out byte[] passwordHash, out byte[] passwordSalt)
        {
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }
            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentException("Se debe proporcionar un valor.", "password");
            }

            using (var hmac = new System.Security.Cryptography.HMACSHA512())
            {
                passwordSalt = hmac.Key;
                passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
            }
        }
Exemplo n.º 26
0
 public bool AdminLogin2(AdminDto admindto)
 {
     using (var crypto = new System.Security.Cryptography.HMACSHA512())
     {
         byte[] username = crypto.ComputeHash(Encoding.UTF8.GetBytes(admindto.UserName));
         var    admin    = _adminService2.GetList();
         foreach (var item in admin)
         {
             if (HashingHelper.VerifyPasswordHash(admindto.Password, admindto.UserName,
                                                  item.AdminPasswordHash, item.AdminUserName, item.AdminPasswordSalt))
             {
                 return(true);
             }
         }
         return(false);
     }
 }
Exemplo n.º 27
0
        private bool verifyPassword(string password, byte [] PasswordHash, byte [] PasswordSalt)
        {
            using (var hash = new System.Security.Cryptography.HMACSHA512(PasswordSalt))
            {
                var Generate_password = hash.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));

                for (int i = 0; i < Generate_password.Length; i++)
                {
                    if (PasswordHash[i] != Generate_password[i])
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
Exemplo n.º 28
0
        private bool VerifyPasswordHash(string password, byte[] passwordHash, byte[] passwordSalt)
        {
            using (var hmac = new System.Security.Cryptography.HMACSHA512(passwordSalt)) // convert passwordSalt back to hmac which is then used to generated computedHash
            {
                var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));

                for (int i = 0; i < computedHash.Length; i++)
                {
                    if (computedHash[i] != passwordHash[i])
                    {
                        return(false);
                    }
                }
            }

            return(true);    // passwords match
        }
Exemplo n.º 29
0
        private PasswordModel CreatePasswordHash(string password)
        {
            using (var hmac = new System.Security.Cryptography.HMACSHA512())
            {
                var result = new PasswordModel();

                // random key generated from hmac hash algo
                result.PasswordSalt = Convert.ToBase64String(hmac.Key);

                // Hash bytes of password
                // (Computes / hashes password with key generated on HMACSHA512 construction)
                var hashBytes = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
                result.PasswordHash = Convert.ToBase64String((hashBytes));

                return(result);
            }
        }
Exemplo n.º 30
0
        // private helper methods

        private static void CreatePasswordHash(string password, out byte[] passwordHash, out byte[] passwordSalt)
        {
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }
            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentException("El campo no puede estar vacio o contener espacios.", "password");
            }

            using (var hmac = new System.Security.Cryptography.HMACSHA512())
            {
                passwordSalt = hmac.Key;
                passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
            }
        }
Exemplo n.º 31
0
 private bool VerifyPasswordHash(string password, byte[] passwordHash, byte[] passwordSalt)
 {
     //passwordSalt is the key we are passing
     //we'll compare the two hashes, if the hashes match --> password is correct
     using (var hmac = new System.Security.Cryptography.HMACSHA512(passwordSalt))
     {
         var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
         for (int i = 0; i < computedHash.Length; i++)
         {
             if (computedHash[i] != passwordHash[i])
             {
                 return(false);
             }
         }
     }
     return(true);
 }
Exemplo n.º 32
0
        public static bool VerifyHashedPasswordByCSHA512(string password, byte[] hashedPassword, byte[] passwordSalt)
        {
            using (var hmac = new System.Security.Cryptography.HMACSHA512(passwordSalt))
            {
                byte[] computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));

                for (int i = 0; i < hashedPassword.Length; i++)
                {
                    if (hashedPassword[i] != computedHash[i])
                    {
                        return(false);
                    }
                }

                return(true);
            }
        }
Exemplo n.º 33
0
        public virtual bool Verify(string password, string storedPassword)
        {
            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentNullException(nameof(password));
            }

            using (var hmac = new System.Security.Cryptography.HMACSHA512(ApplicationSettings.Salt))
            {
                var hashedPassword = hmac
                                     .ComputeHash(Encoding.UTF8.GetBytes(password));

                return(storedPassword.Equals(
                           Convert.ToBase64String(hashedPassword),
                           StringComparison.InvariantCultureIgnoreCase));
            }
        }
Exemplo n.º 34
0
        private void CompareBlocks(HmacAlg Algorithm)
        {
            if (Algorithm == HmacAlg.Sha256Hmac)
            {
                byte[] hashKey = new byte[32];
                byte[] buffer = new byte[640];
                byte[] hash1 = new byte[32];
                byte[] hash2 = new byte[32];

                using (System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider())
                {
                    rng.GetBytes(hashKey);
                    rng.GetBytes(buffer);
                }

                using (System.Security.Cryptography.HMACSHA256 hmac = new System.Security.Cryptography.HMACSHA256(hashKey))
                    hash1 = hmac.ComputeHash(buffer);

                // test 1: HMAC interface
                HMAC hmac1 = new HMAC(new SHA256Digest());
                hmac1.Init(hashKey);
                hmac1.BlockUpdate(buffer, 0, buffer.Length);
                hmac1.DoFinal(hash2, 0);

                if (!Compare.AreEqual(hash2, hash1))
                    throw new Exception("hmac is not equal!");

                // test 2: class with dofinal
                using (SHA256HMAC hmac = new SHA256HMAC())
                {
                    hmac.Init(hashKey);
                    hmac.BlockUpdate(buffer, 0, buffer.Length);
                    hmac.DoFinal(hash2, 0);
                }

                if (!Compare.AreEqual(hash2, hash1))
                    throw new Exception("hmac1 is not equal!");

                // test 3: class with computemac
                using (SHA256HMAC hmac = new SHA256HMAC(hashKey))
                    hash2 = hmac.ComputeMac(buffer);

                if (!Compare.AreEqual(hash2, hash1))
                    throw new Exception("hmac2 is not equal!");
            }
            else
            {
                // SHA512 //
                byte[] hash1 = new byte[64];
                byte[] hash2 = new byte[64];
                byte[] hashKey = new byte[64];
                byte[] buffer = new byte[128];

                using (System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider())
                {
                    rng.GetBytes(hashKey);
                    rng.GetBytes(buffer);
                }

                using (System.Security.Cryptography.HMACSHA512 hmac = new System.Security.Cryptography.HMACSHA512(hashKey))
                    hash1 = hmac.ComputeHash(buffer);

                // test 1: HMAC interface
                HMAC hmac1 = new HMAC(new SHA512Digest());
                hmac1.Init(hashKey);
                hmac1.BlockUpdate(buffer, 0, buffer.Length);
                hmac1.DoFinal(hash2, 0);

                if (!Compare.AreEqual(hash2, hash1))
                    throw new Exception("hmac1 is not equal!");

                // test 2: class with dofinal
                using (SHA512HMAC hmac = new SHA512HMAC())
                {
                    hmac.Init(hashKey);
                    hmac.BlockUpdate(buffer, 0, buffer.Length);
                    hmac.DoFinal(hash2, 0);
                }

                if (!Compare.AreEqual(hash2, hash1))
                    throw new Exception("hmac1 is not equal!");

                // test 3: class with computemac
                using (SHA512HMAC hmac = new SHA512HMAC(hashKey))
                    hash2 = hmac.ComputeMac(buffer);

                if (!Compare.AreEqual(hash2, hash1))
                    throw new Exception("hmac2 is not equal!");
            }
        }
Exemplo n.º 35
0
        protected static string GetBase64HMAC(byte[] key, System.IO.MemoryStream stream)
        {
            System.Security.Cryptography.HMACSHA512 hmac = new System.Security.Cryptography.HMACSHA512(key);
            string ret = Convert.ToBase64String(hmac.ComputeHash(stream.ToArray()));

            stream.Seek(0, System.IO.SeekOrigin.Begin);

            return ret;
        }
Exemplo n.º 36
0
        public static HttpWebRequest SignRequest(this HttpWebRequest req, string pData, string singingKey)
        {
            string nonce = new Random().Next(Int16.MaxValue, Int32.MaxValue).ToString("X", System.Globalization.CultureInfo.InvariantCulture);
            string timeStamp = DateTime.UtcNow.ToUnixTimeStamp().ToString();

            // Create the base string. This is the string that will be hashed for the signature.
            Dictionary<string, string> param = new Dictionary<string, string>();
            param.Add("oauth_nonce", nonce);
            param.Add("oauth_signature_method", "HMAC-SHA512");
            param.Add("oauth_timestamp", timeStamp);

            pData += req.RequestUri.Query;

            foreach (string kv in pData.Replace("?", "&").Split('&'))
            {
                string[] akv = kv.Split('=');
                if (akv.Length == 2)
                {
                    param.Add(akv[0], akv[1].PercentDecode());
                }
            }

            StringBuilder sParam = new StringBuilder(); ;
            foreach (KeyValuePair<string, string> p in param.OrderBy(k => k.Key))
            {
                if (sParam.Length > 0)
                    sParam.Append("&");

                sParam.AppendFormat("{0}={1}", p.Key.PercentEncode(), p.Value.PercentEncode());
            }

            string url = req.RequestUri.AbsoluteUri;
            if (!string.IsNullOrEmpty(req.RequestUri.Query))
            {
                url = url.Replace(req.RequestUri.Query, "");
            }

            string signatureBaseString
                = string.Format("{0}&{1}&{2}",
                req.Method.ToUpper(),
                url.PercentEncode(),
                sParam.ToString().PercentEncode()
            );

            // Generate the hash
            System.Security.Cryptography.HMACSHA512 hmacsha512 = new System.Security.Cryptography.HMACSHA512(Encoding.UTF8.GetBytes(singingKey));
            byte[] signatureBytes = hmacsha512.ComputeHash(Encoding.UTF8.GetBytes(signatureBaseString));

            string signature = Convert.ToBase64String(signatureBytes).PercentEncode();

            req.Headers.Add("oauth_nonce", nonce);
            req.Headers.Add("oauth_signature_method", "HMAC-SHA512");
            req.Headers.Add("oauth_timestamp", timeStamp);
            req.Headers.Add("oauth_signature", signature);
            req.ContentType = "application/x-www-form-urlencoded";

            return req;
        }
 static byte[] Sign(byte[] signingKey, byte[] message)
 {
     var hmac = new System.Security.Cryptography.HMACSHA512(signingKey);
     var hash = hmac.ComputeHash(message);
     return hash;
 }
		private void HashPassword(string Password, out byte[] passwordSalt, out byte[] passwordHash)
		{
			if (Password == null) throw new ArgumentNullException("Password");
			if (string.IsNullOrWhiteSpace(Password) || string.IsNullOrEmpty(Password)) throw new ArgumentException("Value cannot be empty or null", "Password");

			using (var hmac = new System.Security.Cryptography.HMACSHA512())
			{
				passwordSalt = hmac.Key;
				passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(Password));
			}
		}
		private bool VerifyPassword(string Password, byte[] storedSalt, byte[] storedHash)
		{
			if (Password == null) throw new ArgumentNullException("Password");
			if (string.IsNullOrWhiteSpace(Password) || string.IsNullOrEmpty(Password)) throw new ArgumentException("Value cannot be empty or null", "Password");
			if (storedSalt.Length != 128) throw new ArgumentException("Invalid salt size (64 bytes expected)", "passwordSalt");
			if (storedHash.Length != 64) throw new ArgumentException("Invalid hash size (128 bytes expected)", "passwordHash");

			using (var hmac = new System.Security.Cryptography.HMACSHA512(storedSalt))
			{
				var computed = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(Password));
				return computed.SequenceEqual(storedHash);
			}
		}
Exemplo n.º 40
0
        public void Authenticate(string user, string base64HMAC, byte[] nonce, System.IO.MemoryStream stream)
        {
            using (SC.Utility.Lock l = new SC.Utility.Lock(secLock, SC.Utility.Lock.LockType.ForReading))
            {
                if (!users.ContainsKey(user))
                {
                    Logger.Error("Someone tried to login with username " + user);
                    throw new System.Security.SecurityException("Invalid authentication. Check your username and password.");
                }
                string password = users[user].Password;
                byte[] key = new System.Security.Cryptography.Rfc2898DeriveBytes(password, nonce, 997).GetBytes(64);

                System.Security.Cryptography.HMACSHA512 hmac = new System.Security.Cryptography.HMACSHA512(key);
                string computedBase64HMAC = Convert.ToBase64String(hmac.ComputeHash(stream.ToArray()));

                stream.Seek(0, System.IO.SeekOrigin.Begin);

                if (base64HMAC == computedBase64HMAC)
                {
                    if (users[user].LastConnect < DateTime.Now - new TimeSpan(0, 10, 0))
                        Logger.Info("User " + user + " authenticated.");
                    users[user].SetUserConnected();
                    System.Threading.Thread.CurrentPrincipal = new System.Security.Principal.GenericPrincipal(new System.Security.Principal.GenericIdentity(user), new string[] { USER_ROLE });
                }
                else
                {
                    Logger.Error("User " + user + " failed to authenticate.");
                    throw new System.Security.SecurityException("Invalid authentication. Check your username and password.");
                }
            }
        }