internal static byte[] GenerateSteamParentalHash(byte[] password, byte[] salt, byte hashLength, ESteamParentalAlgorithm steamParentalAlgorithm)
        {
            if ((password == null) || (salt == null) || (hashLength == 0) || !Enum.IsDefined(typeof(ESteamParentalAlgorithm), steamParentalAlgorithm))
            {
                ASF.ArchiLogger.LogNullError(nameof(password) + " || " + nameof(salt) + " || " + nameof(hashLength) + " || " + nameof(steamParentalAlgorithm));

                return(null);
            }

            switch (steamParentalAlgorithm)
            {
            case ESteamParentalAlgorithm.Pbkdf2:
                using (HMACSHA1 hmacAlgorithm = new HMACSHA1(password)) {
                    return(Pbkdf2.ComputeDerivedKey(hmacAlgorithm, salt, SteamParentalPbkdf2Iterations, hashLength));
                }

            case ESteamParentalAlgorithm.SCrypt:
                return(SCrypt.ComputeDerivedKey(password, salt, SteamParentalSCryptIterations, SteamParentalSCryptBlocksCount, 1, null, hashLength));

            default:
                ASF.ArchiLogger.LogGenericError(string.Format(Strings.WarningUnknownValuePleaseReport, nameof(steamParentalAlgorithm), steamParentalAlgorithm));

                return(null);
            }
        }
Example #2
0
        public Player GetPlayerByLogin(string name, string password)
        {
            var connection = _databaseService.GetConnection();
            var data       = connection.QueryFirstOrDefault <UserAuthentication>(
                "SELECT id, hash FROM players WHERE name = @name",
                new {
                name
            });

            connection.Close();

            if (data == null)
            {
                return(null);
            }

            var playerId   = data.Id;
            var playerHash = data.Hash;

            if (!Pbkdf2.ValidatePassword(password, playerHash))
            {
                return(null);
            }

            var iterations = Pbkdf2.GetHashIterations(playerHash);

            if (iterations != Pbkdf2.Pbkdf2Iterations)
            {
                var hash = Pbkdf2.HashPassword(password);
                UpdateHash(playerId, hash);
            }

            return(GetPlayerById(playerId));
        }
        private static byte[] DeriveKey(byte[] key, byte[] salt, int outputSize, int iterations)
        {
            var output = new byte[outputSize];

            Pbkdf2.ComputeKey(key, salt, iterations, Pbkdf2.CallbackFromHmac <HMACSHA256>(), outputSize, output);
            return(output);
        }
        public static void Main(string[] args)
        {
            var pbkdf2 = new Pbkdf2();

            Console.WriteLine("Welcome! First you need to register...");
            Console.Write("  Username: "******"  Password: "******"\nThank you for registering, you can now login below...");
            Console.Write("  Username: "******"  Password: "******"\nLogin was successful!");
            }
            else
            {
                Console.WriteLine("\nLogin failed");
            }

            Console.WriteLine("\nPress any key to continue...");
            Console.Read();
        }
Example #5
0
        public void ComparisonTest(string password, string salt, int iterations, int bytes)
        {
            var _pass = System.Text.Encoding.UTF8.GetBytes(password);
            var _salt = System.Text.Encoding.UTF8.GetBytes(salt);
            var algo1 = new Rfc2898DeriveBytes(_pass, _salt, iterations);
            var algo2 = new Pbkdf2(new HMACSHA1(_pass), _salt, iterations);

            var h1 = algo1.GetBytes(bytes).ToHex();
            var h2 = algo2.GetBytes(bytes).ToHex();

            Assert.AreEqual(h1, h2);

            var h3 = algo1.GetBytes(bytes + 7).ToHex();
            var h4 = algo2.GetBytes(bytes + 7).ToHex();

            Assert.AreEqual(h3, h4);

            var h5 = algo1.GetBytes(1).ToHex();
            var h6 = algo2.GetBytes(1).ToHex();

            Assert.AreEqual(h5, h6);

            h5 = algo1.GetBytes(1).ToHex();
            h6 = algo2.GetBytes(1).ToHex();
            Assert.AreEqual(h5, h6);

            h5 = algo1.GetBytes(1).ToHex();
            h6 = algo2.GetBytes(1).ToHex();
            Assert.AreEqual(h5, h6);
        }
Example #6
0
        public void TestVector_PBKDF2_HMAC_SHA_256()
        {
            var p     = System.Text.Encoding.ASCII.GetBytes("passwd");
            var s     = System.Text.Encoding.ASCII.GetBytes("salt");
            var pbkdf = new Pbkdf2(new HMACSHA256(p), s, 1);

            var dk       = pbkdf.GetBytes(64);
            var expected = Encoders.Hex.GetBytes(@"
				55 ac 04 6e 56 e3 08 9f ec 16 91 c2 25 44 b6 05
				f9 41 85 21 6d de 04 65 e6 8b 9d 57 c2 0d ac bc
				49 ca 9c cc f1 79 b6 45 99 16 64 b3 9d 77 ef 31
				7c 71 b8 45 b1 e3 0b d5 09 11 20 41 d3 a1 97 83"                .Clean());

            CollectionAssert.AreEqual(expected, dk);

            p     = System.Text.Encoding.ASCII.GetBytes("Password");
            s     = System.Text.Encoding.ASCII.GetBytes("NaCl");
            pbkdf = new Pbkdf2(new HMACSHA256(p), s, 80000);

            dk       = pbkdf.GetBytes(64);
            expected = Encoders.Hex.GetBytes(@"
				4d dc d8 f6 0b 98 be 21 83 0c ee 5e f2 27 01 f9
				64 1a 44 18 d0 4c 04 14 ae ff 08 87 6b 34 ab 56
				a1 d4 25 a1 22 58 33 54 9a db 84 1b 51 c9 b3 17
				6a 27 2b de bb a1 d0 78 47 8f 62 b3 97 f3 3c 8d"                .Clean());

            CollectionAssert.AreEqual(expected, dk);
        }
Example #7
0
        public void Test_Pbkdf2()
        {
            byte[] password = new byte[256];
            byte[] salt     = new byte[256];

            _random.NextBytes(password);
            _random.NextBytes(salt);

            using (var hmac = new System.Security.Cryptography.HMACSHA1())
            {
                Pbkdf2 pbkdf2 = new Pbkdf2(hmac, password, salt, 1024);
                System.Security.Cryptography.Rfc2898DeriveBytes rfc2898DeriveBytes = new System.Security.Cryptography.Rfc2898DeriveBytes(password, salt, 1024);

                Assert.IsTrue(CollectionUtilities.Equals(pbkdf2.GetBytes(1024), rfc2898DeriveBytes.GetBytes(1024)), "Pbkdf2 #1");
            }

            //_random.NextBytes(password);
            //_random.NextBytes(salt);

            //using (var hmac = new System.Security.Cryptography.HMACSHA256())
            //{
            //    CryptoConfig.AddAlgorithm(typeof(SHA256Cng),
            //        "SHA256",
            //        "SHA256Cng",
            //        "System.Security.Cryptography.SHA256",
            //        "System.Security.Cryptography.SHA256Cng");

            //    hmac.HashName = "System.Security.Cryptography.SHA256";

            //    Pbkdf2 pbkdf2 = new Pbkdf2(hmac, password, salt, 1024);
            //    var h = pbkdf2.GetBytes(10);
            //}
        }
Example #8
0
        public void Generate_returns_correct_result()
        {
            foreach (var i in TestData)
            {
                var expected = i.Expected.Decode64();

                Assert.That(Pbkdf2.Generate(i.Password,
                                            i.Salt,
                                            i.IterationCount,
                                            expected.Length),
                            Is.EqualTo(expected));

                Assert.That(Pbkdf2.Generate(i.Password.ToBytes(),
                                            i.Salt,
                                            i.IterationCount,
                                            expected.Length),
                            Is.EqualTo(expected));

                Assert.That(Pbkdf2.Generate(i.Password,
                                            i.Salt.ToBytes(),
                                            i.IterationCount,
                                            expected.Length),
                            Is.EqualTo(expected));

                Assert.That(Pbkdf2.Generate(i.Password.ToBytes(),
                                            i.Salt.ToBytes(),
                                            i.IterationCount,
                                            expected.Length),
                            Is.EqualTo(expected));
            }
        }
Example #9
0
 public static Pbkdf2 GetStream(byte[] key, byte[] salt,
     int cost, int blockSize, int parallel, int? maxThreads)
 {
     byte[] B = GetEffectivePbkdf2Salt(key, salt, cost, blockSize, parallel, maxThreads);
     Pbkdf2 kdf = new Pbkdf2(key, B, 1, _hmacCallback, hLen);
     Clear(B); return kdf;
 }
Example #10
0
        public static byte[] DeriveKeyHash(string username, string password, int iterationCount)
        {
            var key = DeriveKey(username, password, iterationCount);

            return(iterationCount == 1
                ? Crypto.Sha256(key.ToHex() + password)
                : Pbkdf2.GenerateSha256(key, password.ToBytes(), 1, 32));
        }
Example #11
0
 byte[] PBKDF2(byte[] password, byte[] salt, int iterations, int outputBytes)
 {
     using (var hmac = new HMACSHA256()) {
         var df    = new Pbkdf2(hmac, password, salt, iterations);
         var bytes = df.GetBytes(outputBytes);
         return(bytes);
     }
 }
Example #12
0
        public void Compare_ShouldReturnTrue(string passwordHash1, string passwordHash2)
        {
            var pbkdf2 = new Pbkdf2();

            var result = pbkdf2.Compare(passwordHash1, passwordHash2);

            Assert.IsTrue(result);
        }
Example #13
0
        public void Test_Pbkdf2()
        {
            string hash   = "x7JH1xlG/PgzXTplNhXhvw==";
            Pbkdf2 pbkdf2 = new Pbkdf2(100000, 16);

            Assert.True(pbkdf2.Validate("password@12345", hash));
            Assert.False(pbkdf2.Validate("wasd", hash));
        }
        public void Compute_SaltTooShort()
        {
            var pbkdf2 = new Pbkdf2 {
                PlainText = "TestPlainText", SaltSize = 7
            };
            var hash = pbkdf2.Compute();

            Assert.Fail();
        }
        public void Compute_NotEnoughIterations()
        {
            var pbkdf2 = new Pbkdf2 {
                PlainText = "TestPlainText", HashIterations = 9999
            };
            var hash = pbkdf2.Compute();

            Assert.Fail();
        }
        public void Compute_HashSizeToBig()
        {
            var pbkdf2 = new Pbkdf2 {
                PlainText = "TestPlainText", HashSize = 65
            };
            var hash = pbkdf2.Compute();

            Assert.Fail();
        }
Example #17
0
 internal static byte[] DeriveMasterPasswordAuthKey(string userId,
                                                    byte[] encryptionKey,
                                                    DatabaseInfo databaseInfo)
 {
     return(Pbkdf2.GenerateSha256(password: encryptionKey,
                                  salt: Encoding.Unicode.GetBytes(userId),
                                  iterationCount: 1500,
                                  byteCount: 64));
 }
Example #18
0
        public void Compute_ExtractSaltException()
        {
            var pbkdf2 = new Pbkdf2 {
                PlainText = "Test", Salt = "100A00.Random"
            };

            pbkdf2.Compute();

            Assert.Fail();
        }
Example #19
0
        public void Compute_PlainTextIsEmpty()
        {
            var pbkdf2 = new Pbkdf2 {
                Salt = "100000.Random"
            };

            pbkdf2.Compute();

            Assert.Fail();
        }
        public static byte[] DeriveKeyWithConfig(byte[] key, byte[] salt, int outputSize, byte[] config)
        {
            int iterations;

            PBKDF2ConfigurationUtility.Read(config, out iterations);
            var output = new byte[outputSize];

            Pbkdf2.ComputeKey(key, salt, iterations, Pbkdf2.CallbackFromHmac <HMACSHA256>(), outputSize, output);
            return(output);
        }
        public void GenerateSalt_SaltSizeIsLessThanOne()
        {
            var pbkdf2 = new Pbkdf2 {
                PlainText = "Test", SaltSize = 0
            };

            pbkdf2.GenerateSalt();

            Assert.Fail();
        }
Example #22
0
        public string HashPassword(string password)
        {
            byte[] salt = new byte[32];
            Random r    = new Random();

            r.NextBytes(salt);

            Pbkdf2 pbkdf2 = new Pbkdf2(new HMACSHA256(), System.Text.Encoding.UTF8.GetBytes(password), salt);

            return(Convert.ToBase64String(pbkdf2.GetBytes(32)) + ":" + Convert.ToBase64String(salt));
        }
Example #23
0
 public void DoPbkTest(string password, string salt, int iterations, int dkLen, string expected)
 {
     using (var hmac = new HMACSHA256())
     {
         var     mine     = new Pbkdf2(hmac, System.Text.Encoding.UTF8.GetBytes(password), System.Text.Encoding.UTF8.GetBytes(salt), iterations);
         sbyte[] result   = mine.GetBytes(dkLen);
         byte[]  usResult = (byte[])(Array)result;
         String  hex      = BitConverter.ToString(usResult);
         Assert.AreEqual(hex, expected);
     }
 }
Example #24
0
        //
        // Internal
        //

        internal static byte[] HashPassword(string password, AuthInfo authInfo)
        {
            var passwordBytes = password.ToBytes();

            if (authInfo.IsMd5)
            {
                passwordBytes = Crypto.Md5(passwordBytes);
            }

            return(Pbkdf2.GenerateSha256(passwordBytes, authInfo.Salt, authInfo.IterationCount, 32));
        }
        /// <summary>
        /// Generate authentication informations and store them in a serializable object to allow persistence
        /// </summary>
        /// <param name="email">email</param>
        /// <param name="password">password</param>
        /// <returns><see cref="AuthInfos" /> object containing encrypted data</returns>
        /// <exception cref="ArgumentNullException">email or password is null</exception>
        public AuthInfos GenerateAuthInfos(string email, string password)
        {
            if (string.IsNullOrEmpty(email))
            {
                throw new ArgumentNullException("email");
            }

            if (string.IsNullOrEmpty(password))
            {
                throw new ArgumentNullException("password");
            }

            // Prelogin to retrieve account version
            PreLoginRequest  preLoginRequest  = new PreLoginRequest(email);
            PreLoginResponse preLoginResponse = this.Request <PreLoginResponse>(preLoginRequest);

            if (preLoginResponse.Version == 2 && !string.IsNullOrEmpty(preLoginResponse.Salt))
            {
                // Mega uses a new way to hash password based on a salt sent by Mega during prelogin
                var       saltBytes     = preLoginResponse.Salt.FromBase64();
                var       passwordBytes = password.ToBytesPassword();
                const int Iterations    = 100000;

                var derivedKeyBytes = new byte[32];
                using (var hmac = new HMACSHA512())
                {
                    var pbkdf2 = new Pbkdf2(hmac, passwordBytes, saltBytes, Iterations);
                    derivedKeyBytes = pbkdf2.GetBytes(derivedKeyBytes.Length);
                }

                // Derived key contains master key (0-16) and password hash (16-32)
                return(new AuthInfos(
                           email,
                           derivedKeyBytes.Skip(16).ToArray().ToBase64(),
                           derivedKeyBytes.Take(16).ToArray()));
            }
            else if (preLoginResponse.Version == 1)
            {
                // Retrieve password as UTF8 byte array
                byte[] passwordBytes = password.ToBytesPassword();

                // Encrypt password to use password as key for the hash
                byte[] passwordAesKey = PrepareKey(passwordBytes);

                // Hash email and password to decrypt master key on Mega servers
                string hash = GenerateHash(email.ToLowerInvariant(), passwordAesKey);

                return(new AuthInfos(email, hash, passwordAesKey));
            }
            else
            {
                throw new NotSupportedException("Version of account not supported");
            }
        }
Example #26
0
        public byte[] DeriveSeed(string passphrase = null)
        {
            passphrase = passphrase ?? "";
            byte[] salt  = Concat(Encoding.UTF8.GetBytes("mnemonic"), Normalize(passphrase));
            byte[] bytes = Normalize(this._Mnemonic);

            var mac = new NBitcoin.BouncyCastle.Crypto.Macs.HMac(new NBitcoin.BouncyCastle.Crypto.Digests.Sha512Digest());

            mac.Init(new KeyParameter(bytes));
            return(Pbkdf2.ComputeDerivedKey(mac, salt, 2048, 64));
        }
Example #27
0
        public void VerifyHashedPasswordV2_Invalid_Hashed_Passwords_Should_Return_False(string password, string hash)
        {
            //arrange
            byte[] hashtBytes = Convert.FromBase64String(hash);

            //act
            bool isValid = Pbkdf2.VerifyHashedPasswordV2(hashtBytes, password);

            //assert
            Assert.False(isValid);
        }
Example #28
0
        public static byte[] DeriveKey(string username, string password, int iterationCount)
        {
            if (iterationCount <= 0)
            {
                throw new InternalErrorException("Iteration count should be positive");
            }

            return(iterationCount == 1
                ? Crypto.Sha256(username + password)
                : Pbkdf2.GenerateSha256(password.ToBytes(), username.ToBytes(), iterationCount, 32));
        }
Example #29
0
        public void Sha256_1()
        {
            using var hmac = new HMACSHA256();
            var P     = "password";
            var S     = "salt";
            var c     = 1;
            var dkLen = 32;
            var DK    = "12 0f b6 cf fc f8 b3 2c 43 e7 22 52 56 c4 f8 37 a8 65 48 c9 2c cc 35 48 08 05 98 7c b7 0b e1 7b";
            var df    = new Pbkdf2(hmac, P, S, c);

            Assert.Equal(DK, BitConverter.ToString(df.GetBytes(dkLen)).Replace('-', ' ').ToLowerInvariant());
        }
Example #30
0
        public void Sha1_1()    // RFC 6070
        {
            using var hmac = new HMACSHA1();
            var P     = "password";
            var S     = "salt";
            var c     = 1;
            var dkLen = 20;
            var DK    = "0c 60 c8 0f 96 1f 0e 71 f3 a9 b5 24 af 60 12 06 2f e0 37 a6";
            var df    = new Pbkdf2(hmac, P, S, c);

            Assert.Equal(DK, BitConverter.ToString(df.GetBytes(dkLen)).Replace('-', ' ').ToLowerInvariant());
        }
Example #31
0
        public void Sha1_6()    // RFC 6070
        {
            using var hmac = new HMACSHA1();
            var P     = "pass\0word";
            var S     = "sa\0lt";
            var c     = 4096;
            var dkLen = 16;
            var DK    = "56 fa 6a a7 55 48 09 9d cc 37 d7 f0 34 25 e0 c3";
            var df    = new Pbkdf2(hmac, P, S, c);

            Assert.Equal(DK, BitConverter.ToString(df.GetBytes(dkLen)).Replace('-', ' ').ToLowerInvariant());
        }