예제 #1
0
파일: Encryption.cs 프로젝트: lamemmv/apex
        private static string ComputeHash(HashProvider hashAlgorithm, string plainText, byte[] salt)
        {
            // Convert plain text into a byte array
            byte[] data = Encoding.UTF8.GetBytes(plainText);
            int dataLength = data.Length;

            // Random salt
            int saltLength = salt.Length;

            // Append the salt to the end of the plainText
            byte[] dataSalt = new byte[dataLength + saltLength];

            // Copy both the data and salt into the new array
            Array.Copy(data, dataSalt, dataLength);
            Array.Copy(salt, 0, dataSalt, dataLength, saltLength);

            // Compute hash value of our plain text with appended salt.
            byte[] encrypt = GetHashProvider(hashAlgorithm).ComputeHash(dataSalt);
            int encryptLength = encrypt.Length;

            // Append the salt to the end of the encrypt
            byte[] encryptSalt = new byte[encryptLength + saltLength];
            Array.Copy(encrypt, encryptSalt, encryptLength);
            Array.Copy(salt, 0, encryptSalt, encryptLength, saltLength);

            return Convert.ToBase64String(encryptSalt);
        }
예제 #2
0
파일: Encryption.cs 프로젝트: lamemmv/apex
        private static HashAlgorithm GetHashProvider(HashProvider hashAlgorithm)
        {
            HashAlgorithm hash;
            switch (hashAlgorithm)
            {
                case HashProvider.SHA1:
                    hash = new SHA1Managed();
                    break;

                case HashProvider.SHA256:
                    hash = new SHA256Managed();
                    break;

                case HashProvider.SHA384:
                    hash = new SHA384Managed();
                    break;

                case HashProvider.SHA512:
                    hash = new SHA512Managed();
                    break;

                case HashProvider.MD5:
                default:
                    hash = new MD5CryptoServiceProvider();
                    break;
            }

            return hash;
        }
예제 #3
0
 /// <summary>
 /// Creates a SaltedHasher, configuring it to use the specified hashing provider, salt position and salt length, and password generator
 /// </summary>
 /// <param name="provider">Hash algorithm to use by default</param>
 /// <param name="saltLength">Length for the salt</param>
 /// <param name="saltPosition">Position for the salt</param>
 /// <param name="passwordGenerator">Password generator for generating the salts</param>
 SaltedHasher(HashProvider provider, int saltLength, SaltPosition saltPosition, PasswordGenerator passwordGenerator)
 {
     Provider = provider;
     SaltPosition = saltPosition;
     SaltLength = saltLength;
     PasswordGenerator = passwordGenerator;
 }
예제 #4
0
        static UsersConfiguration()
        {
            var appSettings = ConfigurationManager.AppSettings;

            UserLockoutEnabledByDefault = ToBool(appSettings["UserLockoutEnabledByDefault"], true);
            DefaultAccountLockoutTimeSpan = ToInt(appSettings["DefaultAccountLockoutTimeSpan"], 5);
            MaxFailedAccessAttemptsBeforeLockout = ToInt(appSettings["MaxFailedAccessAttemptsBeforeLockout"], 5);

            SaltSize = ToInt(appSettings["SaltSize"], 12);
            HashProvider = ToHashProvider(appSettings["HashProvider"]);
        }
예제 #5
0
 public static HashAlgorithm GetInstance(HashProvider algorithm)
 {
     switch (algorithm)
     {
         case HashProvider.SHA1:
             return new SHA1CryptoServiceProvider();
         case HashProvider.MD5:
             return new MD5CryptoServiceProvider();
         case HashProvider.HMACSHA1:
             return new HMACSHA1();
         case HashProvider.HMACMD5:
             return new HMACMD5();
         default:
             return null;
     }
 }
예제 #6
0
        /// <summary>
        /// Generate random hash value to store against password
        /// </summary>
        /// <param name="password">String to encrypt</param>
        /// <param name="salt">Random string to salt computed hash, automatically generated if empty</param>
        /// <param name="provider">Hash algorithm to use for computing hash value</param>
        /// <returns>Hash value for the password with the addition of salt 'MD5$Salt$Hash'</returns>
        public static string GenerateHash(string password, string salt = null, HashProvider provider = HashProvider.MD5)
        {
            Guard.CheckNullOrTrimEmpty(password, "Password cannot be empty");

            salt = salt ?? GenerateSalt();

            var bytes = Encoding.Unicode.GetBytes(salt + password);
            try
            {
                var hash = hashProviders[provider].ComputeHash(bytes);
                return provider + "$" + salt + "$" + hash.ToHexString();
            }
            catch (KeyNotFoundException ex)
            {
                throw new NotSupportedException(string.Format("Hash Provider '{0}' is not supported", provider), ex);
            }
        }
예제 #7
0
파일: Encryption.cs 프로젝트: lamemmv/apex
        public static bool CompareStringToHash(HashProvider hashAlgorithm, string plainText, string encrypt, int saltSize = 0)
        {
            byte[] encryptBuffer = Convert.FromBase64String(encrypt);
            int encryptLength = encryptBuffer.Length;

            // Pluck the salt size off of the end of the hash.
            if (saltSize < 0)
            {
                saltSize = 0;
            }

            byte[] saltBuffer = new byte[saltSize];
            Array.Copy(encryptBuffer, encryptLength - saltSize, saltBuffer, 0, saltSize);

            string hash = ComputeHash(hashAlgorithm, plainText, saltBuffer);
            return string.Equals(encrypt, hash);
        }
예제 #8
0
 /// <summary>
 /// Initialize a new instance of the class <see cref="Hash"/>.
 /// </summary>
 /// <param name="provider">Provider</param>
 public Hash(HashProvider provider)
     : this()
 {
     switch (provider)
     {
         case HashProvider.MD5:
             _algorithm = new MD5CryptoServiceProvider();
             break;
         case HashProvider.SHA1:
             _algorithm = new SHA1Managed();
             break;
         case HashProvider.SHA256:
             _algorithm = new SHA256Managed();
             break;
         case HashProvider.SHA384:
             _algorithm = new SHA384Managed();
             break;
         case HashProvider.SHA512:
             _algorithm = new SHA512Managed();
             break;
     }
 }
예제 #9
0
        /// <summary>
        /// Creates and returns the HashAlgorithm object for the specified provider
        /// </summary>
        /// <param name="provider">The desired hash algorithm provider</param>
        /// <returns>The required hashing object</returns>
        public static HashAlgorithm GetHashAlgorithm(HashProvider provider)
        {
            switch( provider )
            {
                case HashProvider.MD5:
                    return System.Security.Cryptography.MD5.Create();

                case HashProvider.SHA1:
                    return SHA1.Create();

                case HashProvider.SHA256:
                    return SHA256.Create();

                case HashProvider.SHA384:
                    return SHA384.Create();

                case HashProvider.SHA512:
                    return SHA512.Create();
            }

            throw new ArgumentException("Unsupported HashProvider: {0}! ".FormatCurrentCulture(provider) +
                    "If you add a new algorithm to the HashProvider, make sure you add it to the " +
                        "switch statement in the Hasher.GetHashAlgorithm method!", "provider");
        }
예제 #10
0
 public SqlPasswordHasher(int saltLength, HashProvider hashProvider)
 {
     _saltLength = saltLength;
     _hashProvider = hashProvider;
 }
예제 #11
0
        internal async Task <bool> Register()
        {
            bool isNew = false;

            if (string.IsNullOrEmpty(FirstName))
            {
                _errorMessage = "Please enter a Name";
                return(false);
            }
            else if (string.IsNullOrEmpty(Surname))
            {
                _errorMessage = "Please enter a Surname";
                return(false);
            }
            else if (string.IsNullOrEmpty(EmailAddress))
            {
                _errorMessage = "Please enter a Email";
                return(false);
            }
            else if (string.IsNullOrEmpty(Password))
            {
                _errorMessage = "Please enter a Password";
                return(false);
            }
            else if (Password != ConfirmPassword)
            {
                _errorMessage = "The password and Confirm Password must match";
                return(false);
            }

            var user = _context.Users.FirstOrDefault(x => ((x.EmailAddress == EmailAddress && x.EmailAddress != null)));

            if (user == null)
            {
                user                 = new User();
                isNew                = true;
                user.UserID          = Guid.NewGuid();
                user.IsSuspended     = false;
                user.LoginTries      = 0;
                user.CreatedUserID   = user.UserID;
                user.CreatedDateTime = DateTime.UtcNow;
                user.IsRemoved       = false;

                user.Password = HashProvider.ComputeHash(Password, HashProvider.HashAlgorithmList.SHA256, _securityOptions.PasswordSalt);
            }
            else
            {
                _errorMessage = "The user email address already exists. Find the existing user first and edit their details";
                return(false);
            }

            user.DisplayName  = DisplayName;
            user.EmailAddress = EmailAddress;
            user.IsSuspended  = false;
            user.LoginTries   = 0;
            user.EditUserID   = user.UserID;
            user.EditDateTime = DateTime.UtcNow;
            user.FirstName    = FirstName;
            user.Surname      = Surname;
            user.Timezone     = _context.SystemConfiguration.First(x => x.EventCode == PublicEnums.SystemConfigurationList.KEY_DEFAULT_TIME_ZONE.ToString()).ConfigValue;

            if (isNew)
            {
                _context.Add(user);

                //Add default student user role
                LinkUserRole link = new LinkUserRole();
                link.LinkUserRoleID = Guid.NewGuid();
                link.UserID         = user.UserID;
                link.UserRoleID     = _context.UserRoles.First(x => x.EventCode == PublicEnums.UserRoleList.ROLE_USER).UserRoleID;
                link.CreatedUserID  = user.UserID;
                link.EditUserID     = user.UserID;
                _context.Add(link);
            }
            else
            {
                _context.Update(user);
            }

            await _context.SaveChangesAsync();

            return(true);
        }
예제 #12
0
 /// <summary>
 /// Creates a SaltedHasher, configuring it to use the specified hashing provider and using a default prefixed salt of 8 characters
 /// </summary>
 /// <param name="provider">Hash algorithm to use by default</param>
 public SaltedHasher(HashProvider provider)
     : this(provider, DefaultSaltLength, SaltPosition.Prefix, new PasswordGenerator())
 {
 }
예제 #13
0
        public HashProvider BuildHashProvider(string value)
        {
            var bytes = value.GetBytes();

            return(HashProvider.New(bytes));
        }
예제 #14
0
 public static Oid GetOID(this HashProvider ForProvider)
 {
     return(Oid.FromFriendlyName(ForProvider.ToString(), OidGroup.HashAlgorithm));
 }
예제 #15
0
 private Data DoHash(HashProvider p)
 {
     using (var h = new Hash(p))
      {
     return h.Calculate(new Data(_targetString));
      }
 }
예제 #16
0
파일: Cert.cs 프로젝트: JeremyOne/CryptLink
 /// <summary>
 /// Loads the certificate using a SecureString for decryption
 /// This function is only needed when the certificate is encrypted with a password.
 /// </summary>
 public void LoadCertificate(SecureString EncryptionPassword, HashProvider Provider)
 {
     this.EncryptionPassword = EncryptionPassword;
     this.Provider           = Provider;
     LoadCertificate(Provider);
 }
        public void HashProvider_ReturnsPasswordMatch(string password, string salt, string hashedPassword)
        {
            HashProvider hashProvider = new HashProvider();

            Assert.IsTrue(hashProvider.VerifyPasswordMatch(hashedPassword, password, salt));
        }
예제 #18
0
 /// <summary>
 /// Initializes a new instance of the Hash class with the specified hash provider.
 /// </summary>
 public Hash(HashProvider provider)
 {
     _hash = HashingFactory.Create(provider);
 }
예제 #19
0
        Hash[] allKeys = null;    //cache the ordered keys for better performance

        public ConsistentHash(HashProvider _Provider)
        {
            Provider = _Provider;
        }
예제 #20
0
        private string GetResultString(HashProvider Provider, long ItemCount)
        {
            var perSec = (ItemCount / TestLength.TotalSeconds);

            return($"{Provider}: added {ItemCount.ToString("n0")} items, replication count: {replicationCount.ToString("n0")}, ({perSec.ToString("n0")} unique per sec, {(perSec * replicationCount).ToString("n0")} replicated)\r\n");
        }
예제 #21
0
        public void when_bytes_is_empty_should_throw_ArgumentNullException()
        {
            byte[] bytes = new byte[0];

            Assert.Throws <ArgumentNullException>(() => HashProvider.New(bytes));
        }
예제 #22
0
        /// <summary>
        /// Creates a new instance of the HashAlgorithm class based on the specified provider.
        /// </summary>
        /// <param name="provider">Provides the type of hash algorithm to create.</param>
        /// <returns>The HashAlgorithm object.</returns>
        /// <exception cref="T:System.ArgumentException">The provider is unknown.</exception>
        public static HashAlgorithm Create(HashProvider provider)
        {
            switch (provider)
             {
            case HashProvider.CRC32:
               return new CRC32();
            case HashProvider.SHA1:
               return SHA1.Create();
            case HashProvider.SHA256:
               return SHA256.Create();
            case HashProvider.SHA384:
               return SHA384.Create();
            case HashProvider.SHA512:
               return SHA512.Create();
            case HashProvider.MD5:
               return MD5.Create();
             }

             throw new ArgumentException("Unknown HashProvider.", "provider");
        }
예제 #23
0
 /// <summary>
 /// Initializes a new instance of the Hash class with the specified hash provider.
 /// </summary>
 public Hash(HashProvider provider)
 {
     _hash = HashAlgorithmFactory.Create(provider);
 }
예제 #24
0
 public void should_call_hash_provider_for_each_file()
 {
     HashProvider.Verify(x => x.hash_file(It.IsAny <string>()), Times.Exactly(files.Count));
 }
예제 #25
0
 private Data DoSaltedHash(HashProvider p, Data salt)
 {
     using (var h = new Hash(p))
      {
     return h.Calculate(new Data(_targetString), salt);
      }
 }
예제 #26
0
파일: Encryption.cs 프로젝트: lamemmv/apex
 public static string ComputeHash(HashProvider hashAlgorithm, string plainText, int saltSize = 0)
 {
     // Random salt.
     byte[] salt = saltSize > 0 ? Random.RNGCrypto(saltSize) : new byte[0];
     return ComputeHash(hashAlgorithm, plainText, salt);
 }
예제 #27
0
 /// <summary>
 /// Creates a Hasher, configuring it to use the specified hashing provider
 /// </summary>
 /// <param name="provider">Hash algorithm to use by default</param>
 public Hasher(HashProvider provider)
 {
     Provider = provider;
 }
예제 #28
0
 /// <summary>
 /// Creates a SaltedHasher, configuring it to use the specified hashing provider, salt position and salt length
 /// </summary>
 /// <param name="provider">Hash algorithm to use by default</param>
 /// <param name="saltLength">Length for the salt</param>
 /// <param name="saltPosition">Position for the salt</param>
 public SaltedHasher(HashProvider provider, int saltLength, SaltPosition saltPosition)
     : this(provider, saltLength, saltPosition, new PasswordGenerator())
 {
 }
예제 #29
0
        /// <summary>
        /// Get hash text with encoding and provider
        /// </summary>
        /// <param name="text">Text</param>
        /// <param name="encoding">Encoding</param>
        /// <param name="provider">Provider</param>
        /// <returns>Hash</returns>
        public static string Hash(this string text, Encoding encoding, HashProvider provider)
        {
            var hash = new Hash(provider) {Encoding = encoding};

            return hash.Get(text);
        }
 /// <summary>
 /// Compute a hash for this object and optionally signs it
 /// </summary>
 /// <param name="Provider">The hash provider to use</param>
 /// <param name="SigningCert">If provided the cert to sign the hash with</param>
 public void ComputeHash(HashProvider Provider, Cert SigningCert = null)
 {
     ComputedHash = Hash.Compute(GetHashableData(), Provider, SigningCert);
 }