예제 #1
0
 /// <summary>
 /// Every time is created new instance of class to guarantee thread safety
 /// </summary>
 /// <param name="function"></param>
 /// <returns></returns>
 private HMAC GetAlgorithmByFunctionName(string function)
 {
     HMAC a;
     switch(Util.Convertion.EnumNameToValue<HMACFunction>(function))
     {
         case HMACFunction.HMACMD5:
             a = new HMACMD5();
             break;
         case HMACFunction.HMACSHA1:
             a = new HMACSHA1();
             break;
         case HMACFunction.HMACSHA256:
             a = new HMACSHA256();
             break;
         case HMACFunction.HMACSHA384:
             a = new HMACSHA384();
             break;
         case HMACFunction.HMACSHA512:
             a = new HMACSHA512();
             break;
         default:
             throw new ArgumentException("Unknown function", "function");
     }
     return a;
 }
예제 #2
0
        public static string Encode(string publicKey, int choice = 2)
        {
            byte[] hashMessage = null;
            byte[] messageBytes = m_encoding.GetBytes(publicKey);

            switch (choice%6)
            {
                case 0:
                    var hmacmd5 = new HMACMD5(m_keyBytes);
                    hashMessage = hmacmd5.ComputeHash(messageBytes);
                    break;
                case 1:
                    var hmacripedmd160 = new HMACRIPEMD160(m_keyBytes);
                    hashMessage = hmacripedmd160.ComputeHash(messageBytes);
                    break;
                case 2:
                    var hmacsha1 = new HMACSHA1(m_keyBytes);
                    hashMessage = hmacsha1.ComputeHash(messageBytes);
                    break;
                case 3:
                    var hmacsha256 = new HMACSHA256(m_keyBytes);
                    hashMessage = hmacsha256.ComputeHash(messageBytes);
                    break;
                case 4:
                    var hmacsha384 = new HMACSHA384(m_keyBytes);
                    hashMessage = hmacsha384.ComputeHash(messageBytes);
                    break;
                case 5:
                    var hmacsha512 = new HMACSHA512(m_keyBytes);
                    hashMessage = hmacsha512.ComputeHash(messageBytes);
                    break;
            }

            return Convert.ToBase64String(hashMessage);
        }
예제 #3
0
        public static string CryptoSHA512(string TextToCryptograph)
        {
            var sha512 = new HMACSHA512();
            byte[] passwordArray = System.Text.Encoding.Default.GetBytes(TextToCryptograph);

            return Convert.ToBase64String(sha512.ComputeHash(passwordArray));
        }
예제 #4
0
 static JsonWebToken()
 {
     HashAlgorithms = new Dictionary<JwtHashAlgorithm, Func<byte[], byte[], byte[]>>
                      {
                          {JwtHashAlgorithm.RS256, (key, value) =>
                                                   {
                                                       using (var sha = new HMACSHA256(key))
                                                       {
                                                           return sha.ComputeHash(value);
                                                       }
                                                   }
                          },
                          {JwtHashAlgorithm.HS384, (key, value) =>
                                                   {
                                                       using (var sha = new HMACSHA384(key))
                                                       {
                                                           return sha.ComputeHash(value);
                                                       }
                                                   }
                          },
                          {JwtHashAlgorithm.HS512, (key, value) =>
                                                   {
                                                       using (var sha = new HMACSHA512(key))
                                                       {
                                                           return sha.ComputeHash(value);
                                                       }
                                                   }
                          }
                      };
 }
예제 #5
0
 // Computes a keyed hash for a source file and creates a target file with the keyed hash
 // prepended to the contents of the source file.
 public static void SignFile(byte[] key, String sourceFile, String destFile)
 {
     // Initialize the keyed hash object.
     using (HMACSHA512 hmac = new HMACSHA512(key))
     {
         using (FileStream inStream = new FileStream(sourceFile, FileMode.Open))
         {
             using (FileStream outStream = new FileStream(destFile, FileMode.Create))
             {
                 // Compute the hash of the input file.
                 byte[] hashValue = hmac.ComputeHash(inStream);
                 // Reset inStream to the beginning of the file.
                 inStream.Position = 0;
                 // Write the computed hash value to the output file.
                 outStream.Write(hashValue, 0, hashValue.Length);
                 // Copy the contents of the sourceFile to the destFile.
                 int bytesRead;
                 // read 1K at a time
                 byte[] buffer = new byte[1024];
                 do
                 {
                     // Read from the wrapping CryptoStream.
                     bytesRead = inStream.Read(buffer, 0, 1024);
                     outStream.Write(buffer, 0, bytesRead);
                 } while (bytesRead > 0);
             }
         }
     }
 }
예제 #6
0
 public static byte[] HMACSHA512(byte[] key, byte[] data)
 {
     using (var hmac = new HMACSHA512(key))
     {
         return hmac.ComputeHash(data);
     }
 }
예제 #7
0
 public BtceApi(string key, string secret)
     : this(key, secret, null)
 {
     this.key = key;
     hashMaker = new HMACSHA512(Encoding.ASCII.GetBytes(secret));
     nonce = UnixTime.Now;
 }
예제 #8
0
 public BtceApi(string key, string secret, string exchangeHost = null)
 {
     this.key = key;
     hashMaker = new HMACSHA512(Encoding.ASCII.GetBytes(secret));
     nonce = UnixTime.Now;
     this.instanseExchangeHost = exchangeHost ?? ExchangeHost;
 }
 public Rfc2898DeriveBytes_HMACSHA512(byte[] password, byte[] salt, int iterations)
 {
     Salt = salt;
     IterationCount = iterations;
     _hmacsha512 = new HMACSHA512(password);
     Initialize();
 }
예제 #10
0
 public byte[] Hash(byte[] key, byte[] plainText)
 {
     using (var hmac = new HMACSHA512(key))
     {
         return hmac.ComputeHash(plainText);
     }
 }
 private static byte[] getHash(byte[] keyByte, byte[] messageBytes)
 {
     using (var hmacsha512 = new HMACSHA512(keyByte))
     {
         Byte[] result = hmacsha512.ComputeHash(messageBytes);
         return result;
     }
 }
        public string GenerateSHA512Signature(FormUrlEncodedContent request)
        {
            HMAC digester = new HMACSHA512(this.PrivateKeyBytes);
            StringBuilder hex = new StringBuilder();
            byte[] requestBytes = System.Text.Encoding.ASCII.GetBytes(request.ReadAsStringAsync().Result);

            return BitConverter.ToString(digester.ComputeHash(requestBytes)).Replace("-", "").ToLower();
        }
예제 #13
0
		public override void SetUp () 
		{
			algo = new HMACSHA512 ();
			algo.Key = new byte [8];
			hash = algo;
			// http://blogs.msdn.com/shawnfa/archive/2007/01/31/please-do-not-use-the-net-2-0-hmacsha512-and-hmacsha384-classes.aspx
			legacy = (new HS512 ().BlockSize == 64);
		}
 public byte[] HashingAMessageWithASecretKey(byte[] iterationNumberByte, byte[] userIdByte)
 {
     using (var hmac = new HMACSHA512(userIdByte))
     {
         byte[] hash = hmac.ComputeHash(iterationNumberByte);
         return hash;
     }
 }
예제 #15
0
 public BtceApi(string key, string secret)
 {
     this.key = key;
     foreach (var b in Encoding.ASCII.GetBytes(secret))
         Console.Write(b);
     hashMaker = new HMACSHA512(Encoding.ASCII.GetBytes(secret));
     nonce = UnixTime.Now;
 }
예제 #16
0
        public static string ComputeSHA(string str, string key)
        {
            byte[] passwordBytes = ASCIIEncoding.ASCII.GetBytes(str);
            byte[] saltBytes = ASCIIEncoding.ASCII.GetBytes(key);
            var crypt = new HMACSHA512(saltBytes);

            return BitConverter.ToString(crypt.ComputeHash(passwordBytes)).Replace("-", "");
        }
        public string Generate(string password)
        {
            byte[] msgByte = ASCIIEncoding.ASCII.GetBytes(password);

            HMACSHA512 hmac = new HMACSHA512();
            byte[] hashMsg = hmac.ComputeHash(msgByte);

            return HttpServerUtility.UrlTokenEncode(hashMsg);
        }
예제 #18
0
        public BtceApi(IConfiguration config, ILogger logger)
        {
            _config = config;
            _logger = logger;

            _hashMaker = new HMACSHA512(Encoding.ASCII.GetBytes(_config.SecretKey));

            synchronizeNonce();
        }
예제 #19
0
        /// <summary>
        /// Computes the mac sha512.
        /// </summary>
        /// <param name="storageKey">The storage key.</param>
        /// <param name="canonicalizedString">The canonicalized string.</param>
        /// <returns>The computed hash.</returns>
        internal static string ComputeMacSha512(StorageKey storageKey, string canonicalizedString)
        {
            byte[] dataToMAC = Encoding.UTF8.GetBytes(canonicalizedString);

            using (HMACSHA512 hmacsha1 = new HMACSHA512(storageKey.Key))
            {
                return System.Convert.ToBase64String(hmacsha1.ComputeHash(dataToMAC));
            }
        }
예제 #20
0
 public byte[] Hash(byte[] clearBytes)
 {
     using (var hmac = new HMACSHA512(_key))
     {
         hmac.Initialize();
         byte[] hashBytes = hmac.ComputeHash(clearBytes);
         return hashBytes;
     }
 }
예제 #21
0
        public static String Sign(HttpRequestMessage request, String secretKey)
        {
            String message = BuildMessage(request);

            HMACSHA512 hmac = new HMACSHA512(Convert.FromBase64String(secretKey));
            byte[] signature = hmac.ComputeHash(encoding.GetBytes(message));

            return Convert.ToBase64String(signature);
        }
예제 #22
0
		public void Constructors () 
		{
			algo = new HMACSHA512 ();
			Assert.IsNotNull (algo, "HMACSHA512 ()");

			byte[] key = new byte [8];
			algo = new HMACSHA512 (key);
			Assert.IsNotNull (algo, "HMACSHA512 (key)");
		}
 public static string SignString512(string stringToSign, string secretKey)
 {
     byte[] secretkeyBytes = Convert.FromBase64String(secretKey);
     byte[] inputBytes = Encoding.UTF8.GetBytes(stringToSign);
     using (var hmac = new HMACSHA512(secretkeyBytes))
     {
         byte[] hashValue = hmac.ComputeHash(inputBytes);
         return System.Convert.ToBase64String(hashValue);
     }
 }
예제 #24
0
 private static string CreateSharedAccessToken(string id, string key, DateTime expiry)
 {
     using (var encoder = new HMACSHA512(Encoding.UTF8.GetBytes(key)))
     {
         var dataToSign = id + "\n" + expiry.ToString("O", CultureInfo.InvariantCulture);
         var hash = encoder.ComputeHash(Encoding.UTF8.GetBytes(dataToSign));
         var signature = Convert.ToBase64String(hash);
         var encodedToken = $"uid={id}&ex={expiry:o}&sn={signature}";
         return encodedToken;
     }
 }
예제 #25
0
        /// <summary>
        /// Creates a Sha512 HMAC hash of an inputted string.
        /// </summary>
        /// <param name="input">The string to create the hash from.</param>
        internal static string ComputeHmacSha512Hash(string input, string secret)
        {
            var utf8Encoding = new UTF8Encoding();
            var inputBytes = utf8Encoding.GetBytes(input);
            var secretBytes = utf8Encoding.GetBytes(secret);

            var hmacSha512 = new HMACSHA512(secretBytes);
            var hash = hmacSha512.ComputeHash(inputBytes);

            return BitConverter.ToString(hash).Replace("-", "");
        }
예제 #26
0
        OrderInfoResponse _dummySellOrder; //TODO: DELETE THESE TWO LINES

        #endregion Fields

        #region Constructors

        internal CoinsBankApi(IConfiguration config, ILogger logger, string baseAsset, string counterAsset)
        {
            _config = config;
            _logger = logger;
            _baseAsset = baseAsset.ToUpperInvariant();
            _counterAsset = counterAsset.ToUpperInvariant();
            _dataBaseUrl = config.GetValue("data_api_url");
            _tradeBaseUrl = config.GetValue("trading_base_url");

            _hashMaker = new HMACSHA512(Encoding.ASCII.GetBytes(_config.SecretKey));
        }
예제 #27
0
		public void Invariants () 
		{
			algo = new HMACSHA512 ();
			Assert.IsTrue (algo.CanReuseTransform, "HMACSHA512.CanReuseTransform");
			Assert.IsTrue (algo.CanTransformMultipleBlocks, "HMACSHA512.CanTransformMultipleBlocks");
			Assert.AreEqual ("SHA512", algo.HashName, "HMACSHA512.HashName");
			Assert.AreEqual (512, algo.HashSize, "HMACSHA512.HashSize");
			Assert.AreEqual (1, algo.InputBlockSize, "HMACSHA512.InputBlockSize");
			Assert.AreEqual (1, algo.OutputBlockSize, "HMACSHA512.OutputBlockSize");
			Assert.AreEqual ("System.Security.Cryptography.HMACSHA512", algo.ToString (), "HMACSHA512.ToString()");
		}
예제 #28
0
        public static byte[] CreateHmac(byte[] iv, byte[] encryptedBytes, string password)
        {
            var data = encryptedBytes.Concat(iv).ToArray();

            byte[] result;
            using (var hmacsha512 = new HMACSHA512(data))
            {
                result = hmacsha512.ComputeHash(CreateKey(password, SaltType.Hmac));
            }

            return result;
        }
예제 #29
0
        private static string Gethmacsha512(Encoding encoding, string apiSecret, string url)
        {
            // doing the encoding
            var keyByte = encoding.GetBytes(apiSecret);
            string result;
            using (var hmacsha512 = new HMACSHA512(keyByte))
            {
                hmacsha512.ComputeHash(encoding.GetBytes(url));

                result = ByteToString(hmacsha512.Hash);
            }
            return result;
        }
예제 #30
0
파일: SecurityHelper.cs 프로젝트: mrG7/PTS
        /// <summary>
        /// Computes Hash 
        /// </summary>
        /// <param name="messageKey"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public static string ComputeHash(string messageKey, string message)
        {
            var key = Encoding.UTF8.GetBytes(messageKey.ToUpper());
            string hashString;

            using (var hmac = new HMACSHA512(key))
            {
                var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(message));
                hashString = Convert.ToBase64String(hash);
            }

            return hashString;
        }
예제 #31
0
 public static bool VerifyPasswordHash(string password, byte[] passwordHash, byte[] passwordSalt)//doğrulama password hash yapcaz - out ilave etmiyoruz çünkü doğrulama yapcaz
 {
     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);
 }
예제 #32
0
 // GOOD - Hash with a salt.
 public 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 i = 0; i < computedHash.Length; i++)
         {
             if (computedHash[i] != passwordHash[i])
             {
                 return(false);
             }
         }
         return(true);
     }
 }
예제 #33
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("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));
        }
예제 #34
0
 private bool VerifyPassword(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)); // 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.
 }
예제 #35
0
 public bool ValidateHashCode(string password, byte[] passwordHash, byte[] passwordSalt)
 {
     using (var hmac = new System.Security.Cryptography.HMACSHA512(passwordSalt))
     {
         byte[] hashpassword = hmac.ComputeHash(Encoding.ASCII.GetBytes(password));
         for (int i = 0; i < hashpassword.Length; i = i + 1)
         {
             if (hashpassword[i] != passwordHash[i])
             {
                 return(false);
             }
         }
     }
     return(true);
 }
예제 #36
0
 public static bool AdminVerifyPasswordHash(string userName, byte[] userNameHash)
 {
     using (var hmac = new System.Security.Cryptography.HMACSHA512())
     {
         var computedAdminMailHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(userName));
         for (int i = 0; i < computedAdminMailHash.Length; i++)
         {
             if (computedAdminMailHash[i] != userNameHash[i])
             {
                 return(false);
             }
         }
         return(true);
     }
 }
예제 #37
0
 public static bool VerificarSenhaHash(string senha, byte[] passwordHash, byte[] passwordSalt)
 {
     using (var hmac = new System.Security.Cryptography.HMACSHA512(passwordSalt))
     {
         var ComputeHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(senha));
         for (var i = 0; i < ComputeHash.Length; i++)
         {
             if (ComputeHash[i] != passwordHash[i])
             {
                 return(false);
             }
         }
     }
     return(true);
 }
예제 #38
0
 public bool WriterLogin(WriterLoginDto writerLoginDto)
 {
     using (var crypto = new System.Security.Cryptography.HMACSHA512())
     {
         var writer = _writerService.GetList();
         foreach (var item in writer)
         {
             if (HashingHelper.WriterVerifyPasswordHash(writerLoginDto.WriterPassword,
                                                        item.WriterPasswordHash, item.WriterPasswordSalt))
             {
                 return(true);
             }
         }
         return(false);
     }
 }
예제 #39
0
        private bool VerifyPasswordHash(string password, byte[] passwordHash, byte[] passwordSalt)
        {
            // create password hash from salt and password to see if it matches computedHash
            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);
        }
예제 #40
0
        private static bool VerifyPinHash(string Pin, byte[] pinHash, byte[] pinSalt)
        {
            //
            using (var hmac = new System.Security.Cryptography.HMACSHA512(pinSalt))
            {
                var computedPinHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(Pin));
                for (int i = 0; i < computedPinHash.Length; i++)
                {
                    if (computedPinHash[i] != pinHash[i])
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
        private static void HashPassword(string password, out byte[] hashed, out byte[] salt)
        {
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }
            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentException("Value cannot be null or whitespace.", "password");
            }

            using (var hmac = new System.Security.Cryptography.HMACSHA512())
            {
                salt   = hmac.Key;
                hashed = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
            }
        }
예제 #42
0
        // private helper methods

        private static void CreatePasswordHash(string password, out string passwordHash, out string passwordSalt)
        {
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }
            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentException("Value cannot be empty or whitespace only string.", "password");
            }

            passwordSalt = getSalt();
            using (var hmac = new System.Security.Cryptography.HMACSHA512(Encoding.UTF8.GetBytes(passwordSalt)))
            {
                passwordHash = BitConverter.ToString(hmac.ComputeHash(Encoding.UTF8.GetBytes(password))).Replace("-", "").ToLower();
            }
        }
예제 #43
0
 public bool AdminLogIn(LoginDto adminLogInDto)
 {
     using (var crypto = new System.Security.Cryptography.HMACSHA512())
     {
         var mailHash = crypto.ComputeHash(Encoding.UTF8.GetBytes(adminLogInDto.AdminMail));
         var admin    = _adminService.GetList();
         foreach (var item in admin)
         {
             if (HashingHelper.AdminVerifyPasswordHash(adminLogInDto.AdminMail, adminLogInDto.AdminPassword, item.AdminMail,
                                                       item.AdminPasswordHash, item.AdminPasswordSalt))
             {
                 return(true);
             }
         }
         return(false);
     }
 }
        public static bool VerifyPasswordHash(string password, string passwordHash, string passwordSalt)
        {
            using (var hmac = new System.Security.Cryptography.HMACSHA512(Encoding.UTF8.GetBytes(passwordSalt)))
            {
                var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
                var oldHash      = Convert.FromBase64String(passwordHash);

                for (int i = 0; i < computedHash.Length; i++)
                {
                    if (computedHash[i] != oldHash[i])
                    {
                        return(false);
                    }
                }
                return(true);
            }
        }
예제 #45
0
        private bool VerifyUserPasswordHash(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);                                           // Burası return false olacak. Ancak hash te bi sıkıntı var devam ediyoruz şimdilik.
                    }
                }
            }

            return(true);
        }
예제 #46
0
        private bool ValidatePassword(string password, byte[] passwordHash, byte[] passwordSalt)
        {
            using (var hmac = new System.Security.Cryptography.HMACSHA512(passwordSalt))
            {
                var hashComputado = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));


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

            return(true);
        }
예제 #47
0
        private bool VerifyPasswordHash(string password, byte[] userPasswordHash, byte[] userPasswordSalt)
        {
            var passwordVerified = true;

            using (var hmac = new System.Security.Cryptography.HMACSHA512(userPasswordSalt))
            {
                var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
                for (var i = 0; i < computedHash.Length; i++)
                {
                    if (computedHash[i] == userPasswordHash[i])
                    {
                        continue;
                    }
                    passwordVerified = false;
                    break;
                }
            }

            return(passwordVerified);
        }
예제 #48
0
        private PasswordModel CreatePasswordHashModel(string password)
        {
            PasswordModel model = new PasswordModel();

            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())
            {
                model.passwordSalt = hmac.Key;
                model.passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
            }
            return(model);
        }
예제 #49
0
        public static bool VerifyPasswordHash(string username, string password, byte[] storedHash, byte[] storedSalt)
        {
            if (username == null || password == null)
            {
                throw new ArgumentNullException("Username or password is required");
            }
            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentException("Value cannot be empty or whitespace only string.", "password");
            }
            if (storedHash.Length != 64)
            {
                throw new ArgumentException("Invalid length of password hash (64 bytes expected).", "passwordHash");
            }
            if (storedSalt.Length != 128)
            {
                throw new ArgumentException("Invalid length of password salt (128 bytes expected).", "passwordHash");
            }
            var email = new EmailAddressAttribute();

            if (email.IsValid(username))
            {
                username = $"{username.Substring(0, username.IndexOf('@'))}{key}";
            }
            else
            {
                username = username + key;
            }
            using (var hmac = new System.Security.Cryptography.HMACSHA512(storedSalt))
            {
                var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password + username));
                for (int i = 0; i < computedHash.Length; i++)
                {
                    if (computedHash[i] != storedHash[i])
                    {
                        return(false);
                    }
                }
            }
            return(true);
        }
예제 #50
0
        // *****************************************************************************************
        //  Hash Method
        //
        /// <summary>
        ///    Generates hashed string
        ///     </summary>
        /// <remarks>
        ///    Generic hash function that can be used for alternative hashing implementations
        ///     </remarks>
        /// <param name="string">
        ///        Input value to be hashed
        ///     </param>
        /// <param name="key">
        ///     </param>
        /// <returns>
        ///    Hash string
        ///     </returns>
        //
        // *****************************************************************************************
        public 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(value);
            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);
        }
예제 #51
0
    public static bool ChangePassword(string userName, string userPassword = "", string newPassword = "", bool forceChange = false)
    {
        if (string.IsNullOrWhiteSpace(newPassword))
        {
            return(false);
        }

        if (forceChange == false && string.IsNullOrWhiteSpace(userPassword))
        {
            return(false);
        }

        var user = _db.Users.Where(x => x.UserName == userName.Trim()).FirstOrDefault();

        if (user == null)
        {
            return(false);
        }


        var validPassword = !forceChange?VerifyPasswordHash(userPassword, user.PasswordSalt, user.PasswordHash) : true;

        if (validPassword)
        {
            // Overwrite with new PasswordHash
            using (var hmac = new System.Security.Cryptography.HMACSHA512())
            {
                user.PasswordSalt = hmac.Key;
                user.PasswordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(newPassword));
            }

            _db.Entry(user).State = System.Data.Entity.EntityState.Modified;
            _db.SaveChanges();
            return(true);
        }
        else
        {
            return(false);
        }
    }
예제 #52
0
    public static int?Create(string userName, string userPassword, string userRoles = "", bool requiresActivation = false)
    {
        if (string.IsNullOrWhiteSpace(userPassword))
        {
            return(null);
        }
        if (string.IsNullOrWhiteSpace(userName) || userName.Any(Char.IsWhiteSpace))
        {
            return(null);
        }

        var user = new UserAccount();

        user.UserName = userName.Trim().ToLower();

        var userExists = _db.Users.Where(x => x.UserName == user.UserName).Count() > 0;

        if (userExists)
        {
            return(null);
        }

        // Create PasswordHash
        using (var hmac = new System.Security.Cryptography.HMACSHA512())
        {
            user.PasswordSalt = hmac.Key;
            user.PasswordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(userPassword));
        }

        user.Roles     = System.Text.RegularExpressions.Regex.Replace(userRoles, @"\s+", "");
        user.CreatedOn = DateTime.Now;
        user.IsActive  = !requiresActivation;

        _db.Users.Add(user);
        _db.SaveChanges();

        return(user.Id);
    }
예제 #53
0
 public static bool AdminVerifyPasswordHash(string adminMail, string password, byte[] adminMailHash, byte[] adminPasswordHash, byte[] passwordSalt)
 {
     using (var hmac = new System.Security.Cryptography.HMACSHA512(passwordSalt))
     {
         var computedPasswordHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(password));
         for (int i = 0; i < computedPasswordHash.Length; i++)
         {
             if (computedPasswordHash[i] != adminPasswordHash[i])
             {
                 return(false);
             }
         }
         var computedAdminMailHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(adminMail));
         for (int i = 0; i < computedAdminMailHash.Length; i++)
         {
             if (computedAdminMailHash[i] != adminMailHash[i])
             {
                 return(false);
             }
         }
         return(true);
     }
 }
 public bool VerifyPasswordHash(string password, byte[] storedHash,
                                byte[] storedSalt)
 {
     if (password == null ||
         string.IsNullOrWhiteSpace(password) ||
         storedHash.Length != 64 ||
         storedSalt.Length != 128)
     {
         return(false);
     }
     using (var hmac = new System.Security.Cryptography.HMACSHA512(storedSalt))
     {
         var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
         for (int i = 0; i < computedHash.Length; i++)
         {
             if (computedHash[i] != storedHash[i])
             {
                 return(false);
             }
         }
     }
     return(true);
 }
예제 #55
0
        public static bool VerifyPasswordHash(string password, byte[] storedHash, byte[] storedSalt)
        {
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }

            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentException("Value cannot be empty or whitespace only string.", "password");
            }

            if (storedHash.Length != 64)
            {
                throw new ArgumentException("Invalid length of password hash (64 bytes expected).", "passwordHash");
            }

            if (storedSalt.Length != 128)
            {
                throw new ArgumentException("Invalid length of password salt (128 bytes expected).", "passwordHash");
            }

            using (var hmac = new System.Security.Cryptography.HMACSHA512(storedSalt))
            {
                byte[] computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));

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

            return(true);
        }
예제 #56
0
        private static bool VerifyPasswordHash(string password, string passwordHash, string passwordSalt)
        {
            if (password == null)
            {
                throw new ArgumentNullException("password", "Password is required!");
            }

            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentException("Password can not be null or empty only string!", "password");
            }

            var PasswordHash = Convert.FromBase64String(passwordHash);
            var PasswordSalt = Convert.FromBase64String(passwordSalt);

            if (PasswordHash.Length != 64)
            {
                throw new ArgumentException("Invalid length of password hash (64 bytes expected)", "passwordHash");
            }
            if (PasswordSalt.Length != 128)
            {
                throw new ArgumentException("Invalid length of password salt (128 bytes expected)", "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);
        }
        private bool IsAuthUser(User userInfo)
        {
            var userName     = _configuration.GetSection("AutorizationSettings:User").Value;
            var passwordSalt = Convert.FromBase64String(_configuration.GetSection("AutorizationSettings:Salt").Value);
            var passwordHash = Convert.FromBase64String(_configuration.GetSection("AutorizationSettings:PasswordHash").Value);

            if (userName != userInfo.UserName)
            {
                return(false);
            }

            using (var hmac = new System.Security.Cryptography.HMACSHA512(passwordSalt))
            {
                var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(userInfo.Password));
                for (int i = 0; i < computedHash.Length; i++)
                {
                    if (computedHash[i] != passwordHash[i])
                    {
                        return(false);
                    }
                }
                return(true);
            }
        }
예제 #58
0
        private static bool VerifyPasswordHash(string password, byte[] storedHash, byte[] storedSalt)
        {
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }
            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentException("Value cannot be empty or whitespace only string.", "password");
            }
            if (storedHash.Length != 64)
            {
                throw new ArgumentException("Invalid length of password hash (64 bytes expected).", "passwordHash");
            }
            if (storedSalt.Length != 128)
            {
                throw new ArgumentException("Invalid length of password salt (128 bytes expected).", "passwordHash");
            }

            using var hmac = new System.Security.Cryptography.HMACSHA512(storedSalt);
            var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));

            return(!computedHash.Where((t, i) => t != storedHash[i]).Any());
        }
예제 #59
0
        public static HMAC CreateHmac( )
        {
            var hmac = new System.Security.Cryptography.HMACSHA512();

            return(hmac);
        }
예제 #60
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));
 }