Пример #1
0
        public void Hashers_HMAC_SHA512Hasher()
        {
            byte[] data = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            byte[] key;
            byte[] digest;

            key    = new byte[] { 0, 1, 2, 3, 4, 5 };
            digest = SHA512Hasher.Compute(key, data);
            Assert.AreEqual(SHA512Hasher.DigestSize, digest.Length);

            key = new byte[128];
            for (int i = 0; i < key.Length; i++)
            {
                key[i] = (byte)i;
            }

            digest = SHA512Hasher.Compute(key, data);
            Assert.AreEqual(SHA512Hasher.DigestSize, digest.Length);

            // $todo(jeff.lill):
            //
            // At some point I'd like to verify this
            // against a hash produced by another
            // codebase.
        }
Пример #2
0
        private static Hasher CreateHasher(int crypto)
        {
            Hasher hasher = null;

            switch (crypto)
            {
            case (int)HashName.MD5:
                hasher = new MD5Hasher();
                break;

            case (int)HashName.SHA1:
                hasher = new SHA1Hasher();
                break;

            case (int)HashName.SHA256:
                hasher = new SHA256Hasher();
                break;

            case (int)HashName.SHA384:
                hasher = new SHA384Hasher();
                break;

            case (int)HashName.SHA512:
                hasher = new SHA512Hasher();
                break;
            }
            return(hasher);
        }
 public ActionResult EditCredentials(EditCredentialsDTO request)
 {
     if (ModelState.IsValid)
     {
         if (request.CurrentPassword != request.NewPassword)
         {
             if (BinaryComparer.AreEqual(Account.Password, SHA512Hasher.Hash(request.CurrentPassword)))
             {
                 PartnerBLL partnerBLL = new PartnerBLL(WebApp.Connector);
                 Uri        requestUrl = Request.Url;
                 string     baseUrl    = new UriBuilder(requestUrl.Scheme, requestUrl.Host, requestUrl.Port).ToString();
                 partnerBLL.ChangePasswordEmailSubject  = LocalizationProvider["ChangePasswordEmailSubject"];
                 partnerBLL.ChangePasswordEmailTemplate = LocalizationProvider["ChangePasswordEmailTemplate"];
                 partnerBLL.ChangePassword(Account, request.NewPassword, baseUrl);
                 TempData["Result"] = "PasswordHasBeenChanged";
                 return(RedirectToAction("MyProfile"));
             }
             else
             {
                 AddError("CurrentPassword", "CurrentPasswordDoesntMatch");
                 return(View());
             }
         }
         else
         {
             AddError("NewPassword", "NewAndCurrentPasswordAreTheSame");
             return(View());
         }
     }
     else
     {
         return(BadRequestWithErrors());
     }
 }
Пример #4
0
 private static byte[] Generate(string value)
 {
     using (RandomNumberGenerator randomNumberGenerator = new RNGCryptoServiceProvider())
     {
         byte[] data = new byte[256];
         randomNumberGenerator.GetBytes(data);
         return(SHA512Hasher.Hash($"{value}|TimeStamp={DateTime.UtcNow.Ticks}|Random={FormatHelper.FromArrayToHexString(data)}"));
     }
 }
Пример #5
0
        public void Hashers_SHA512()
        {
            EnhancedMemoryStream ms;

            byte[] data;
            byte[] digest1, digest2;

            digest1 = SHA512Hasher.Compute(new byte[] { 0, 1, 2, 3 }, 0, 4);
            Assert.AreEqual(64, digest1.Length);
            Assert.AreEqual(64, SHA512Hasher.DigestSize);

            digest2 = SHA512Hasher.Compute(new byte[] { 1, 1, 2, 3 }, 0, 4);
            CollectionAssert.AreNotEqual(digest1, digest2);

            digest1 = SHA512Hasher.Compute(new byte[0]);
            Assert.AreEqual(64, digest1.Length);
            Assert.AreEqual(64, SHA512Hasher.DigestSize);

            digest1 = SHA512Hasher.Compute(new byte[] { 0, 1, 2, 3 });
            ms      = new EnhancedMemoryStream();

            ms.Seek(0, SeekOrigin.Begin);
            ms.Write(new byte[] { 0, 1, 2, 3 }, 0, 4);
            ms.Seek(0, SeekOrigin.Begin);
            digest2 = SHA512Hasher.Compute(ms, 4);
            CollectionAssert.AreEqual(digest1, digest2);
            Assert.AreEqual(64, digest2.Length);
            Assert.AreEqual(0, ms.Position);

            data = new byte[2048];
            for (int i = 0; i < data.Length; i++)
            {
                data[i] = (byte)i;
            }

            digest1 = SHA512Hasher.Compute(data);

            ms.Seek(0, SeekOrigin.Begin);
            ms.Write(data, 0, data.Length);
            ms.Seek(0, SeekOrigin.Begin);

            digest2 = SHA512Hasher.Compute(ms, data.Length);
            CollectionAssert.AreEqual(digest1, digest2);
            Assert.AreEqual(64, digest2.Length);
            Assert.AreEqual(0, ms.Position);

            digest1 = SHA512Hasher.Compute("hello");
            digest2 = SHA512Hasher.Compute("world");
            CollectionAssert.AreNotEqual(digest1, digest2);
            CollectionAssert.AreEqual(digest1, SHA512Hasher.Compute("hello"));
        }
Пример #6
0
        public ChangePasswordResult ChangePassword(PartnerDTO partner, string password, string baseUrl)
        {
            Repository.Update(partner.Id, new Dictionary <string, object>()
            {
                { "Password", SHA512Hasher.Hash(password) }
            });
            string      fullName = partner.FullName;
            MailAddress to       = new MailAddress(partner.EmailAddress, fullName);

            if (baseUrl.LastIndexOf('/') == baseUrl.Length - 1)
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            string logoUrl = new UriBuilder(baseUrl)
            {
                Path = "/png/Logo_361x86.png"
            }.ToString();
            string body = string.Format(ChangePasswordEmailTemplate, logoUrl, fullName);

            EmailSender.Send(to, ChangePasswordEmailSubject, body);
            return(ChangePasswordResult.OK);
        }
Пример #7
0
        public void Initialize()
        {
            Helper.InitializeApp(Assembly.GetExecutingAssembly());

            this.ADSettings   = new ADTestSettings();
            this.DB           = SqlTestDatabase.Create();
            this.AuthFilePath = Path.GetTempFileName();

            //-------------------------------------------------------------
            // Initialize file authentication

            Helper.WriteToFile(this.AuthFilePath, @"

file.com;file1;file-password1
file.com;file2;file-password2
");
            this.Accounts.Add(new AuthTestAccount(AuthTestExtensionType.File, "file.com", "file1", "file-password1"));
            this.Accounts.Add(new AuthTestAccount(AuthTestExtensionType.File, "file.com", "file2", "file-password2"));

            //-------------------------------------------------------------
            // Initialize RADIUS authentication

            RadiusServerSettings radiusSettings = new RadiusServerSettings();

            radiusSettings.NetworkBinding = NetworkBinding.Parse("ANY:52111");
            radiusSettings.Devices.Add(new RadiusNasInfo(IPAddress.Loopback, this.RadiusSecret));
            radiusSettings.Devices.Add(new RadiusNasInfo(NetHelper.GetActiveAdapter(), this.RadiusSecret));

            this.RadiusServer = new RadiusServer();
            this.RadiusServer.Start(radiusSettings);
            this.RadiusServer.LoadAccountsFromString(@"

radius.com;radius1;radius-password1
radius.com;radius2;radius-password2
");
            this.Accounts.Add(new AuthTestAccount(AuthTestExtensionType.Radius, "radius.com", "radius1", "radius-password1"));
            this.Accounts.Add(new AuthTestAccount(AuthTestExtensionType.Radius, "radius.com", "radius2", "radius-password2"));

            //-------------------------------------------------------------
            // Initialize config authentication

            Config.SetConfig(@"

Accounts[0] = config.com;config1;config-password1
Accounts[1] = config.com;config2;config-password2
");
            this.Accounts.Add(new AuthTestAccount(AuthTestExtensionType.Config, "config.com", "config1", "config-password1"));
            this.Accounts.Add(new AuthTestAccount(AuthTestExtensionType.Config, "config.com", "config2", "config-password2"));

#if TEST_AD
            //-------------------------------------------------------------
            // Initialize active directory authentication

#if !TEST_AD_LDAP
            if (ADSettings.NasSecret != string.Empty)   // Disable the test if the NAS secret is blank
#endif
            this.Accounts.Add(new AuthTestAccount(AuthTestExtensionType.Ldap, ADSettings.Domain, ADSettings.Account, ADSettings.Password));
#endif

            //-------------------------------------------------------------
            // Initalize ODBC authentication

            SqlConnection   sqlCon = null;
            SqlScriptRunner scriptRunner;
            MacroProcessor  processor;
            string          initScript =
                @"
create table Accounts (

Realm           varchar(64),
Account         varchar(64),
Password        varchar(64),
MD5             varbinary(128),
SHA1            varbinary(128),
SHA256          varbinary(128),
SHA512          varbinary(128)
)
go

insert into Accounts(Realm,Account,Password,MD5,SHA1,SHA256,SHA512)
values ('odbc.com','odbc1','odbc-password1',$(md5-1),$(sha1-1),$(sha256-1),$(sha512-1))

insert into Accounts(Realm,Account,Password,MD5,SHA1,SHA256,SHA512)
values ('odbc.com','odbc2','odbc-password2',$(md5-2),$(sha1-2),$(sha256-2),$(sha512-2))

go
";
            try
            {
                processor = new MacroProcessor();
                processor.Add("md5-1", SqlHelper.Literal(MD5Hasher.Compute("odbc-password1")));
                processor.Add("sha1-1", SqlHelper.Literal(SHA1Hasher.Compute("odbc-password1")));
                processor.Add("sha256-1", SqlHelper.Literal(SHA256Hasher.Compute("odbc-password1")));
                processor.Add("sha512-1", SqlHelper.Literal(SHA512Hasher.Compute("odbc-password1")));

                processor.Add("md5-2", SqlHelper.Literal(MD5Hasher.Compute("odbc-password2")));
                processor.Add("sha1-2", SqlHelper.Literal(SHA1Hasher.Compute("odbc-password2")));
                processor.Add("sha256-2", SqlHelper.Literal(SHA256Hasher.Compute("odbc-password2")));
                processor.Add("sha512-2", SqlHelper.Literal(SHA512Hasher.Compute("odbc-password2")));

                initScript = processor.Expand(initScript);

                sqlCon       = DB.OpenConnection();
                scriptRunner = new SqlScriptRunner(initScript);
                scriptRunner.Run(sqlCon);

                this.Accounts.Add(new AuthTestAccount(AuthTestExtensionType.Odbc, "odbc.com", "odbc1", "odbc-password1"));
                this.Accounts.Add(new AuthTestAccount(AuthTestExtensionType.Odbc, "odbc.com", "odbc2", "odbc-password2"));
            }
            finally
            {
                if (sqlCon != null)
                {
                    sqlCon.Close();
                }
            }
        }
Пример #8
0
        public LoginResult Login(PartnerCredentialDTO credential, IPAddress ipAddress, bool keepOpened, out PartnerSessionDTO session)
        {
            Connector.IsTransaction = true;
            PartnerBLL partnerBLL = new PartnerBLL(Connector);
            PartnerDTO partner    = partnerBLL.ReadByUsername(credential.Username);

            if (partner != null)
            {
                if (!partner.IsLocked)
                {
                    byte[] credentialPassword = SHA512Hasher.Hash(credential.Password);
                    if (BinaryComparer.AreEqual(credentialPassword, partner.Password))
                    {
                        if (partner.HasEmailAddressBeenVerified)
                        {
                            DateTime loggedAt = DateTime.UtcNow;
                            session = new PartnerSessionDTO()
                            {
                                Partner   = partner,
                                IPAddress = ipAddress,
                                LoggedAt  = loggedAt
                            };
                            if (!keepOpened)
                            {
                                session.ExpiresOn = loggedAt.AddMinutes(16);
                            }
                            Create(session);
                            Connector.CommitTransaction();
                            return(LoginResult.OK);
                        }
                        else
                        {
                            Connector.RollbackTransaction();
                            session = null;
                            return(LoginResult.EmailAddressHasNotBeenVerified);
                        }
                    }
                    else
                    {
                        PartnerLoginAttemptBLL loginAttemptBLL = new PartnerLoginAttemptBLL(Connector);
                        PartnerLoginAttemptDTO loginAttempt    = new PartnerLoginAttemptDTO()
                        {
                            Partner   = partner,
                            IPAddress = ipAddress
                        };
                        loginAttemptBLL.Create(loginAttempt);
                        Guid partnerId = partner.Id;
                        PartnerSessionDTO             lastSession   = ReadLastByPartner(partnerId);
                        List <PartnerLoginAttemptDTO> loginAttempts = loginAttemptBLL.ReadByPartnerAndTimeStampAsDate(partnerId, lastSession?.LoggedAt ?? DateTime.UtcNow.Date).ToList();
                        if (loginAttempts.Count >= 3)
                        {
                            partnerBLL.Update(partnerId, new Dictionary <string, object>()
                            {
                                { "IsLocked", true }
                            });
                        }
                        Connector.CommitTransaction();
                        session = null;
                        return(LoginResult.PasswordDoesntMatch);
                    }
                }
                else
                {
                    Connector.RollbackTransaction();
                    session = null;
                    return(LoginResult.AccountIsLocked);
                }
            }
            else
            {
                Connector.RollbackTransaction();
                session = null;
                return(LoginResult.AccountDoesntExist);
            }
        }
Пример #9
0
        private void ProcessRequest(Options commandLineOptions)
        {
            StreamHasher fileHashMaker;

            switch (commandLineOptions.HashAgorithm.ToUpper())
            {
            case "MD160":
                fileHashMaker = new MD160Hasher();
                break;

            case "SHA1":
                fileHashMaker = new SHA1Hasher();
                break;

            case "SHA256":
                fileHashMaker = new SHA256Hasher();
                break;

            case "SHA384":
                fileHashMaker = new SHA384Hasher();
                break;

            case "SHA512":
                fileHashMaker = new SHA512Hasher();
                break;

            case "MD5":
            default:
                fileHashMaker = new MD5Hasher();
                break;
            }

            fileHashMaker.HashBlockProcessed += fileHashMaker_HashBlockProcessed;

            List <String[]> inputFiles = new List <String[]>();

            if (commandLineOptions.Concatenate)
            {
                // Files will be treated as a single stream -
                // copy all filenames into a string array,
                // then add the array to the List
                String[] files = new String[commandLineOptions.Items.Count];
                for (int loop = 0; loop < commandLineOptions.Items.Count; loop++)
                {
                    files[loop] = commandLineOptions.Items[loop];
                }
                inputFiles.Add(files);
            }
            else
            {
                // Each file treated as a separate entity -
                // copy each filename into a separate string array,
                // then add each array to the List
                foreach (String fileToProcess in commandLineOptions.Items)
                {
                    String[] file = new String[] { fileToProcess };
                    inputFiles.Add(file);
                }
            }
            foreach (String[] fileEntry in inputFiles)
            {
                byte[] fileHash = fileHashMaker.ComputeFileHash(fileEntry, (int)commandLineOptions.BlockSize);
                Console.WriteLine(commandLineOptions.HashAgorithm.ToUpper() + ": " + BitConverter.ToString(fileHash));

                if (!string.IsNullOrWhiteSpace(commandLineOptions.AppendToHashFile))
                {
                    var settings = HashFile.OpenFile(commandLineOptions.AppendToHashFile);
                    settings.Add(fileEntry[0], BitConverter.ToString(fileHash).Replace("-", string.Empty), commandLineOptions.HashAgorithm.ToUpper());
                    settings.Save();
                }
            }
        }
Пример #10
0
 public void Join(PartnerCredentialDTO credential)
 {
     Username = credential.Username;
     Password = SHA512Hasher.Hash(credential.Password);
 }
Пример #11
0
        /// <summary>
        /// Authenticates the account credentials against the authentication extension.
        /// </summary>
        /// <param name="realm">The authentication realm.</param>
        /// <param name="account">The account ID.</param>
        /// <param name="password">The password.</param>
        /// <returns>A <see cref="AuthenticationResult" /> instance with the result of the operation.</returns>
        /// <remarks>
        /// <para>
        /// The <see cref="AuthenticationResult.Status" /> property indicates the disposition
        /// of the authentication operation.  Extensions will return <see cref="AuthenticationStatus.Authenticated" />
        /// if the operation was successful.  Authentication failures due to the
        /// sumbission of invalid credentials will be indicated by returning one of
        /// the error codes.  Extensions may return specific error codes such as
        /// <see cref="AuthenticationStatus.BadPassword" /> and <see cref="AuthenticationStatus.BadAccount" />
        /// or the generic error code <see cref="AuthenticationStatus.AccessDenied" />.
        /// </para>
        /// <para>
        /// The <see cref="AuthenticationResult.MaxCacheTime" /> returns as the maximum time the
        /// results of the authentication operation should be cached.
        /// </para>
        /// </remarks>
        /// <exception cref="AuthenticationException">Thrown for authentication related exception.</exception>
        public AuthenticationResult Authenticate(string realm, string account, string password)
        {
            OdbcConnection dbCon;
            OdbcCommand    cmd;
            OdbcDataReader reader = null;
            MacroProcessor processor;
            string         _conString;
            string         query;
            int            authCode;

            using (TimedLock.Lock(this))
            {
                if (!IsOpen)
                {
                    throw new AuthenticationException("Authentication extension is closed.");
                }

                cAuthentications++;
                _conString = conString;

                // Substitute the credentials into the query template.

                processor = new MacroProcessor();
                processor.Add("realm", SqlHelper.Literal(realm));
                processor.Add("account", SqlHelper.Literal(account));
                processor.Add("password", SqlHelper.Literal(password));
                processor.Add("md5-password", SqlHelper.Literal(MD5Hasher.Compute(password)));
                processor.Add("sha1-password", SqlHelper.Literal(SHA1Hasher.Compute(password)));
                processor.Add("sha256-password", SqlHelper.Literal(SHA256Hasher.Compute(password)));
                processor.Add("sha512-password", SqlHelper.Literal(SHA512Hasher.Compute(password)));
                query = processor.Expand(queryTemplate);
            }

            // Perform the query.

            dbCon = new OdbcConnection(_conString);
            dbCon.Open();

            try
            {
                cmd             = dbCon.CreateCommand();
                cmd.CommandText = query;
                cmd.CommandType = CommandType.Text;

                perf.Queries.Increment();
                reader = cmd.ExecuteReader();
                if (!reader.Read())
                {
                    authCode = (int)AuthenticationStatus.AccessDenied; // Empty result set
                }
                else
                {
                    object o    = reader[0];
                    Type   type = o.GetType();

                    if (type == typeof(byte))
                    {
                        authCode = (int)(byte)o;
                    }
                    else if (type == typeof(int))
                    {
                        authCode = (int)o;
                    }
                    else if (type == typeof(long))
                    {
                        authCode = (int)(long)o;
                    }
                    else
                    {
                        throw new AuthenticationException("ODBC authenticate query returned a [{0}] instead of the expected [integer].", type.Name);
                    }

                    if (authCode < 0 || authCode > 5)
                    {
                        throw new AuthenticationException("ODBC authenticate query returned the invalid return code [{0}]. Valid codes range from 0..5", authCode);
                    }
                }
            }
            catch (Exception e)
            {
                perf.Exceptions.Increment();
                throw new AuthenticationException(e);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }

                dbCon.Close();
            }

            return(new AuthenticationResult((AuthenticationStatus)authCode, maxCacheTime));
        }