Exemplo n.º 1
0
        public TokenViewModel GenerateToken(int userID, string username, string password, string ip, string userAgent, long ticks)
        {
            string hash      = string.Join(":", new string[] { username, ip, userAgent, ticks.ToString() });
            string hashLeft  = "";
            string hashRight = "";

            using (HMAC hmac = HMACSHA256.Create(_alg))
            {
                hmac.Key = Encoding.UTF8.GetBytes(GetHashedPassword(password));
                hmac.ComputeHash(Encoding.UTF8.GetBytes(hash));
                hashLeft  = Convert.ToBase64String(hmac.Hash);
                hashRight = string.Join(":", new string[] { username, ticks.ToString() });
            }
            string tokenString = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Join(":", hashLeft, hashRight)));
            var    issuedOn    = DateTime.Now;

            var token = new Token
            {
                UserId      = userID,
                TokenString = tokenString,
                IssuedOn    = issuedOn,
                ExpiresIn   = 86400
            };

            _tokenRepository.Add(token);

            _unitOfWork.SaveChanges();
            return(Mapper.Map <Token, TokenViewModel>(token));
        }
Exemplo n.º 2
0
        /// <summary>
        /// Generates a token based on username, passwords and timestamp.
        /// </summary>
        /// <param name="username">The username.</param>
        /// <param name="password">The password.</param>
        /// <param name="timestamp">The timestamp.</param>
        /// <param name="userId">The user identifier.</param>
        /// <returns></returns>
        public static string GenerateToken(string username, string password, DateTime timestamp, int userId)
        {
            //Getting strings from parameter
            string hash       = username + timestamp.ToString() + password;
            string firstHash  = "";
            string secondHash = "";

            //Creating a
            using (HMAC hmac = HMACSHA256.Create(_alg))
            {
                hmac.Key = Encoding.UTF8.GetBytes(password);

                hmac.ComputeHash(Encoding.UTF8.GetBytes(hash));

                firstHash = Convert.ToBase64String(hmac.Hash);

                secondHash = username + ":" + timestamp.ToString();
            }
            //Adding hash values together
            var token = Convert.ToBase64String(Encoding.UTF8.GetBytes(firstHash + ":" + secondHash));

            //If this code was complete, it would be possible to decode it using the same rules.

            return(token);
        }
Exemplo n.º 3
0
        public void Hash(byte[] temp)
        {
            using var DSACng = new DSACng(10);                                                                                      // Noncompliant {{Make sure this weak hash algorithm is not used in a sensitive context here.}}
//                             ^^^^^^^^^^^^^^
            using var DSACryptoServiceProvider = new DSACryptoServiceProvider();                                                    // Noncompliant
            using var DSACreate              = DSA.Create();                                                                        // Noncompliant
            using var DSACreateWithParam     = DSA.Create("DSA");                                                                   // Noncompliant
            using var DSACreateFromName      = (AsymmetricAlgorithm)CryptoConfig.CreateFromName("DSA");                             // Noncompliant
            using var DSAAsymmetricAlgorithm = AsymmetricAlgorithm.Create("DSA");                                                   // Noncompliant
            using var DSAAsymmetricAlgorithmWithNamespace = AsymmetricAlgorithm.Create("System.Security.Cryptography.DSA");         // Noncompliant

            using var HMACCreate          = HMAC.Create();                                                                          // Noncompliant
            using var HMACCreateWithParam = HMAC.Create("HMACMD5");                                                                 // Noncompliant

            using var HMACMD5                   = new HMACMD5();                                                                    // Noncompliant
            using var HMACMD5Create             = HMACMD5.Create();                                                                 // Noncompliant
            using var HMACMD5CreateWithParam    = HMACMD5.Create("HMACMD5");                                                        // Noncompliant
            using var HMACMD5KeyedHashAlgorithm = KeyedHashAlgorithm.Create("HMACMD5");                                             // Noncompliant
            using var HMACMD5KeyedHashAlgorithmWithNamespace = KeyedHashAlgorithm.Create("System.Security.Cryptography.HMACMD5");   // Noncompliant
            using var HMACMD5CryptoConfig = (HashAlgorithm)CryptoConfig.CreateFromName("HMACMD5");                                  // Noncompliant

            using var HMACSHA1                   = new HMACSHA1();                                                                  // Noncompliant
            using var HMACSHA1Create             = HMACMD5.Create();                                                                // Noncompliant
            using var HMACSHA1CreateWithParam    = HMACMD5.Create("HMACSHA1");                                                      // Noncompliant
            using var HMACSHA1KeyedHashAlgorithm = KeyedHashAlgorithm.Create("HMACSHA1");                                           // Noncompliant
            using var HMACSHA1KeyedHashAlgorithmWithNamespace = KeyedHashAlgorithm.Create("System.Security.Cryptography.HMACSHA1"); // Noncompliant
            using var HMACSHA1CryptoConfig = (HashAlgorithm)CryptoConfig.CreateFromName("HMACSHA1");                                // Noncompliant

            using var HMACSHA256Create             = HMACSHA256.Create("HMACSHA256");
            using var HMACSHA256KeyedHashAlgorithm = KeyedHashAlgorithm.Create("HMACSHA256");
            using var HMACSHA256KeyedHashAlgorithmWithNamespace = KeyedHashAlgorithm.Create("System.Security.Cryptography.HMACSHA256");
            using var HMACSHA256CryptoConfig = (HashAlgorithm)CryptoConfig.CreateFromName("HMACSHA256");

            using var MD5CryptoServiceProvider      = new MD5CryptoServiceProvider();                             // Noncompliant
            using var MD5CryptoConfig               = (HashAlgorithm)CryptoConfig.CreateFromName("MD5");          // Noncompliant
            using var MD5HashAlgorithm              = HashAlgorithm.Create("MD5");                                // Noncompliant
            using var MD5HashAlgorithmWithNamespace = HashAlgorithm.Create("System.Security.Cryptography.MD5");   // Noncompliant
            using var MD5Create          = MD5.Create();                                                          // Noncompliant
            using var MD5CreateWithParam = MD5.Create("MD5");                                                     // Noncompliant

            using var SHA1Managed                    = new SHA1Managed();                                         // Noncompliant
            using var SHA1Create                     = SHA1.Create();                                             // Noncompliant
            using var SHA1CreateWithParam            = SHA1.Create("SHA1");                                       // Noncompliant
            using var SHA1HashAlgorithm              = HashAlgorithm.Create("SHA1");                              // Noncompliant
            using var SHA1HashAlgorithmWithNamespace = HashAlgorithm.Create("System.Security.Cryptography.SHA1"); // Noncompliant
            using var SHA1CryptoServiceProvider      = new SHA1CryptoServiceProvider();                           // Noncompliant

            using var sha256Managed       = new SHA256Managed();
            using var sha256HashAlgorithm = HashAlgorithm.Create("SHA256Managed");
            using var sha256HashAlgorithmWithNamespace = HashAlgorithm.Create("System.Security.Cryptography.SHA256Managed");
            var sha256CryptoConfig = CryptoConfig.CreateFromName("SHA256Managed");

            HashAlgorithm hashAlgo = HashAlgorithm.Create();

            var algoName = "MD5";
            var md5Var   = (HashAlgorithm)CryptoConfig.CreateFromName(algoName); // Noncompliant

            algoName = "SHA256Managed";
            var SHA256ManagedVar = (HashAlgorithm)CryptoConfig.CreateFromName(algoName);
        }
Exemplo n.º 4
0
        public string GenerateToken(string secret)
        {
            if (WasInbound)
            {
                return(OriginalToken);
            }

            StringBuilder sb = new StringBuilder();

            OriginalParts = new string[3];

            OriginalParts[0] = $"{{typ:\"{Type}\", alg=\"{Algorithm}\"}}";
            sb.Append(Convert.ToBase64String(Encoding.UTF8.GetBytes(OriginalParts[0])));

            string hash;

            switch (Algorithm)
            {
            case "HS256":
                hash = Convert.ToBase64String(HMACSHA256.Create().ComputeHash(Encoding.UTF8.GetBytes(sb.ToString())));
                break;

            case "none":
                hash = string.Empty;
                break;

            default:
                throw new InvalidOperationException("You are generating a token string without setting the Algorithm properly");
            }
            sb.Append(".").Append(hash);

            return(sb.ToString());
        }
Exemplo n.º 5
0
        public void HmaCalls()
        {
            using (var hmac = new HMACSHA1()) // Noncompliant
            {
            }
            using (var hmac = HMAC.Create()) // Noncompliant
            {
            }
            using (var hmacmd5 = HMACMD5.Create("HMACMD5")) // Noncompliant
            {
            }
            using (var hmacmd5 = KeyedHashAlgorithm.Create("HMACMD5")) // Noncompliant
            {
            }
            using (var hmacmd5 = (KeyedHashAlgorithm)CryptoConfig.CreateFromName("HMACMD5")) // Noncompliant
            {
            }

            using (var hmacsha256 = HMACSHA256.Create("HMACSHA256"))
            {
            }
            using (var hmacsha256 = KeyedHashAlgorithm.Create("HMACSHA256"))
            {
            }
            using (var hmacsha256 = (KeyedHashAlgorithm)CryptoConfig.CreateFromName("HMACSHA256"))
            {
            }
        }
Exemplo n.º 6
0
        public static bool IsTokenValid(string token, string ip, string userAgent)
        {
            bool result = false;

            try
            {
                // Base64 decode the string, obtaining the token:username:timeStamp.
                string key = Encoding.UTF8.GetString(Convert.FromBase64String(token));
                // Split the parts.
                string[] parts = key.Split(new char[] { ':' });
                if (parts.Length == 3)
                {
                    // Get the hash message, username, and timestamp.
                    string   hash      = parts[0];
                    string   username  = parts[1];
                    long     ticks     = long.Parse(parts[2]);
                    DateTime timeStamp = new DateTime(ticks);
                    // Ensure the timestamp is valid.
                    bool expired = Math.Abs((DateTime.UtcNow - timeStamp).TotalMinutes) > _expirationMinutes;
                    if (!expired)
                    {
                        String passwordEnc = string.Empty;
                        string hashLeft    = string.Empty;
                        using (HMAC hmac = HMACSHA256.Create(_alg))
                        {
                            hmac.ComputeHash(Encoding.UTF8.GetBytes(hash));
                            hashLeft = Convert.ToBase64String(hmac.Hash);
                        }
                        using (var ctx = new GASEntities())
                        {
                            if (username.All(char.IsDigit))
                            {
                                passwordEnc = (from u in ctx.Users
                                               where u.UserMobile == username
                                               select u.Password.ToString()).First();
                            }
                            else
                            {
                                passwordEnc = (from u in ctx.Users
                                               where u.UserEmail == username
                                               select u.Password.ToString()).First();
                            }
                        }
                        if (!string.IsNullOrEmpty(passwordEnc))
                        {
                            string computedToken = GenerateTokenUsingHashPassword(username, passwordEnc, ip, userAgent, ticks);
                            // Compare the computed token with the one supplied and ensure they match.
                            result = (token == computedToken);
                        }
                    }
                }
            }
            catch
            {
            }
            return(result);
        }
Exemplo n.º 7
0
        public static string GetHash256(string password, string salt)
        {
            byte[] passwordByte = ASCIIEncoding.ASCII.GetBytes(password + salt + "SM");

            // HashAlgorithm algorithm = new HMACSHA256();
            HashAlgorithm algorithm = HMACSHA256.Create();
            Byte[] hashPassword = algorithm.ComputeHash(passwordByte);
            return Convert.ToBase64String(hashPassword);
        }
Exemplo n.º 8
0
        private string MakeAuthorizationSign(PayLoad?body)
        {
            var crypto = HMACSHA256.Create("HmacSHA256");

            crypto.Key = Encoding.UTF8.GetBytes(AppSecret);
            var hash = crypto.ComputeHash(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(body)));

            return(Convert.ToBase64String(hash));
        }
Exemplo n.º 9
0
 private void ComputeHash(string path)
 {
     using (var fileStream = File.OpenRead(path))
     {
         using (var hasher = HMACSHA256.Create())
         {
             _result = hasher.ComputeHash(fileStream);
         }
     }
 }
Exemplo n.º 10
0
        public static byte[] ComputeHash(byte[] input, byte[] key, string algorithm)
        {
            if (input == null || input.Length == 0)
            {
                throw new ArgumentException();
            }
            if (key == null || key.Length == 0)
            {
                throw new ArgumentException();
            }

            System.Security.Cryptography.KeyedHashAlgorithm hash;
            switch (algorithm.ToUpperInvariant())
            {
            case "MD5":
            case "HMACMD5":
                hash = HMACMD5.Create();
                break;

            case "MD160":
            case "RIPEMD160":
            case "HMACRIPEMD160":
                hash = HMACRIPEMD160.Create();
                break;

            case "SHA":
            case "SHA1":
            case "HMACSHA":
            case "HMACSHA1":
                hash = HMACSHA1.Create();
                break;

            case "SHA256":
            case "HMACSHA256":
                hash = HMACSHA256.Create();
                break;

            case "SHA384":
            case "HMACSHA384":
                hash = HMACSHA384.Create();
                break;

            case "SHA512":
            case "HMACSHA512":
                hash = HMACSHA512.Create();
                break;

            default:
                throw new NotSupportedException();
            }
            hash.Key = key;
            byte[] result = hash.ComputeHash(input);
            hash.Clear();
            return(result);
        }
Exemplo n.º 11
0
        public static string HashMotDePass(string MotDePass)
        {
            string key = string.Join(":", new string[] { MotDePass, _CleeLongue });

            using (HMAC hmac = HMACSHA256.Create(_Algo))
            {
                hmac.Key = Encoding.UTF8.GetBytes(MotDePass);
                hmac.ComputeHash(Encoding.UTF8.GetBytes(key));
                return(Convert.ToBase64String(hmac.Hash));
            }
        }
Exemplo n.º 12
0
        public static string GetHashedPassword(string password)
        {
            string key = string.Join(":", new string[] { password, SaltKey });

            using (HMAC hmac = HMACSHA256.Create(VIKey))
            {
                hmac.Key = Encoding.UTF8.GetBytes(SaltKey);
                hmac.ComputeHash(Encoding.UTF8.GetBytes(key));
                return(Convert.ToBase64String(hmac.Hash));
            }
        }
        public string GenerateSignature(string unsignedToken, byte[] signingKey)
        {
            using (var algorithm = HMACSHA256.Create())
            {
                algorithm.Key = signingKey;
                var data = Encoding.UTF8.GetBytes(unsignedToken);

                var mac = algorithm.ComputeHash(data);
                return(Convert.ToBase64String(mac));
            }
        }
Exemplo n.º 14
0
        public static string GetHashedPassword(string password)
        {
            string key = string.Join(":", new string[] { password, "rz8LuOtFBXphj9WQfvFh" });

            using (HMAC hmac = HMACSHA256.Create("HmacSHA256"))
            {
                // Hash the key.
                hmac.Key = Encoding.UTF8.GetBytes("rz8LuOtFBXphj9WQfvFh");
                hmac.ComputeHash(Encoding.UTF8.GetBytes(key));
                return(Convert.ToBase64String(hmac.Hash));
            }
        }
Exemplo n.º 15
0
        private static string GetHashedPassword(string password)
        {
            string key = string.Join(":", new string[] { password, _salt });

            using (HMAC hmac = HMACSHA256.Create(_algo))
            {
                // Hash the key.
                hmac.Key = Encoding.UTF8.GetBytes(_salt);
                hmac.ComputeHash(Encoding.UTF8.GetBytes(key));
                return(Convert.ToBase64String(hmac.Hash));
            }
        }
Exemplo n.º 16
0
        private static byte[] GetHash([CanBeNull] string input, EHashType hash)
        {
            var inputBytes = Encoding.ASCII.GetBytes(input);

            switch (hash)
            {
            case EHashType.HMAC:
                return(HMAC.Create().ComputeHash(inputBytes));

#pragma warning disable RECS0030                                   // Suggests using the class declaring a static function when calling it
            case EHashType.HMACMD5:                                // DevSkim: ignore DS126858
                return(HMACMD5.Create().ComputeHash(inputBytes));  // DevSkim: ignore DS126858

            case EHashType.HMACSHA1:                               // DevSkim: ignore DS126858
                return(HMACSHA1.Create().ComputeHash(inputBytes)); // DevSkim: ignore DS126858

            case EHashType.HMACSHA256:
                return(HMACSHA256.Create().ComputeHash(inputBytes));

            case EHashType.HMACSHA384:
                return(HMACSHA384.Create().ComputeHash(inputBytes));

            case EHashType.HMACSHA512:
                return(HMACSHA512.Create().ComputeHash(inputBytes));

#pragma warning restore RECS0030                               // Suggests using the class declaring a static function when calling it

            case EHashType.MD5:                                // DevSkim: ignore DS126858
#pragma warning disable SG0006                                 // Weak hashing function
                return(MD5.Create().ComputeHash(inputBytes));  // DevSkim: ignore DS126858

#pragma warning restore SG0006                                 // Weak hashing function

            case EHashType.SHA1:                               // DevSkim: ignore DS126858
#pragma warning disable SG0006                                 // Weak hashing function
                return(SHA1.Create().ComputeHash(inputBytes)); // DevSkim: ignore DS126858

#pragma warning restore SG0006                                 // Weak hashing function

            case EHashType.SHA256:
                return(SHA256.Create().ComputeHash(inputBytes));

            case EHashType.SHA384:
                return(SHA384.Create().ComputeHash(inputBytes));

            case EHashType.SHA512:
                return(SHA512.Create().ComputeHash(inputBytes));

            default:
                return(inputBytes);
            }
        }
Exemplo n.º 17
0
        private byte[] GetHashedPassword(string password)
        {
            string key = string.Join(":", new { password, salt });

            using (HMAC hmac = HMACSHA256.Create(alg))
            {
                // Hash the key.
                hmac.Key = Encoding.UTF8.GetBytes(salt);
                hmac.ComputeHash(Encoding.UTF8.GetBytes(key));

                return(hmac.Hash);
            }
        }
Exemplo n.º 18
0
        public static string GenerateToken(string username, string password, string phoneNumber)
        {
            string text  = string.Join("#$#", new string[] { username, phoneNumber, DateTime.Now.AddMinutes(1.1234).ToLongDateString() });
            string token = "";

            using (HMAC hmac = HMACSHA256.Create(ALGORITHM))
            {
                hmac.Key = Encoding.UTF8.GetBytes(GetHashedPassword(password));
                hmac.ComputeHash(Encoding.UTF8.GetBytes(text));
                token = Convert.ToBase64String(hmac.Hash);
            }
            return(Convert.ToBase64String(Encoding.UTF8.GetBytes(token)));
        }
Exemplo n.º 19
0
 private async Task <byte[]> ComputeHashAsync(string path)
 {
     using (var fileStream = File.OpenRead(path))
     {
         using (var hasher = HMACSHA256.Create())
         {
             return(await Task.Run(() =>
             {
                 return hasher.ComputeHash(fileStream);
             }));
         }
     }
 }
Exemplo n.º 20
0
        private static byte[] GetHash(string Source, HashType hash)
        {
            byte[] inputBytes = Encoding.ASCII.GetBytes(Source);

            switch (hash)
            {
            case HashType.HMAC:
                return(HMAC.Create().ComputeHash(inputBytes));

            case HashType.HMACMD5:
                return(HMACMD5.Create().ComputeHash(inputBytes));

            case HashType.HMACSHA1:
                return(HMACSHA1.Create().ComputeHash(inputBytes));

            case HashType.HMACSHA256:
                return(HMACSHA256.Create().ComputeHash(inputBytes));

            case HashType.HMACSHA384:
                return(HMACSHA384.Create().ComputeHash(inputBytes));

            case HashType.HMACSHA512:
                return(HMACSHA512.Create().ComputeHash(inputBytes));

            /*
             * case HashType.MACTripleDES:
             * return MACTripleDES.Create().ComputeHash(inputBytes);
             */
            case HashType.MD5:
                return(MD5.Create().ComputeHash(inputBytes));

            /*
             * case HashType.RIPEMD160:
             * return RIPEMD160.Create().ComputeHash(inputBytes);
             */
            case HashType.SHA1:
                return(SHA1.Create().ComputeHash(inputBytes));

            case HashType.SHA256:
                return(SHA256.Create().ComputeHash(inputBytes));

            case HashType.SHA384:
                return(SHA384.Create().ComputeHash(inputBytes));

            case HashType.SHA512:
                return(SHA512.Create().ComputeHash(inputBytes));

            default:
                return(inputBytes);
            }
        }
Exemplo n.º 21
0
        /// <summary>
        /// Returns a collection of hash algorithms that can be used
        /// </summary>
        /// <returns></returns>
        public Dictionary <string, HashAlgorithm> GetHashAlgorithms()
        {
            Dictionary <string, HashAlgorithm> hashAlgorithms = new Dictionary <string, HashAlgorithm>();

            hashAlgorithms.Add("Sha-256", CreateSha256());
            hashAlgorithms.Add("Sha-512", CreateSha512());
            hashAlgorithms.Add("MD5", CreateMD5());
            hashAlgorithms.Add("Keyed Hash Algorithm", CreateKeyHashAlgorithm());
            hashAlgorithms.Add("Ripe MD 160", CreateRipeMdAlgorithm());
            hashAlgorithms.Add("Whirlpool", CreateWhirlpool());
            hashAlgorithms.Add("HMAC", HMACSHA256.Create());
            hashAlgorithms.Add("MACTripleDES", CreateMACTripleDES());
            return(hashAlgorithms);
        }
Exemplo n.º 22
0
        /// <summary>
        /// Returns a hashed password + salt, to be used in generating a token.
        /// </summary>
        /// <param name="password">string - user's password</param>
        /// <returns>string - hashed password</returns>
        public static string GetHashedPassword(string password)
        {
            string key = string.Join(":", new string[] { password, _salt });

            //用password和_salt产生key,其中_salt是绝对安全的,因为不进行任何传输
            using (HMAC hmac = HMACSHA256.Create(_alg))//新建一个hmac由_alg产生
            {
                // Hash the key.
                hmac.Key = Encoding.UTF8.GetBytes(_salt);
                hmac.ComputeHash(Encoding.UTF8.GetBytes(key));

                return(Convert.ToBase64String(hmac.Hash));
            }
        }
Exemplo n.º 23
0
        private Task <dynamic> MakePrivateCallAsync(Uri uri, object request)
        {
            var    nonce = Guid.NewGuid().ToString("N");
            string json  = JsonConvert.SerializeObject(request);
            string contentBase64String = Convert.ToBase64String(MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(json)));
            var    rawData             = String.Concat(_settings.ApiKey, "POST", uri.ToString(), nonce, contentBase64String);
            string signature           = HttpHelper.GetHash(HMACSHA256.Create(), _settings.Secret, rawData);

            SetHeaders(new Dictionary <string, string> {
                { "amx", $"{_settings.ApiKey}:{signature}:{nonce}" }
            });

            return(CallAsync <dynamic>(HttpMethod.Post, uri, new StringContent(json, Encoding.UTF8, "application/json")));
        }
Exemplo n.º 24
0
        private static byte[] GetHash(string input, EHashType hash)
        {
            var inputBytes = Encoding.ASCII.GetBytes(input);

            switch (hash)
            {
            case EHashType.HMAC:
                return(HMAC.Create().ComputeHash(inputBytes));

            case EHashType.HMACMD5:
                return(HMACMD5.Create().ComputeHash(inputBytes));

            case EHashType.HMACSHA1:
                return(HMACSHA1.Create().ComputeHash(inputBytes));

            case EHashType.HMACSHA256:
                return(HMACSHA256.Create().ComputeHash(inputBytes));

            case EHashType.HMACSHA384:
                return(HMACSHA384.Create().ComputeHash(inputBytes));

            case EHashType.HMACSHA512:
                return(HMACSHA512.Create().ComputeHash(inputBytes));

            case EHashType.MACTripleDES:
                return(MACTripleDES.Create().ComputeHash(inputBytes));

            case EHashType.MD5:
                return(MD5.Create().ComputeHash(inputBytes));

            case EHashType.RIPEMD160:
                return(RIPEMD160.Create().ComputeHash(inputBytes));

            case EHashType.SHA1:
                return(SHA1.Create().ComputeHash(inputBytes));

            case EHashType.SHA256:
                return(SHA256.Create().ComputeHash(inputBytes));

            case EHashType.SHA384:
                return(SHA384.Create().ComputeHash(inputBytes));

            case EHashType.SHA512:
                return(SHA512.Create().ComputeHash(inputBytes));

            default:
                return(inputBytes);
            }
        }
Exemplo n.º 25
0
        private const int _tokenExpiration = 10;                             // mins

        public static string GenerateToken(string username, string password, string ip, long ticks)
        {
            string hash      = string.Join(":", new string[] { username, ip, ticks.ToString() });
            string hashLeft  = "";
            string hashRight = "";

            using (HMAC hmac = HMACSHA256.Create(_algo))
            {
                hmac.Key = Encoding.UTF8.GetBytes(GetHashedPassword(password));
                hmac.ComputeHash(Encoding.UTF8.GetBytes(hash));
                hashLeft  = Convert.ToBase64String(hmac.Hash);
                hashRight = string.Join(":", new string[] { username, ticks.ToString() });
            }
            return(Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Join(":", hashLeft, hashRight))));
        }
Exemplo n.º 26
0
        public static string GenerateToken(string type, string userId, long ticks)
        {
            string hash      = string.Join(":", new string[] { type, "rz8LuOtFBXphj9WQfvFh" });
            string hashLeft  = "";
            string hashRight = "";

            using (HMAC hmac = HMACSHA256.Create("HmacSHA256"))
            {
                hmac.Key = Encoding.UTF8.GetBytes(GetHashedPassword("Test"));
                hmac.ComputeHash(Encoding.UTF8.GetBytes(hash));
                hashLeft  = string.Join(":", new String[] { hmac.Hash.ToString(), hash });
                hashRight = string.Join(":", new string[] { userId, ticks.ToString() });
            }
            return(Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Join(":", hashLeft, hashRight))));
        }
Exemplo n.º 27
0
        public static string GenererToken(string Login, string MotDePass, long ticks)
        {
            string hash       = string.Join(":", new string[] { Login, ticks.ToString() });
            string hashGauche = "";
            string hashDroit  = "";

            using (HMAC hmac = HMACSHA256.Create(_Algo))
            {
                hmac.Key = Encoding.UTF8.GetBytes(MotDePass);
                hmac.ComputeHash(Encoding.UTF8.GetBytes(hash));
                hashGauche = Convert.ToBase64String(hmac.Hash);
                hashDroit  = string.Join(":", new string[] { Login, ticks.ToString() });
            }
            return(Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Join(":", hashGauche, hashDroit))));
        }
Exemplo n.º 28
0
        private static byte[] GetHash(string input, EHashType hash)
        {
            byte[] inputBytes = Encoding.ASCII.GetBytes(input);

            switch (hash)
            {
            case EHashType.HMAC:
                return(HMAC.Create().ComputeHash(inputBytes));

            case EHashType.HMACMD5:
                return(HMACMD5.Create().ComputeHash(inputBytes));

            case EHashType.HMACSHA1:
                return(HMACSHA1.Create().ComputeHash(inputBytes));

            case EHashType.HMACSHA256:
                return(HMACSHA256.Create().ComputeHash(inputBytes));

            case EHashType.HMACSHA384:
                return(HMACSHA384.Create().ComputeHash(inputBytes));

            case EHashType.HMACSHA512:
                return(HMACSHA512.Create().ComputeHash(inputBytes));

#pragma warning disable CS0618 // Type or member is obsolete
            case EHashType.MD5:
#pragma warning restore CS0618 // Type or member is obsolete
                return(MD5.Create().ComputeHash(inputBytes));

#pragma warning disable CS0618 // Type or member is obsolete
            case EHashType.SHA1:
#pragma warning restore CS0618 // Type or member is obsolete
                return(SHA1.Create().ComputeHash(inputBytes));

            case EHashType.SHA256:
                return(SHA256.Create().ComputeHash(inputBytes));

            case EHashType.SHA384:
                return(SHA384.Create().ComputeHash(inputBytes));

            case EHashType.SHA512:
                return(SHA512.Create().ComputeHash(inputBytes));

            default:
                return(inputBytes);
            }
        }
Exemplo n.º 29
0
        public static string GetHashedPassword(string password, int maxPasswordength = -1)
        {
            string key          = string.Join(":|:", new string[] { password, SALT });
            string hashPassword = null;

            using (HMAC hmac = HMACSHA256.Create(ALGORITHM))
            {
                hmac.Key = Encoding.UTF8.GetBytes(ALGORITHM);
                hmac.ComputeHash(Encoding.UTF8.GetBytes(key));
                hashPassword = Convert.ToBase64String(hmac.Hash);
            }
            if (maxPasswordength > 0 && hashPassword.Length > maxPasswordength)
            {
                hashPassword = hashPassword.Substring(0, maxPasswordength);
            }
            return(hashPassword);
        }
        /// <summary>
        /// Method used to generate token. The token is generated based on the user's email,
        /// password and claim
        ///
        /// Algorithm found on the following website:
        /// http://www.primaryobjects.com/2015/05/08/token-based-authentication-for-web-service-apis-in-c-mvc-net/
        ///
        /// </summary>
        ///
        /// <param name="email"></param>
        /// <param name="password"></param>
        /// <param name="claim"></param>
        ///
        /// <returns>
        /// Token that will be assigned to the user
        /// </returns>
        public string GenerateToken(string email, string password, string claim)
        {
            // Concatenate email, (hashed) password, and claim in a string array.
            string hash      = string.Join(":", new string[] { email, password, claim });
            string hashLeft  = "";
            string hashRight = "";

            using (HMAC hmac = HMACSHA256.Create(_algorithm))
            {
                hmac.Key = Encoding.UTF8.GetBytes(password);
                hmac.ComputeHash(Encoding.UTF8.GetBytes(hash));
                hashLeft  = Convert.ToBase64String(hmac.Hash);
                hashRight = string.Join(":", new string[] { email, claim });
            }
            string token = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Join(":", hashLeft, hashRight)));

            return(token);
        }