Ejemplo 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
        }
Ejemplo n.º 4
0
        private bool VerifyPasswordHash(string password, byte[] passwordHash, byte[] passwordSalt)
        {
            // Here you do the same but on reverse using the key (passwordSalt) to compute the password
            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 (passwordHash[i] != computedHash[i])
                    {
                        return(false);
                    }
                }
            }
            return(true);
        }
Ejemplo n.º 5
0
 public static bool VerifyPasswordHash
     (string password, byte[] passwordHash, byte[] passwordSalt)
 {
     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);
         //22.33 te kaldım
     }
 }
Ejemplo n.º 6
0
 private bool VerifyPassword(string password, string hexpsw, string hexsalt)
 {
     byte[] passwordHash = Utils.StringToByteArray(hexpsw);
     byte[] passwordSalt = Utils.StringToByteArray(hexsalt);
     using (var hmac = new System.Security.Cryptography.HMACSHA512(passwordSalt))
     {
         var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password)); // Create hash using password salt.
         for (int i = 0; i < computedHash.Length; i++)
         {                                                                                  // Loop through the byte array
             if (computedHash[i] != passwordHash[i])
             {
                 return(false);                                    // if mismatch
             }
         }
     }
     return(true); //if no mismatches.
 }
Ejemplo n.º 7
0
        public static bool IsValidPasswordHash(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));

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

            return(true);
        }
Ejemplo n.º 8
0
        // 私人助手方法
        //创建hash和salt值
        private static void CreatePasswordHash(string password, out byte[] passwordHash, out byte[] passwordSalt)
        {
            if (password == null)
            {
                throw new ArgumentNullException(nameof(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));
            }
        }
 private bool VerifyPassword(string pwd, byte[] hashedPassword, byte[] saltPassword)
 {
     // throw new NotImplementedException();
     using (var hmac = new System.Security.Cryptography.HMACSHA512(saltPassword)){
         var computedHashed = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(pwd));
         //  System.Console.WriteLine("Computed hashed: " + computedHashed + "\nHasedPassword: "******"Computed hashed: " + computedHashed[i] + "\nHasedPassword: " + hashedPassword[i]);
                 return(false);
             }
         }
     }
     return(true);
 }
Ejemplo n.º 10
0
 private bool VerifyPasswordHash(string password, byte[] passwordHash, byte[] passwordSalt)
 {
     using(var hmac = new System.Security.Cryptography.HMACSHA512(passwordSalt))
    {
        
        //converts password to byte array
       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;
 }
Ejemplo n.º 11
0
 private bool VerifyPasswordHash(string password, byte[] passwordHash, byte[] passwordSalt)
 {
     // Reverse of creating password hash to verify a passowrd
     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++)
         {
             // Compares each index of the byte array to see if passwords match
             if (computedHash[i] != passwordHash[i])
             {
                 return(false);
             }
         }
     }
     return(true);
 }
Ejemplo n.º 12
0
        private bool VerifyHashPassword(string password, byte[] hashPassword, byte[] saltPassword)
        {
            using (var hmac = new System.Security.Cryptography.HMACSHA512(saltPassword))
            {
                var computedPassword = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));

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

            return(true);
        }
Ejemplo n.º 13
0
 //29 th caption
 private bool VerifyPasswordHash(string password, byte[] passwordHash, byte[] passwordSalt)
 {
     //same as create password hash pass passwordsalt
     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++)
         {
             //compair both computed and password hashes
             if (computedHash[i] != passwordHash[i])
             {
                 return(false);
             }
         }
     }
     return(true);
 }
Ejemplo n.º 14
0
        /// <summary>
        /// Создание хэша пароля
        /// </summary>
        /// <param name="password"></param>
        /// <param name="passwordHash"></param>
        /// <param name="passwordSalt"></param>
        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("Пароль не может быть пустым или содержать пробелы.", "password");
            }

            using (var hmac = new System.Security.Cryptography.HMACSHA512())
            {
                passwordSalt = hmac.Key;
                passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
            }
        }
Ejemplo n.º 15
0
 private bool VerifyPasswordHash(string password, byte[] passwordHash, byte[] passwordSalt)
 {
     using (var hmac = new System.Security.Cryptography.HMACSHA512(passwordSalt)) {
         // Create the same hash to see if both the password and hash are equal
         var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
         for (int hash_index = 0; hash_index < computedHash.Length; hash_index++)
         {
             // If any character of the hash is different return false
             if (computedHash[hash_index] != passwordHash[hash_index])
             {
                 return(false);
             }
         }
     }
     // If all the characters are equal then return true
     return(true);
 }
Ejemplo n.º 16
0
        private bool VerifyPasswordHash(string password, byte[] passwordHash, byte[] passwordSalt)
        {
            using (System.Security.Cryptography.HMACSHA512 hmac = (System.Security.Cryptography.HMACSHA512)System.Security.Cryptography.HashAlgorithm.Create("HMACSHA512"))
            {
                hmac.Key = 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);
        }
Ejemplo n.º 17
0
 //Function VerifyPasswordHash có ba tham số password, passwordHash, passwordSalt. Trong đó nó sẽ
 private bool VerifyPasswordHash(string password, byte[] passwordHash, byte[] passwordSalt)
 {
     //Khởi tạo hmac là một instance của HMACSHA512 dựa vào key passwordSalt. Là một key bí mật dùng để truy cập đến passwordHash và dựa vào khóa này để mã hóa Password thành PasswordHash
     using (var hmac = new System.Security.Cryptography.HMACSHA512(passwordSalt))
     {
         //computedHash = hmac dùng khóa cùng khóa với passwordSalt để mã hóa password thành passwordHash
         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);
     }
 }
Ejemplo n.º 18
0
        public void CreatePasswordHash(string password, out byte[] passwordHash, out byte[] passwordSalt)
        {
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }
            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentException("A senha não pode ser vazia ou em branco", "password");
            }

            using (var hmac = new System.Security.Cryptography.HMACSHA512())
            {
                passwordSalt = hmac.Key;
                passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
            }
        }
Ejemplo n.º 19
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));

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

            return(true);
        }
Ejemplo n.º 20
0
        private bool VeryPasswordHash(string password, byte[] passwordHash, byte[] passwordSalt)
        {
            // we are using "using" method to call Dispose() method
            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);
        }
Ejemplo n.º 21
0
 public static bool VerifyPasswordHash(string password, byte[] passwordHash, byte[] passwordSalt)
 {
     /* burada hesaplanan hesh salt kullanılarak yapıalcak yani anahtar salt oluyor */
     using (var hmac = new System.Security.Cryptography.HMACSHA512(passwordSalt))
     {
         var computedHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(password));
         /* değerleri aynı mı */
         for (int i = 0; i < computedHash.Length; i++)
         {
             if (computedHash[i] != passwordHash[i])
             {
                 return(false);
             }
         }
     }
     return(true);
 }
Ejemplo n.º 22
0
 private bool VerifyPasswordHash(string password, byte[] passwordHash, byte[] passwordSalt)
 {
     using (var hmac = new System.Security.Cryptography.HMACSHA512(passwordSalt))
     {
         //computedHash will be the same as passwordHash from when the user registered.
         var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
         //looping over each byte in the array to match each element.
         for (int i = 0; i < computedHash.Length; i++)
         {
             if (computedHash[i] != passwordHash[i])
             {
                 return(false);
             }
         }
     }
     return(true);
 }
Ejemplo n.º 23
0
 private bool VerifyPasswordHash(string password, byte[] passwordHash, byte[] passwordSalt)
 {
     using (var hmac = new System.Security.Cryptography.HMACSHA512(passwordSalt))
     {
         // passwordSalt = hmac.Key;
         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);
     // throw new NotImplementedException();
 }
Ejemplo n.º 24
0
        public void Execute()
        {
            ProgressChanged(0, 1);

            System.Security.Cryptography.HMAC hmacAlgorithm;

            switch ((HMACSettings.HashFunction)settings.SelectedHashFunction)
            {
            case HMACSettings.HashFunction.MD5:
                hmacAlgorithm = new System.Security.Cryptography.HMACMD5();
                break;

            case HMACSettings.HashFunction.RIPEMD160:
                hmacAlgorithm = new System.Security.Cryptography.HMACRIPEMD160();
                break;

            case HMACSettings.HashFunction.SHA1:
                hmacAlgorithm = new System.Security.Cryptography.HMACSHA1();
                break;

            case HMACSettings.HashFunction.SHA256:
                hmacAlgorithm = new System.Security.Cryptography.HMACSHA256();
                break;

            case HMACSettings.HashFunction.SHA384:
                hmacAlgorithm = new System.Security.Cryptography.HMACSHA384();
                break;

            case HMACSettings.HashFunction.SHA512:
                hmacAlgorithm = new System.Security.Cryptography.HMACSHA512();
                break;

            default:
                GuiLogMessage("No hash algorithm for HMAC selected, using MD5.", NotificationLevel.Warning);
                hmacAlgorithm = new System.Security.Cryptography.HMACMD5();
                break;
            }

            hmacAlgorithm.Key = key;

            OutputData = (inputData != null) ? hmacAlgorithm.ComputeHash(inputData.CreateReader()) : hmacAlgorithm.ComputeHash(new byte[] {});

            GuiLogMessage(String.Format("HMAC computed. (using hash algorithm {0}: {1})", settings.SelectedHashFunction, hmacAlgorithm.GetType().Name), NotificationLevel.Info);

            ProgressChanged(1, 1);
        }
Ejemplo n.º 25
0
        // private helper methods

        private static void CreatePasswordHash(string password, out byte[] passwordHash, out byte[] passwordSalt)
        {
            if (password == null)
            {
                throw new ArgumentNullException("Hasło nie może być puste");
            }
            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentException("Hasło nie może być puste.");
            }

            using (var hmac = new System.Security.Cryptography.HMACSHA512())
            {
                passwordSalt = hmac.Key;
                passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
            }
        }
Ejemplo n.º 26
0
 private bool VerifyPasswordHash(string password, byte[] passwordHash, byte[] passwordSalt)
 {
     //we pas passwordSalt(as key in method) so i'll identify than the hash and if generated hash matches with password than its true
     using (var hmac = new System.Security.Cryptography.HMACSHA512(passwordSalt))
     {
         //it will compute a hash based on password but itll use the key also
         //computedHash is array so we compare with this bytearr with every element in passwordHashArray
         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); //passwords do not match
             }
         }
     }
     return(true); //paswords match
 }
Ejemplo n.º 27
0
        public static List <byte[]> GenerateHash(string password)
        {
            byte[] passwordSalt, passwordHash;

            // convert password to hash value and generate salt
            using (var hash = new System.Security.Cryptography.HMACSHA512())
            {
                passwordSalt = hash.Key;
                passwordHash = hash.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
            }

            var result = new List <byte[]>();

            result.Add(passwordHash);
            result.Add(passwordSalt);

            return(result);
        }
Ejemplo n.º 28
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));
                // var computedHash = hmac.ComputeHash(Encoding.ASCII.GetBytes(password));
                Console.WriteLine(computedHash);
                for (int i = 0; i < computedHash.Length; i++)
                {
                    if (computedHash[i] != passwordHash[i])
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
Ejemplo n.º 29
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));
         //we loop over the byte array & compare both hashes
         for (int i = 0; i < computedHash.Length; i++)
         {
             //if the element dont match then return false
             if (computedHash[i] != passwordHash[i])
             {
                 return(false);
             }
         }
     }
     //if the elements match then return true
     return(true);
 }
Ejemplo n.º 30
0
        private bool VerifyPasswordHash(string password, byte[] passwordHash, byte[] passwordSalt)
        {
            byte [] compPassHash;
            using (var compHash = new System.Security.Cryptography.HMACSHA512(passwordSalt))
            {
                compPassHash = compHash.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));

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

                return(true);
            }
        }
Ejemplo n.º 31
0
        private static bool VerifyPasswordHash(string inPassword, byte[] inStoredHash, byte[] inStoredSalt)
        {
            if (inPassword == null) throw new ArgumentNullException("password");
            if (string.IsNullOrWhiteSpace(inPassword)) throw new ArgumentException("Value cannot be empty or whitespace only string.", "password");
            if (inStoredHash.Length != 64) throw new ArgumentException("Invalid length of password hash (64 bytes expected).", "passwordHash");
            if (inStoredSalt.Length != 128) throw new ArgumentException("Invalid length of password salt (128 bytes expected).", "passwordHash");

            using (var hmac = new System.Security.Cryptography.HMACSHA512(inStoredSalt))
            {
                var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(inPassword));
                for (int i = 0; i < computedHash.Length; i++)
                {
                    if (computedHash[i] != inStoredHash[i]) return false;
                }
            }

            return true;
        }
Ejemplo n.º 32
0
        private void CreatePasswordHash(
            string password,
            out byte[] passwordHash,
            out byte[] passwordSalt

            )
        {
            using (var hmac = new System.Security.Cryptography.HMACSHA512())
            {
                passwordSalt = hmac.Key;
                passwordHash =
                    hmac.ComputeHash(System
                                     .Text
                                     .Encoding
                                     .UTF8
                                     .GetBytes(password));
            }
        }
        private bool VerifyUserPassword(string password, byte[] passwordHash, byte[] passwordSalt)
        {
            using (var hmac = new System.Security.Cryptography.HMACSHA512(passwordHash))
            {
                var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));

                //comparar byte a byte
                for (int i = 0; i < passwordSalt.Length; i++)
                {
                    if (passwordSalt[i] != computedHash[i])
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
		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);
			}
		}
		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));
			}
		}
Ejemplo n.º 36
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!");
            }
        }
Ejemplo n.º 37
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;
        }
Ejemplo n.º 38
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;
        }
Ejemplo n.º 39
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.");
                }
            }
        }
 static byte[] Sign(byte[] signingKey, byte[] message)
 {
     var hmac = new System.Security.Cryptography.HMACSHA512(signingKey);
     var hash = hmac.ComputeHash(message);
     return hash;
 }