Exemplo n.º 1
0
        } // End Function PBKDF2

        // https://stackoverflow.com/questions/21565369/how-to-encrypt-and-salt-the-password-using-bouncycastle-api-in-java
        // Password-Based Key Derivation Function
        // PBKDF1 and PBKDF2
        public static void PBKDF2(string passwordToSave, string passwordToCheck)
        {
            // tuning parameters

            // these sizes are relatively arbitrary
            int seedBytes = 20;
            int hashBytes = 20;

            // increase iterations as high as your performance can tolerate
            // since this increases computational cost of password guessing
            // which should help security
            int iterations = 1000;

            // to save a new password:

            Org.BouncyCastle.Security.SecureRandom rng = new Org.BouncyCastle.Security.SecureRandom();


            byte[] salt = rng.GenerateSeed(seedBytes);

            Org.BouncyCastle.Crypto.Generators.Pkcs5S2ParametersGenerator kdf = new Org.BouncyCastle.Crypto.Generators.Pkcs5S2ParametersGenerator();
            kdf.Init(System.Text.Encoding.UTF8.GetBytes(passwordToSave), salt, iterations);

            byte[] hash =
                ((Org.BouncyCastle.Crypto.Parameters.KeyParameter)kdf.GenerateDerivedMacParameters(8 * hashBytes)).GetKey();

            // now save salt and hash

            // to check a password, given the known previous salt and hash:

            kdf = new Org.BouncyCastle.Crypto.Generators.Pkcs5S2ParametersGenerator();
            kdf.Init(System.Text.Encoding.UTF8.GetBytes(passwordToCheck), salt, iterations);

            byte[] hashToCheck =
                ((Org.BouncyCastle.Crypto.Parameters.KeyParameter)kdf.GenerateDerivedMacParameters(8 * hashBytes)).GetKey();

            // if the bytes of hashToCheck don't match the bytes of hash
            // that means the password is invalid
        } // End Function PBKDF2