示例#1
0
        /// <summary>
        /// Hashes a password.
        /// </summary>
        /// <param name="password">Password to hash. It is converted to bytes using UTF8.</param>
        /// <param name="saltSize">Size of salt. It is kept between 0 and 16 characters without throwing exception.</param>
        /// <param name="algorithm">Algorithm to use.</param>
        /// <param name="iterationCount">Number of iterations. If value is 0 then default value is used.</param>
        /// <exception cref="System.ArgumentNullException">Password cannot be null.</exception>
        /// <exception cref="System.ArgumentOutOfRangeException">Unknown algorithm.</exception>
        public static String Create(String password, Int32 saltSize, PasswordAlgorithm algorithm, Int32 iterationCount)
        {
            if (password == null)
            {
                throw new ArgumentNullException(nameof(password), "Password cannot be null.");
            }

            if (saltSize < MinimumSaltSize)
            {
                saltSize = MinimumSaltSize;
            }
            if (saltSize > MaximumSaltSize)
            {
                saltSize = MaximumSaltSize;
            }

            var salt = new byte[saltSize];

            Rng.GetBytes(salt);
            for (var i = 0; i < salt.Length; i++)
            { //make it an ascii
                salt[i] = (byte)Base64Characters[salt[i] % Base64Characters.Length];
            }

            return(Create(Utf8WithoutBom.GetBytes(password), salt, algorithm, iterationCount));
        }
示例#2
0
 public SifHashEncryption(PasswordAlgorithm algorithm,
                          string keyName,
                          HashAlgorithm alg)
     : base(algorithm, string.Empty)
 {
     fHashAlgorithm = alg;
 }
示例#3
0
        /// <summary>
        /// Hashes a password.
        /// </summary>
        /// <param name="password">Password to hash. It is converted to bytes using UTF8.</param>
        /// <param name="saltSize">Size of salt. It is kept between 0 and 16 characters without throwing exception.</param>
        /// <param name="algorithm">Algorithm to use.</param>
        /// <param name="iterationCount">Number of iterations. If value is 0 then default value is used.</param>
        /// <exception cref="System.ArgumentNullException">Password cannot be null.</exception>
        /// <exception cref="System.ArgumentOutOfRangeException">Unknown algorithm.</exception>
        public static string Create(string password, int saltSize, PasswordAlgorithm algorithm, int iterationCount)
        {
            if (password == null)
            {
                throw new ArgumentNullException("password", "Password cannot be null.");
            }

            if (saltSize < Password.MinimumSaltSize)
            {
                saltSize = Password.MinimumSaltSize;
            }
            if (saltSize > Password.MaximumSaltSize)
            {
                saltSize = Password.MaximumSaltSize;
            }

            var salt = new byte[saltSize];

            Password.Rng.GetBytes(salt);
            for (var i = 0; i < salt.Length; i++)   //make it an ascii
            {
                salt[i] = (byte)Password.Base64Characters[salt[i] % Password.Base64Characters.Length];
            }

            return(Create(Password.Utf8WithoutBom.GetBytes(password), salt, algorithm, iterationCount));
        }
示例#4
0
        /// <summary>
        /// Creates an instance of SIFEncryption that uses the specified
        /// PasswordAlgorithm, keyName and key
        /// </summary>
        /// <param name="algorithm">The algorithm to use for encrypting or decrypting passwords</param>
        /// <param name="keyName">The name of the encryption key to use.</param>
        /// <param name="key">The encryption key to use. This parameter is ignored for
        /// SHA1 and MD5 because they are not keyed hash algorithms </param>
        /// <returns>An instance of the SifEncryption class for reading and writing passwords</returns>
        public static SifEncryption GetInstance(
            PasswordAlgorithm algorithm,
            string keyName,
            byte [] key
            )
        {
            if (sCurrentInstance != null)
            {
                if (!sCurrentInstance.fDisposed &&
                    sCurrentInstance.Algorithm.Value.Equals(algorithm.Value) &&
                    (sCurrentInstance.KeyName == keyName || sCurrentInstance.Key == null))
                {
                    return(sCurrentInstance);
                }
                else
                {
                    sCurrentInstance.Dispose();
                    sCurrentInstance = null;
                }
            }

            if (algorithm.ValueEquals("base64"))
            {
                sCurrentInstance = new SifClearTextEncryption(algorithm, keyName);
            }
            else if (algorithm.Value == PasswordAlgorithm.SHA1.Value)
            {
                sCurrentInstance = new SifHashEncryption(algorithm, keyName, new SHA1Managed());
            }
            else if (algorithm.Value == PasswordAlgorithm.MD5.Value)
            {
                sCurrentInstance =
                    new SifHashEncryption(algorithm, keyName, new MD5CryptoServiceProvider());
            }
            else if (algorithm.Value == PasswordAlgorithm.DES.Value)
            {
                sCurrentInstance =
                    new SifSymmetricEncryption
                        (algorithm, keyName, new DESCryptoServiceProvider(), key);
            }
            else if (algorithm.Value == PasswordAlgorithm.TRIPLEDES.Value)
            {
                sCurrentInstance =
                    new SifSymmetricEncryption
                        (algorithm, keyName, new TripleDESCryptoServiceProvider(), key);
            }
            else if (algorithm.Value == PasswordAlgorithm.RC2.Value)
            {
                sCurrentInstance =
                    new SifSymmetricEncryption
                        (algorithm, keyName, new RC2CryptoServiceProvider(), key);
            }
            else
            {
                throw new AdkNotSupportedException
                          (string.Format("Encryption algorithm {0} is not supported.", algorithm.Value));
            }

            return(sCurrentInstance);
        }
示例#5
0
 /// <summary>
 /// Hashes a password.
 /// </summary>
 /// <param name="password">Password to hash. It is converted to bytes using UTF8.</param>
 /// <param name="algorithm">Algorithm to use.</param>
 /// <exception cref="System.ArgumentNullException">Password cannot be null.</exception>
 /// <exception cref="System.ArgumentOutOfRangeException">Unknown algorithm.</exception>
 public static string Create(string password, PasswordAlgorithm algorithm)
 {
     if ((algorithm == PasswordAlgorithm.MD5) || (algorithm == PasswordAlgorithm.MD5Apache))
     {
         return(Create(password, 8, algorithm));
     }
     else
     {
         return(Create(password, 16, algorithm));
     }
 }
 public void ConfigurePasswordAlgorithm(PasswordAlgorithm passwordAlgorithm)
 {
     if (null == passwordAlgorithm)
     {
         throw new ArgumentNullException("passwordAlgorithm");
     }
     passwordAlgorithm.CompareInConstantTime = CompareInConstantTime;
     passwordAlgorithm.HashFunction          = HashFunction;
     passwordAlgorithm.HashIterations        = HashIterations;
     passwordAlgorithm.SaltLength            = SaltLength;
 }
示例#7
0
 public SifSymmetricEncryption(PasswordAlgorithm algorithm,
                               string keyName,
                               SymmetricAlgorithm alg,
                               byte [] key)
     : base(algorithm, keyName)
 {
     fSymmetricAlgorithm = alg;
     alg.Key             = key;
     alg.BlockSize       = 64;
     alg.Mode            = CipherMode.CBC;
     alg.Padding         = PaddingMode.PKCS7;
 }
        /// <summary>
        /// Tests the SifEncryption Class using clear text encryption
        /// </summary>
        //[Test, Explicit]
        //public void TestRSAEncryption()
        //{
        //    // This test is not currently run with the full suite of tests because support for RSA encryption is
        //    // not implemented in the ADK
        //    SifEncryption encr = SifEncryption.GetInstance(PasswordAlgorithm.RSA, "SECRET_KEY_RSA", null);
        //    AssertEncryption(encr, DEFAULT_ENCRYPTED_STRING);
        //}

        /// <summary>
        /// Asserts that the password is encrypted and decrypted properly and returns the AuthenticationInfo
        /// object that was produced in test for further assertions, if necessary
        /// </summary>
        /// <param name="encryptor"></param>
        /// <param name="passwordText"></param>
        /// <returns></returns>
        private AuthenticationInfo AssertEncryption(SifEncryption encryptor, string passwordText)
        {
            AuthenticationInfo returnValue = null;

            Authentication     auth = CreateAuthentication();
            AuthenticationInfo inf  = auth.AuthenticationInfo;

            inf.PasswordList = new PasswordList();
            inf.PasswordList.Add(new Password());
            // Encrypt the password
            encryptor.WritePassword(inf.PasswordList.ItemAt(0), passwordText);

            // Write the object to and and read from xml to assure that the values are being persisted properly
            Authentication reparsedAuth =
                (Authentication)AdkObjectParseHelper.WriteParseAndReturn(auth, Adk.SifVersion);

            returnValue = reparsedAuth.AuthenticationInfo;

            SifEncryption decryptor =
                SifEncryption.GetInstance(PasswordAlgorithm.Wrap(returnValue.PasswordList.ItemAt(0).Algorithm),
                                          encryptor.KeyName, encryptor.Key);

            string decryptedValue = decryptor.ReadPassword(returnValue.PasswordList.ItemAt(0));

            if (encryptor.IsHash)
            {
                // Assert that the decrypted value is the same as the AuthenticationInfoPassword's text value
                Assert.AreEqual(returnValue.PasswordList.ItemAt(0).TextValue, decryptedValue,
                                "Hashed implementation of ReadPassword() should return the Base64 value");
                // Assert that the hash is correct
                HashAlgorithm hasher = null;
                if (returnValue.PasswordList.ItemAt(0).Algorithm == PasswordAlgorithm.SHA1.Value)
                {
                    hasher = new SHA1CryptoServiceProvider();
                }
                else if (returnValue.PasswordList.ItemAt(0).Algorithm == PasswordAlgorithm.MD5.Value)
                {
                    hasher = new MD5CryptoServiceProvider();
                }
                byte[] preHashed = Encoding.UTF8.GetBytes(passwordText);
                byte[] hashed    = hasher.ComputeHash(preHashed);
                string textHash  = Convert.ToBase64String(hashed);
                ((IDisposable)hasher).Dispose();

                Assert.AreEqual(textHash, decryptedValue, "Hash values do not match");
            }
            else
            {
                Assert.AreEqual(passwordText, decryptedValue, "Decypted value differs from original value.");
            }

            return(returnValue);
        }
        private PasswordAlgorithm CreateIfNotExistsOrGet(PasswordAlgorithms algorithm)
        {
            var name = Enum.GetName(typeof(PasswordAlgorithms), algorithm);
            var passwordAlgorithm = Repository.GetSet <PasswordAlgorithm>().FirstOrDefault(p => p.Name.ToLower().Equals(name.ToLower()));

            if (passwordAlgorithm == null)
            {
                passwordAlgorithm      = new PasswordAlgorithm();
                passwordAlgorithm.Name = name;
                Repository.Add(passwordAlgorithm);
            }
            return(passwordAlgorithm);
        }
示例#10
0
        public void ConfigurePasswordAlgorithm(PasswordAlgorithm passwordAlgorithm)
        {
            var element = Section;

            if (element != null)
            {
                var elementInformation = element.ElementInformation;
                if (elementInformation != null && elementInformation.IsPresent)
                {
                    element.ConfigurePasswordAlgorithm(passwordAlgorithm);
                }
            }
        }
示例#11
0
 /// <summary>
 /// Creates an instance of SIFEncryption that can decrypt
 /// the password field automatically, using settings
 /// defined in the agent's properties.
 /// </summary>
 /// <remarks>
 /// <para>
 /// This method searches the agent properties in effect
 /// for the zone and looks for one that matches the key
 /// defined in the Password object.
 /// If it finds one, it returns an instance of SIFEncryption
 /// that has been initialized with the proper key and
 /// encryption algorithm for the field.
 /// </para>
 /// <para>
 /// This method looks for a property named
 /// "adk.encryption.keys.[key]" where [key] is the name
 /// of the key field defined by the Password
 /// field.
 /// </para>
 /// </remarks>
 /// <param name="password">The password object that needs
 /// to be decrypted</param>
 /// <param name="zone">The zone that is in scope for the
 /// current message</param>
 /// <returns></returns>
 public static SifEncryption GetInstance(
     Password password,
     IZone zone)
 {
     if (sCurrentInstance != null &&
         sCurrentInstance.Algorithm.Value == password.Algorithm &&
         (sCurrentInstance.KeyName == password.KeyName || sCurrentInstance.Key == null))
     {
         return(sCurrentInstance);
     }
     byte [] key = zone.Properties.GetEncryptionKey(password.KeyName);
     return
         (GetInstance(PasswordAlgorithm.Wrap(password.Algorithm), password.KeyName, key));
 }
示例#12
0
        /// <summary>
        /// Creates an instance of SIFEncryption that can be used
        /// for writing the Password field,
        /// using settings from the agent's properties
        /// </summary>
        /// <remarks>
        /// This method searches for two properties in the agent
        /// properties. "adk.encryption.algorithm" returns the default
        /// algorithm the agent uses for encryption.
        /// "adk.encryption.key" returns the name of the key to use for
        /// encryption, which the agent then retrieves from the
        /// "adk.encryption.keys.[key]" property.
        /// </remarks>
        /// <returns>An instance of the SIfEncryption class</returns>
        public static SifEncryption GetInstance(IZone zone)
        {
            string alg     = zone.Properties.DefaultEncryptionAlgorithm;
            string keyName = zone.Properties.DefaultEncryptionKeyName;

            if (alg == null)
            {
                throw new AdkException
                          ("The default encryption algorithm or default key name is not defined in the agent or zone properties",
                          zone);
            }
            byte [] key = null;
            if (keyName != null)
            {
                zone.Properties.GetEncryptionKey(keyName);
            }
            // Don't check for a null key at this time because some of the algorithms don't even need a key
            return(GetInstance(PasswordAlgorithm.Wrap(alg), keyName, key));
        }
示例#13
0
        /// <summary>
        /// Hashes a password.
        /// </summary>
        /// <param name="password">Password to hash.</param>
        /// <param name="algorithm">Algorithm to use.</param>
        /// <param name="salt">Salt. Length of salt is not restricted.</param>
        /// <param name="iterationCount">Number of iterations. If value is 0 then default value is used.</param>
        /// <exception cref="System.ArgumentNullException">Password cannot be null. -or- Salt cannot be null.</exception>
        /// <exception cref="System.ArgumentOutOfRangeException">Unknown algorithm.</exception>
        public static string Create(byte[] password, byte[] salt, PasswordAlgorithm algorithm, int iterationCount)
        {
            if (password == null)
            {
                throw new ArgumentNullException("password", "Password cannot be null.");
            }
            if (salt == null)
            {
                throw new ArgumentNullException("salt", "Salt cannot be null.");
            }

            if (iterationCount != 0)   //silently setup iterationCount to allowable limits (except for default value)
            {
                if (iterationCount < Password.MinimumIterationCount)
                {
                    iterationCount = Password.MinimumIterationCount;
                }
                if (iterationCount > Password.MaximumIterationCount)
                {
                    iterationCount = Password.MaximumIterationCount;
                }
            }

            if (algorithm == PasswordAlgorithm.Default)
            {
                algorithm = PasswordAlgorithm.Sha512;
            }
            switch (algorithm)
            {
            case PasswordAlgorithm.MD5: return(CreateMd5Basic(password, salt, iterationCount));

            case PasswordAlgorithm.MD5Apache: return(CreateMd5Apache(password, salt, iterationCount));

            case PasswordAlgorithm.Sha256: return(CreateSha256(password, salt, iterationCount));

            case PasswordAlgorithm.Sha512: return(CreateSha512(password, salt, iterationCount));

            default: throw new ArgumentOutOfRangeException("algorithm", "Unknown algorithm.");
            }
        }
        public void ConfigurePasswordAlgorithm_ConfiguresInstance()
        {
            var appConfig = @"<?xml version='1.0'?>
                <configuration>
                    <configSections>
                        <section name='ensues.security' type='Ensues.Configuration.SecuritySection, Ensues.Security' />
                    </configSections>
                    <ensues.security>
                        <passwordAlgorithm hashFunction='SHA384' hashIterations='123456' compareInConstantTime='false' saltLength='321' />
                        <passwordGenerator length='100' symbols='abcdefghijklmnopqrstuvwxyz' />
                    </ensues.security>
                </configuration>
            ";

            using (AppConfig.With(appConfig)) {
                var algo = new PasswordAlgorithm();
                SecurityConfiguration.Default.ConfigurePasswordAlgorithm(algo);
                Assert.AreEqual(HashFunction.SHA384, algo.HashFunction);
                Assert.AreEqual(123456, algo.HashIterations);
                Assert.AreEqual(false, algo.CompareInConstantTime);
                Assert.AreEqual(321, algo.SaltLength);
            }
        }
示例#15
0
 ///<summary>Adds the value of the <c>&lt;Password&gt;</c> element.</summary>
 /// <param name="Algorithm">The method used to encrypt the user's password. See the implementation details below.</param>
 /// <param name="KeyName">The name of the key to be used for decryption of the password.  Left blank for plain, encoded text (Algorithm attribute value of "base64") and hash algorithms.</param>
 /// <param name="Value">Gets or sets the content value of the &amp;lt;Password&amp;gt; element</param>
 ///<remarks>
 /// <para>This form of <c>setPassword</c> is provided as a convenience method
 /// that is functionally equivalent to the method <c>AddPassword</c></para>
 /// <para>Version: 2.6</para>
 /// <para>Since: 2.3</para>
 /// </remarks>
 public void AddPassword(PasswordAlgorithm Algorithm, string KeyName, string Value)
 {
     AddChild(InfrastructureDTD.PASSWORDLIST_PASSWORD, new Password(Algorithm, KeyName, Value));
 }
示例#16
0
 private SifEncryption(PasswordAlgorithm algorithm,
                       string keyName)
 {
     fkeyName   = keyName;
     fAlgorithm = algorithm;
 }
示例#17
0
 /// <summary>
 /// Hashes a password.
 /// </summary>
 /// <param name="password">Password to hash. It is converted to bytes using UTF8.</param>
 /// <param name="saltSize">Size of salt. It is kept between 0 and 16 characters without throwing exception.</param>
 /// <param name="algorithm">Algorithm to use.</param>
 /// <exception cref="System.ArgumentNullException">Password cannot be null.</exception>
 /// <exception cref="System.ArgumentOutOfRangeException">Unknown algorithm.</exception>
 public static string Create(string password, int saltSize, PasswordAlgorithm algorithm)
 {
     return(Create(password, saltSize, algorithm, 0));
 }
示例#18
0
 /// <summary>
 /// Hashes a password.
 /// </summary>
 /// <param name="password">Password to hash. It is converted to bytes using UTF8.</param>
 /// <param name="saltSize">Size of salt. It is kept between 0 and 16 characters without throwing exception.</param>
 /// <param name="algorithm">Algorithm to use.</param>
 /// <exception cref="System.ArgumentNullException">Password cannot be null.</exception>
 /// <exception cref="System.ArgumentOutOfRangeException">Unknown algorithm.</exception>
 public static String Create(String password, Int32 saltSize, PasswordAlgorithm algorithm)
 {
     return(Create(password, saltSize, algorithm, 0));
 }
示例#19
0
 public SifClearTextEncryption(PasswordAlgorithm algorithm,
                               string keyName)
     : base(algorithm, string.Empty)
 {
 }