Inheritance: Org.BouncyCastle.Crypto.PbeParametersGenerator
Ejemplo n.º 1
0
		private static byte[] SingleIterationPBKDF2(byte[] P, byte[] S, int dkLen)
		{
			PbeParametersGenerator pGen = new Pkcs5S2ParametersGenerator(new Sha256Digest());
			pGen.Init(P, S, 1);
			KeyParameter key = (KeyParameter)pGen.GenerateDerivedMacParameters(dkLen * 8);
			return key.GetKey();
		}
Ejemplo n.º 2
0
 //http://stackoverflow.com/questions/34950611/how-to-create-a-pbkdf2-sha256-password-hash-in-c-sharp-bouncy-castle//
 public byte[] GeneratePbkdf2Sha256DerivedKey(byte[] password, byte[] salt, int count, int dklen)
 {
     var pdb = new Pkcs5S2ParametersGenerator(new Sha256Digest());
     pdb.Init(password, salt, count);
     //if dklen == 32, then it is 256 (8 * 32)
     var key = (KeyParameter)pdb.GenerateDerivedMacParameters(8 * dklen);
     return key.GetKey();
 }
Ejemplo n.º 3
0
        private static byte[] SingleIterationPBKDF2(byte[] P, byte[] S, int dkLen)
        {
            PbeParametersGenerator pGen = new Pkcs5S2ParametersGenerator(new Sha256Digest());

            pGen.Init(P, S, 1);
            KeyParameter key = (KeyParameter)pGen.GenerateDerivedMacParameters(dkLen * 8);

            return(key.GetKey());
        }
Ejemplo n.º 4
0
        public byte[] DeriveKey(string password, byte[] salt)
        {
            var passwordInBytes = PbeParametersGenerator.Pkcs5PasswordToBytes(password.ToCharArray());

            var keyGenerator = new Pkcs5S2ParametersGenerator();
            keyGenerator.Init(passwordInBytes, salt, _iterations);

            var keyParameter = (KeyParameter) keyGenerator.GenerateDerivedMacParameters(_keyBitSize);
            var keyBytes = keyParameter.GetKey();
            return keyBytes;
        }
Ejemplo n.º 5
0
        public static bool CheckPassword(string rawPassword, string hashPassword, string salt)
        {
            Pkcs5S2ParametersGenerator kdf = new Pkcs5S2ParametersGenerator();
            byte[] seed = StringHelper.FromBase64String(salt);

            kdf.Init(StringHelper.GetBytes(rawPassword), seed, 100);

            byte[] hash = ((KeyParameter)kdf.GenerateDerivedMacParameters(8 * rawPassword.Length)).GetKey();
            byte[] hashToCheck = StringHelper.FromBase64String(hashPassword);

            return AreBytesArraysEqual(hash, hashToCheck);
        }
 public void TestPBE3()
 {
     Stopwatch sw = new Stopwatch();
     sw.Start();
     var rng = new RNGCryptoServiceProvider();
     byte[] data = new byte[30];
     rng.GetBytes(data);
     var pk = new Pkcs5S2ParametersGenerator(new Sha512Digest());
     pk.Init(Encoding.UTF8.GetBytes("test"), data, 400000);
     pk.GenerateDerivedMacParameters(20 * 8);
     sw.Stop();
     System.Console.WriteLine(sw.Elapsed.TotalMilliseconds);
 }
Ejemplo n.º 7
0
        /// <summary>
        /// Generates a key from a password and salt and IV
        /// </summary>
        /// <param name="password"></param>
        /// <param name="saltBytes"></param>
        /// <param name="ivBytes"></param>
        /// <returns></returns>
        private static ParametersWithIV GenerateKey(string password, byte[] saltBytes, byte[] ivBytes)
        {
            var passBytes = PbeParametersGenerator.Pkcs5PasswordToUtf8Bytes(password.ToCharArray());

            //create key generator
            var generator = new Pkcs5S2ParametersGenerator();
            //initialize
            generator.Init(passBytes, saltBytes, KEY_DERIVATION_ITERATION);

            //generate with a 256bit key, and a 128bit IV
            var kp = new ParametersWithIV(generator.GenerateDerivedParameters(ALGORITHM_NAME, KEY_SIZE), ivBytes);

            return kp;
        }
Ejemplo n.º 8
0
        public static string HashPassword(string rawPassword, string salt, int hashLength = 10)
        {
            SecureRandom rng = new SecureRandom();
            Pkcs5S2ParametersGenerator kdf = new Pkcs5S2ParametersGenerator();
            byte[] seed = StringHelper.GetBytes(salt);

            kdf.Init(StringHelper.GetBytes(rawPassword), seed, 100);

            byte[] hash = ((KeyParameter)kdf.GenerateDerivedMacParameters(8 * hashLength)).GetKey();

            salt = StringHelper.ToBase64String(seed);

            return StringHelper.ToBase64String(hash);
        }
Ejemplo n.º 9
0
        internal override KeyParameter GetEncoded(
			string algorithmOid)
        {
            Pkcs5S2ParametersGenerator gen = new Pkcs5S2ParametersGenerator();

            gen.Init(
                PbeParametersGenerator.Pkcs5PasswordToBytes(this.Password),
                this.Salt,
                this.IterationCount);

            return (KeyParameter) gen.GenerateDerivedParameters(
                algorithmOid,
                CmsEnvelopedHelper.Instance.GetKeySize(algorithmOid));
        }
Ejemplo n.º 10
0
		/// <summary>
		/// Simple Encryption And Authentication (AES-GCM) of a UTF8 String
		/// using key derived from a password.
		/// </summary>
		/// <param name="secretMessage">The secret message.</param>
		/// <param name="password">The password.</param>
		/// <param name="nonSecretPayload">The non secret payload.</param>
		/// <returns>
		/// Encrypted Message
		/// </returns>
		/// <exception cref="System.ArgumentException">Must have a password of minimum length;password</exception>
		/// <remarks>
		/// Significantly less secure than using random binary keys.
		/// Adds additional non secret payload for key generation parameters.
		/// </remarks>
		public static byte[] SimpleEncryptWithPassword(byte[] secretMessage, string password, byte[] nonSecretPayload = null)
		{
			nonSecretPayload = nonSecretPayload ?? new byte[] { };

			//User Error Checks
			if (string.IsNullOrWhiteSpace(password) || password.Length < MinPasswordLength)
				throw new ArgumentException(String.Format("Must have a password of at least {0} characters!", MinPasswordLength), "password");

			if (secretMessage == null || secretMessage.Length == 0)
				throw new ArgumentException("Secret Message Required!", "secretMessage");

			var generator = new Pkcs5S2ParametersGenerator();

			//Use Random Salt to minimize pre-generated weak password attacks.
			var salt = new byte[SaltBitSize / 8];
			Random.NextBytes(salt);

			generator.Init(
				PbeParametersGenerator.Pkcs5PasswordToBytes(password.ToCharArray()),
				salt,
				Iterations);

			//Generate Key
			var key = (KeyParameter)generator.GenerateDerivedMacParameters(KeyBitSize);

			//Create Full Non Secret Payload
			var payload = new byte[salt.Length + nonSecretPayload.Length];
			Array.Copy(nonSecretPayload, payload, nonSecretPayload.Length);
			Array.Copy(salt, 0, payload, nonSecretPayload.Length, salt.Length);

			return SimpleEncrypt(secretMessage, key.GetKey(), payload);
		}
Ejemplo n.º 11
0
        static PbeParametersGenerator MakePbeGenerator(
			string	type,
			IDigest	digest,
			byte[]	key,
			byte[]	salt,
			int		iterationCount)
        {
            PbeParametersGenerator generator;

            if (type.Equals(Pkcs5S1))
            {
                generator = new Pkcs5S1ParametersGenerator(digest);
            }
            else if (type.Equals(Pkcs5S2))
            {
                generator = new Pkcs5S2ParametersGenerator();
            }
            else if (type.Equals(Pkcs12))
            {
                generator = new Pkcs12ParametersGenerator(digest);
            }
            else if (type.Equals(OpenSsl))
            {
                generator = new OpenSslPbeParametersGenerator();
            }
            else
            {
                throw new ArgumentException("Unknown PBE type: " + type, "type");
            }

            generator.Init(key, salt, iterationCount);
            return generator;
        }
Ejemplo n.º 12
0
        private KeyParameter CreateKey(string password, byte[] salt, int iterations, int keySizeInBits)
        {
            var generator = new Pkcs5S2ParametersGenerator(new Sha256Digest());
            generator.Init(PbeParametersGenerator.Pkcs5PasswordToUtf8Bytes(password.ToCharArray()), salt, iterations);

            return (KeyParameter)generator.GenerateDerivedMacParameters(keySizeInBits);
        }
Ejemplo n.º 13
0
            public override void PerformTest()
            {
                char[] password = "******".ToCharArray();
                PbeParametersGenerator generator = new Pkcs5S2ParametersGenerator();

                EncryptedPrivateKeyInfo info = null;
                try
                {
                    info = EncryptedPrivateKeyInfo.GetInstance(Asn1Object.FromByteArray(sample));
                }
                catch (System.Exception e)
                {
                    Fail("failed construction - exception " + e.ToString(), e);
                }

                PbeS2Parameters alg = PbeS2Parameters.GetInstance(info.EncryptionAlgorithm.Parameters);
                Pbkdf2Params func = Pbkdf2Params.GetInstance(alg.KeyDerivationFunc.Parameters);
                EncryptionScheme scheme = alg.EncryptionScheme;

                if (func.KeyLength != null)
                {
                    keySize = func.KeyLength.IntValue * 8;
                }

                int iterationCount = func.IterationCount.IntValue;
                byte[] salt = func.GetSalt();

                generator.Init(PbeParametersGenerator.Pkcs5PasswordToBytes(password), salt, iterationCount);

                DerObjectIdentifier algOid = scheme.Algorithm;

                byte[] iv;
                if (algOid.Equals(PkcsObjectIdentifiers.RC2Cbc))
                {
                    RC2CbcParameter rc2Params = RC2CbcParameter.GetInstance(scheme.Asn1Object);
                    iv = rc2Params.GetIV();
                }
                else
                {
                    iv = ((Asn1OctetString) scheme.Asn1Object).GetOctets();
                }

                ICipherParameters param = new ParametersWithIV(
                    generator.GenerateDerivedParameters(algOid.Id, keySize), iv);

                cipher.Init(false, param);

                byte[] data = info.GetEncryptedData();
                byte[] outBytes = new byte[cipher.GetOutputSize(data.Length)];
                int len = cipher.ProcessBytes(data, 0, data.Length, outBytes, 0);

                try
                {
                    len += cipher.DoFinal(outBytes, len);
                }
                catch (Exception e)
                {
                    Fail("failed DoFinal - exception " + e.ToString());
                }

                if (result.Length != len)
                {
                    Fail("failed length");
                }

                for (int i = 0; i != len; i++)
                {
                    if (outBytes[i] != result[i])
                    {
                        Fail("failed comparison");
                    }
                }
            }
Ejemplo n.º 14
0
        public override void PerformTest()
        {
            BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(new DesEngine()));
            SimpleTest test = new PbeTest(this, 0, cipher, sample1, 64);

            test.PerformTest();

            cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(new DesEdeEngine()));
            test = new PbeTest(this, 1, cipher, sample2, 192);

            test.PerformTest();

            cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(new RC2Engine()));
            test = new PbeTest(this, 2, cipher, sample3, 0);

            test.PerformTest();

            //
            // RFC 3211 tests
            //
            char[] password = "******".ToCharArray();
            PbeParametersGenerator generator = new Pkcs5S2ParametersGenerator();

            byte[] salt = Hex.Decode("1234567878563412");

            generator.Init(
                PbeParametersGenerator.Pkcs5PasswordToBytes(password),
                salt,
                5);

            if (!AreEqual(((KeyParameter)generator.GenerateDerivedParameters("DES", 64)).GetKey(),
                Hex.Decode("d1daa78615f287e6")))
            {
                Fail("64 test failed");
            }

            password = "******".ToCharArray();

            generator.Init(
                PbeParametersGenerator.Pkcs5PasswordToBytes(password),
                salt,
                500);

            if (!AreEqual(((KeyParameter)generator.GenerateDerivedParameters("DESEDE", 192)).GetKey(),
                Hex.Decode("6a8970bf68c92caea84a8df28510858607126380cc47ab2d")))
            {
                Fail("192 test failed");
            }

            generator.Init(PbeParametersGenerator.Pkcs5PasswordToBytes(password), salt, 60000);
            if (!AreEqual(((KeyParameter)generator.GenerateDerivedParameters("DESEDE", 192)).GetKey(),
                Hex.Decode("29aaef810c12ecd2236bbcfb55407f9852b5573dc1c095bb")))
            {
                Fail("192 (60000) test failed");
            }
        }
Ejemplo n.º 15
0
		/// <summary>
		/// Simple Decryption and Authentication of a UTF8 message
		/// using a key derived from a password
		/// </summary>
		/// <param name="encryptedMessage">The encrypted message.</param>
		/// <param name="password">The password.</param>
		/// <param name="nonSecretPayloadLength">Length of the non secret payload.</param>
		/// <returns>
		/// Decrypted Message
		/// </returns>
		/// <exception cref="System.ArgumentException">Must have a password of minimum length;password</exception>
		/// <remarks>
		/// Significantly less secure than using random binary keys.
		/// </remarks>
		public static byte[] SimpleDecryptWithPassword(byte[] encryptedMessage, string password, int nonSecretPayloadLength = 0)
		{
			//User Error Checks
			if (string.IsNullOrWhiteSpace(password) || password.Length < MinPasswordLength)
				throw new ArgumentException(String.Format("Must have a password of at least {0} characters!", MinPasswordLength), "password");

			if (encryptedMessage == null || encryptedMessage.Length == 0)
				throw new ArgumentException("Encrypted Message Required!", "encryptedMessage");

			var generator = new Pkcs5S2ParametersGenerator();

			//Grab Salt from Payload
			var salt = new byte[SaltBitSize / 8];
			Array.Copy(encryptedMessage, nonSecretPayloadLength, salt, 0, salt.Length);

			generator.Init(
				PbeParametersGenerator.Pkcs5PasswordToBytes(password.ToCharArray()),
				salt,
				Iterations);

			//Generate Key
			var key = (KeyParameter)generator.GenerateDerivedMacParameters(KeyBitSize);

			return SimpleDecrypt(encryptedMessage, key.GetKey(), salt.Length + nonSecretPayloadLength);
		}
Ejemplo n.º 16
0
        /// <summary>
        /// Gets the derived bytes using the store's parameters
        /// </summary>
        /// <param name="length">The length.</param>
        /// <param name="passwordPrompt">The password prompt.</param>
        /// <returns></returns>
        /// <exception cref="InvalidKeySetException">Hmac_Sha256 not supported.</exception>
        protected byte[] GetDerivedBytes(int length, Func<string> passwordPrompt)
        {
            PbeParametersGenerator pdb;
            if (Hmac == PbeHashType.HmacSha1)
            {
                pdb = new Pkcs5S2ParametersGenerator();
                pdb.Init(PbeParametersGenerator.Pkcs5PasswordToBytes(passwordPrompt().ToCharArray()), Salt,
                         IterationCount);
            }
            else if (Hmac == PbeHashType.HmacSha256)
            {
                throw new InvalidKeySetException("Hmac_Sha256 not supported.");
            }
            else
            {
                throw new InvalidKeySetException("Unknown Pbe Cipher");
            }

            var key = (KeyParameter) pdb.GenerateDerivedMacParameters(length*8);
            return key.GetKey();
        }
Ejemplo n.º 17
0
		/// <summary>
		/// Generate an AES key using a given password and salt.
		/// </summary>
		/// <param name="password">The password to be used to create the key.</param>
		/// <param name="salt">The 32 byte long array to be used to create the key.</param>
		public void GenerateKey(string password, byte[] salt)
		{
			Pkcs5S2ParametersGenerator generator = new Pkcs5S2ParametersGenerator();

			byte[] passwordBytes = Pkcs5S2ParametersGenerator.Pkcs5PasswordToUtf8Bytes(password.ToCharArray());
			generator.Init(passwordBytes, salt, 20000);
			aes_key = (KeyParameter) generator.GenerateDerivedMacParameters(AES_256);
		}
Ejemplo n.º 18
0
		/// <summary>
		/// Generate an AES key. A key generated by this method would typically be
		/// encrypted using RSA and sent to the recipient along with data that was
		/// encrypted with the key. The recipient would then decrypt the key using
		/// RSA then use the key to decrypt the data.
		/// </summary>
		public void GenerateKey()
		{
			Pkcs5S2ParametersGenerator generator = new Pkcs5S2ParametersGenerator();

			SecureRandom random = new SecureRandom();
			byte[] password = new byte[SALT_SIZE];
			random.NextBytes(password);

			generator.Init(password, GenerateSalt(), 20000);
			aes_key = (KeyParameter) generator.GenerateDerivedMacParameters(AES_256);
		}
Ejemplo n.º 19
0
        /// <summary>
        /// Computes the PBKDF2-SHA256 hash of a password.
        /// </summary>
        /// <param name="password">The password to hash.</param>
        /// <param name="salt">The salt.</param>
        /// <param name="iterations">The PBKDF2 iteration count.</param>
        /// <param name="outputBytes">The length in bytes of the hash to
        /// generate.</param>
        /// <returns>A hash of the password.</returns>
        private static byte[] PBKDF2(string password, byte[] salt,
            uint iterations, int outputBytes)
        {
            Pkcs5S2ParametersGenerator gen =
                new Pkcs5S2ParametersGenerator(new Sha256Digest());

            gen.Init(PbeParametersGenerator.Pkcs5PasswordToBytes(
                password.ToCharArray()), salt, Iterations);

            KeyParameter key = (KeyParameter) gen
                .GenerateDerivedMacParameters(HashByteSize * 8);

            return key.GetKey();
        }