/// <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)); }
/// <summary> /// 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="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> private static byte[] EncryptWithPassword(byte[] secretMessage, string password, byte[] nonSecretPayload = null) { nonSecretPayload = nonSecretPayload ?? new byte[] { }; 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(Encrypt(secretMessage, key.GetKey(), payload)); }
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($"Must have a password of at least {MinPasswordLength} characters!", nameof(password)); } if (secretMessage == null || secretMessage.Length == 0) { throw new ArgumentException("Secret Message Required!", nameof(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)); }
/// <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> /// <returns>Encrypted Message</returns> /// <remarks>Significantly less secure than using random binary keys. /// Adds additional non secret payload for key generation parameters. /// </remarks> public static string SimpleEncryptWithPassword(string secretMessage, string password) { //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 (string.IsNullOrEmpty(secretMessage)) { 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 Non Secret Payload var payload = new byte[salt.Length]; Array.Copy(salt, payload, salt.Length); return(SimpleEncrypt(secretMessage, key.GetKey(), payload)); }
internal override KeyParameter GetEncoded(string algorithmOid) { Pkcs5S2ParametersGenerator pkcs5S2ParametersGenerator = new Pkcs5S2ParametersGenerator(); pkcs5S2ParametersGenerator.Init(PbeParametersGenerator.Pkcs5PasswordToBytes(password), salt, iterationCount); return((KeyParameter)pkcs5S2ParametersGenerator.GenerateDerivedParameters(algorithmOid, CmsEnvelopedHelper.Instance.GetKeySize(algorithmOid))); }
public override void PerformTest() { byte[] salt = new byte[16]; int iCount = 100; for (int i = 0; i != salt.Length; i++) { salt[i] = (byte)i; } PbeParametersGenerator pGen = new OpenSslPbeParametersGenerator(); pGen.Init( PbeParametersGenerator.Pkcs5PasswordToBytes(password), salt, iCount); ParametersWithIV parameters = (ParametersWithIV) pGen.GenerateDerivedParameters(baseAlgorithm, keySize, ivSize); KeyParameter encKey = (KeyParameter)parameters.Parameters; IBufferedCipher c; if (baseAlgorithm.Equals("RC4")) { c = CipherUtilities.GetCipher(baseAlgorithm); c.Init(true, encKey); } else { c = CipherUtilities.GetCipher(baseAlgorithm + "/CBC/PKCS7Padding"); c.Init(true, parameters); } byte[] enc = c.DoFinal(salt); c = CipherUtilities.GetCipher(algorithm); // PBEKeySpec keySpec = new PBEKeySpec(password, salt, iCount); // SecretKeyFactory fact = SecretKeyFactory.getInstance(algorithm); // // c.Init(false, fact.generateSecret(keySpec)); Asn1Encodable algParams = PbeUtilities.GenerateAlgorithmParameters( algorithm, salt, iCount); ICipherParameters cipherParams = PbeUtilities.GenerateCipherParameters( algorithm, password, algParams); c.Init(false, cipherParams); byte[] dec = c.DoFinal(enc); if (!AreEqual(salt, dec)) { Fail("" + algorithm + "failed encryption/decryption test"); } }
public static KeyParameter Pkcs5Pbkdf2Hmac(string password, string salt = "Yubico", int iterationCount = 10000, int keySize = 256) { var pbkdf2 = new Pkcs5S2ParametersGenerator(new Sha256Digest()); pbkdf2.Init(PbeParametersGenerator.Pkcs5PasswordToBytes(password.ToCharArray()), Encoding.UTF8.GetBytes(salt), iterationCount); return((KeyParameter)pbkdf2.GenerateDerivedMacParameters(keySize)); }
/// <summary> /// Generates a password hash using the <see cref="IDigest"/> and a salt. /// </summary> /// <param name="password"> The password to generate the hash for. </param> /// <param name="salt"> The salt to use to generate our password hash. </param> /// <param name="iterations"> The number of iterations to apply to the encryption. </param> /// <param name="hashSize"> The size of the hash. </param> /// <returns> The generated password hash as a <see langword="byte"/>[]. </returns> private byte[] GeneratePasswordHash(char[] password, byte[] salt, int iterations, int hashSize) { var generator = new Pkcs5S2ParametersGenerator(engine.PBKDF2Digest); generator.Init(PbeParametersGenerator.Pkcs5PasswordToBytes(password), salt, iterations <= MIN_ITERATIONS ? MIN_ITERATIONS : iterations); return(((KeyParameter)generator.GenerateDerivedMacParameters((hashSize <= MIN_HASH_SIZE ? MIN_HASH_SIZE : hashSize) * 8)).GetKey()); }
/// <summary> /// Gets a PBKDF2_SHA256 Hash (CORE METHOD) /// </summary> /// <param name="password">The password as a plain text string</param> /// <param name="salt">The salt as a byte array</param> /// <returns>A the hash as a byte array.</returns> public static byte[] PBKDF2_SHA256_GetHash(string str, byte[] salt) { var pdb = new Pkcs5S2ParametersGenerator(new Org.BouncyCastle.Crypto.Digests.Sha256Digest()); pdb.Init(PbeParametersGenerator.Pkcs5PasswordToBytes(str.ToCharArray()), salt, iterations); var key = (KeyParameter)pdb.GenerateDerivedMacParameters(hashByteSize * 8); return(key.GetKey()); }
internal override byte[] GetEncoded( string algorithmOid) { Pkcs5S2ParametersGenerator gen = new Pkcs5S2ParametersGenerator(); gen.Init(PbeParametersGenerator.Pkcs5PasswordToBytes(this.Password), this.GetSalt(), this.IterationCount); return(((KeyParameter)gen.GenerateDerivedParameters(CmsEnvelopedHelper.Instance.GetKeySize(algorithmOid))).GetKey()); }
internal static byte[] ComputePbkdf2(string password, byte[] salt, int iterations, int hashByteSize) { var pdb = new Pkcs5S2ParametersGenerator(new Sha256Digest()); pdb.Init(PbeParametersGenerator.Pkcs5PasswordToBytes(password.ToCharArray()), salt, iterations); var key = (KeyParameter)pdb.GenerateDerivedMacParameters(hashByteSize * 8); return(key.GetKey()); }
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"); } }
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); }
/// <summary> /// Generates the key. /// </summary> /// <param name="user_iden">The user iden.</param> /// <param name="password">The password.</param> /// <returns></returns> public static string GenerateKey(string user_iden, string password) { var keyLength = 32; var iterations = 30000; var saltBytes = Encoding.UTF8.GetBytes(user_iden); var pdb = new Pkcs5S2ParametersGenerator(new Org.BouncyCastle.Crypto.Digests.Sha256Digest()); pdb.Init(PbeParametersGenerator.Pkcs5PasswordToBytes(password.ToCharArray()), saltBytes, iterations); var key = (KeyParameter)pdb.GenerateDerivedMacParameters(keyLength * 8); return(Convert.ToBase64String(key.GetKey())); }
public string Hash(string password) { try { var pdb = new Pkcs5S2ParametersGenerator(new Org.BouncyCastle.Crypto.Digests.Sha512Digest()); pdb.Init(PbeParametersGenerator.Pkcs5PasswordToBytes(password.ToCharArray()), Encoding.UTF8.GetBytes(salt), iterations); var key = (KeyParameter)pdb.GenerateDerivedMacParameters(hashByteSize * 8); return(Convert.ToBase64String(key.GetKey())); } catch { return(password); } }
/// <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> /// <returns>Encrypted Message</returns> /// <remarks>Significantly less secure than using random binary keys. /// Adds additional non secret payload for key generation parameters. /// </remarks> public static string SimpleEncryptWithPassword(string secretMessage, string password) { //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 (string.IsNullOrEmpty(secretMessage)) { 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); //iterations are not secret, nor does it need to change randomly //I'm just using random data because i prefer the non-secret payload looking //like random data var iters = new byte[8]; Random.NextBytes(iters); var m = Math.Abs(BitConverter.ToInt32(iters, 0)) % 10; var a = Math.Abs(BitConverter.ToInt32(iters, 4)) % 10000; var iterations = 1000 * m + a + 5000; generator.Init( PbeParametersGenerator.Pkcs5PasswordToBytes(password.ToCharArray()), salt, iterations); //Generate Key var key = (KeyParameter)generator.GenerateDerivedMacParameters(KeyBitSize); //Create Non Secret Payload var payload = new byte[salt.Length + iters.Length]; Array.Copy(salt, payload, salt.Length); Array.Copy(iters, 0, payload, salt.Length, iters.Length); return(SimpleEncrypt(secretMessage, key.GetKey(), payload)); }
/// <summary> /// 获取用户密钥 /// </summary> /// <param name="key"></param> /// <param name="utf8"></param> /// <returns></returns> private byte[] GetUserKey(string key, bool utf8) { if (string.IsNullOrWhiteSpace(key)) { return(null); } var gen = new Pkcs5S2ParametersGenerator(); var bytes = utf8 ? PbeParametersGenerator.Pkcs5PasswordToUtf8Bytes(key.ToCharArray()) : PbeParametersGenerator.Pkcs5PasswordToBytes(key.ToCharArray()); gen.Init(bytes, header.UserSalt, header.Rounds); var param = (KeyParameter)gen.GenerateDerivedParameters("AES256", AbHeader.PBKDF2_KEY_SIZE); var userKey = param.GetKey(); return(userKey); }
public static byte[] androidPBKDF2(char[] pwArray, byte[] salt, int rounds, bool useUtf8) { PbeParametersGenerator generator = new Pkcs5S2ParametersGenerator(); // Android treats password bytes as ASCII, which is obviously // not the case when an AES key is used as a 'password'. // Use the same method for compatibility. // Android 4.4 however uses all char bytes // useUtf8 needs to be true for KitKat byte[] pwBytes = useUtf8 ? PbeParametersGenerator.Pkcs5PasswordToUtf8Bytes(pwArray) : PbeParametersGenerator.Pkcs5PasswordToBytes(pwArray); generator.Init(pwBytes, salt, rounds); KeyParameter param = (KeyParameter)generator.GenerateDerivedParameters("AES256", PBKDF2_KEY_SIZE); return(param.GetKey()); //return new byte[])(params.getKey(), "AES"); }
public string Encrypt(string strToEncrypt, string passPhrase) { var plainText = Encoding.UTF8.GetBytes(strToEncrypt); var generator = new Pkcs5S2ParametersGenerator(); var salt = new byte[SaltBitSize / 8]; Random.NextBytes(salt); generator.Init( PbeParametersGenerator.Pkcs5PasswordToBytes(passPhrase.ToCharArray()), salt, Iterations); var key = (KeyParameter)generator.GenerateDerivedMacParameters(KeyBitSize); var nonSecretPayload = new byte[] { }; var payload = new byte[salt.Length]; Array.Copy(nonSecretPayload, payload, nonSecretPayload.Length); Array.Copy(salt, 0, payload, nonSecretPayload.Length, salt.Length); var nonce = new byte[NonceBitSize / 8]; Random.NextBytes(nonce, 0, nonce.Length); var cipher = new GcmBlockCipher(new AesEngine()); var parameters = new AeadParameters( new KeyParameter(key.GetKey()), MacBitSize, nonce, payload); cipher.Init(true, parameters); var cipherText = new byte[cipher.GetOutputSize(plainText.Length)]; var len = cipher.ProcessBytes(plainText, 0, plainText.Length, cipherText, 0); cipher.DoFinal(cipherText, len); using var combinedStream = new MemoryStream(); using var binaryWriter = new BinaryWriter(combinedStream); binaryWriter.Write(payload); binaryWriter.Write(nonce); binaryWriter.Write(cipherText); return(Convert.ToBase64String(combinedStream.ToArray())); }
/// <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="ArgumentException">Must have a password of minimum length;password</exception> /// <remarks> /// Significantly less secure than using random binary keys. /// </remarks> private static byte[] DecryptWithPassword(byte[] encryptedMessage, string password, int nonSecretPayloadLength = 0) { 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(Decrypt(encryptedMessage, key.GetKey(), salt.Length + nonSecretPayloadLength)); }
private static ICipherParameters GetCipherParameters( char[] password, string baseAlg, byte[] salt) { string algorithm; int keyBits; switch (baseAlg) { case "AES-128": keyBits = 128; algorithm = "AES128"; break; case "AES-192": keyBits = 192; algorithm = "AES192"; break; case "AES-256": keyBits = 256; algorithm = "AES256"; break; case "BF": keyBits = 128; algorithm = "BLOWFISH"; break; case "DES": keyBits = 64; algorithm = "DES"; break; case "DES-EDE": keyBits = 128; algorithm = "DESEDE"; break; case "DES-EDE3": keyBits = 192; algorithm = "DESEDE3"; break; case "RC2": keyBits = 128; algorithm = "RC2"; break; case "RC2-40": keyBits = 40; algorithm = "RC2"; break; case "RC2-64": keyBits = 64; algorithm = "RC2"; break; default: return(null); } OpenSslPbeParametersGenerator pGen = new OpenSslPbeParametersGenerator(); pGen.Init(PbeParametersGenerator.Pkcs5PasswordToBytes(password), salt); return(pGen.GenerateDerivedParameters(algorithm, keyBits)); }
private static ICipherParameters GetCipherParameters( char[] password, PemBaseAlg baseAlg, byte[] salt) { string algorithm; int keyBits; switch (baseAlg) { case PemBaseAlg.AES_128: keyBits = 128; algorithm = "AES128"; break; case PemBaseAlg.AES_192: keyBits = 192; algorithm = "AES192"; break; case PemBaseAlg.AES_256: keyBits = 256; algorithm = "AES256"; break; case PemBaseAlg.BF: keyBits = 128; algorithm = "BLOWFISH"; break; case PemBaseAlg.DES: keyBits = 64; algorithm = "DES"; break; case PemBaseAlg.DES_EDE: keyBits = 128; algorithm = "DESEDE"; break; case PemBaseAlg.DES_EDE3: keyBits = 192; algorithm = "DESEDE3"; break; case PemBaseAlg.RC2: keyBits = 128; algorithm = "RC2"; break; case PemBaseAlg.RC2_40: keyBits = 40; algorithm = "RC2"; break; case PemBaseAlg.RC2_64: keyBits = 64; algorithm = "RC2"; break; default: return(null); } OpenSslPbeParametersGenerator pGen = new OpenSslPbeParametersGenerator(); pGen.Init(PbeParametersGenerator.Pkcs5PasswordToBytes(password), salt); return(pGen.GenerateDerivedParameters(algorithm, keyBits)); }
/// <summary> /// To encrypt, plain data /// </summary> /// <param name="secretMessage">Data to encrypt</param> /// <param name="password">Password for encrypting</param> /// <param name="nonSecretPayload">nonSecretPayload for encryption</param> /// <returns>Returns encrypted data</returns> public static byte[] Encrypt(byte[] secretMessage, SecureString password = null, byte[] nonSecretPayload = null) { nonSecretPayload = nonSecretPayload ?? new byte[] { }; if (password == null) { password = Security.Generator.HWID; } ////User Error Checks if (password.IsNullOrWhiteSpace() || password.UnsecureString().Length < MinPasswordLength) { throw new ArgumentException(string.Format("Must have a password of at least {0} characters!", MinPasswordLength), "password"); } if (secretMessage == null || secretMessage.Length == 0) { return(null); } 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.UnsecureString().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(Encrypt(secretMessage, key.GetKey(), payload)); }
/// <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()); }
/** * create the secret key needed for this object, fetching the password */ private ICipherParameters GetKey( string algorithm, int keyLength, byte[] salt) { if (pFinder == null) { throw new InvalidOperationException("No password finder specified, but a password is required"); } char[] password = pFinder.GetPassword(); if (password == null) { throw new IOException("Password is null, but a password is required"); } OpenSslPbeParametersGenerator pGen = new OpenSslPbeParametersGenerator(); pGen.Init(PbeParametersGenerator.Pkcs5PasswordToBytes(password), salt); return(pGen.GenerateDerivedParameters(keyLength * 8)); }
/// <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> /// <returns>Decrypted Message</returns> /// <remarks>Significantly less secure than using random binary keys. </remarks> public static string SimpleDecryptWithPassword(string encryptedMessage, string password) { //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 (string.IsNullOrWhiteSpace(encryptedMessage)) { throw new ArgumentException("Encrypted Message Required!", "encryptedMessage"); } var generator = new Pkcs5S2ParametersGenerator(); //Grab Salt and Iterations from Payload var salt = new byte[SaltBitSize / 8]; var iters = new byte[8]; var message = Convert.FromBase64String(encryptedMessage); Array.Copy(message, salt, salt.Length); Array.Copy(message, salt.Length, iters, 0, iters.Length); var m = Math.Abs(BitConverter.ToInt32(iters, 0)) % 10; var a = Math.Abs(BitConverter.ToInt32(iters, 4)) % 10000; var iterations = 1000 * m + a + 5000; generator.Init( PbeParametersGenerator.Pkcs5PasswordToBytes(password.ToCharArray()), salt, iterations); //Generate Key var key = (KeyParameter)generator.GenerateDerivedMacParameters(KeyBitSize); return(SimpleDecrypt(encryptedMessage, key.GetKey(), salt.Length + iters.Length)); }
public string Decrypt(string strEncrypted, string passPhrase) { var cipherText = Convert.FromBase64String(strEncrypted); var generator = new Pkcs5S2ParametersGenerator(); var salt = new byte[SaltBitSize / 8]; Array.Copy(cipherText, 0, salt, 0, salt.Length); generator.Init( PbeParametersGenerator.Pkcs5PasswordToBytes(passPhrase.ToCharArray()), salt, Iterations); var key = (KeyParameter)generator.GenerateDerivedMacParameters(KeyBitSize); using var cipherStream = new MemoryStream(cipherText); using var cipherReader = new BinaryReader(cipherStream); var payload = cipherReader.ReadBytes(salt.Length); var nonce = cipherReader.ReadBytes(NonceBitSize / 8); var cipher = new GcmBlockCipher(new AesEngine()); var parameters = new AeadParameters( new KeyParameter(key.GetKey()), MacBitSize, nonce, payload); cipher.Init(false, parameters); var readBytes = cipherReader.ReadBytes(strEncrypted.Length - salt.Length - nonce.Length); var plainTextBytes = new byte[cipher.GetOutputSize(readBytes.Length)]; var len = cipher.ProcessBytes(readBytes, 0, readBytes.Length, plainTextBytes, 0); cipher.DoFinal(plainTextBytes, len); return(Encoding.UTF8.GetString(plainTextBytes)); }
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.ObjectID; 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"); } } }
public static ICipherParameters GenerateCipherParameters( string algorithm, char[] password, bool wrongPkcs12Zero, Asn1Encodable pbeParameters) { string mechanism = (string)algorithms[algorithm.ToUpper(CultureInfo.InvariantCulture)]; byte[] keyBytes = null; byte[] salt = null; int iterationCount = 0; if (IsPkcs12(mechanism)) { Pkcs12PbeParams pbeParams = Pkcs12PbeParams.GetInstance(pbeParameters); salt = pbeParams.GetIV(); iterationCount = pbeParams.Iterations.IntValue; keyBytes = PbeParametersGenerator.Pkcs12PasswordToBytes(password, wrongPkcs12Zero); } else if (IsPkcs5Scheme2(mechanism)) { // See below } else { PbeParameter pbeParams = PbeParameter.GetInstance(pbeParameters); salt = pbeParams.GetSalt(); iterationCount = pbeParams.IterationCount.IntValue; keyBytes = PbeParametersGenerator.Pkcs5PasswordToBytes(password); } ICipherParameters parameters = null; if (IsPkcs5Scheme2(mechanism)) { PbeS2Parameters s2p = PbeS2Parameters.GetInstance(pbeParameters.ToAsn1Object()); AlgorithmIdentifier encScheme = s2p.EncryptionScheme; DerObjectIdentifier encOid = encScheme.ObjectID; Asn1Object encParams = encScheme.Parameters.ToAsn1Object(); // TODO What about s2p.KeyDerivationFunc.ObjectID? Pbkdf2Params pbeParams = Pbkdf2Params.GetInstance(s2p.KeyDerivationFunc.Parameters.ToAsn1Object()); byte[] iv; if (encOid.Equals(PkcsObjectIdentifiers.RC2Cbc)) // PKCS5.B.2.3 { RC2CbcParameter rc2Params = RC2CbcParameter.GetInstance(encParams); iv = rc2Params.GetIV(); } else { iv = Asn1OctetString.GetInstance(encParams).GetOctets(); } salt = pbeParams.GetSalt(); iterationCount = pbeParams.IterationCount.IntValue; keyBytes = PbeParametersGenerator.Pkcs5PasswordToBytes(password); int keyLength = pbeParams.KeyLength != null ? pbeParams.KeyLength.IntValue * 8 : GeneratorUtilities.GetDefaultKeySize(encOid); PbeParametersGenerator gen = MakePbeGenerator( (string)algorithmType[mechanism], null, keyBytes, salt, iterationCount); parameters = gen.GenerateDerivedParameters(encOid.Id, keyLength); if (iv != null) { // FIXME? OpenSSL weirdness with IV of zeros (for ECB keys?) if (Arrays.AreEqual(iv, new byte[iv.Length])) { //Console.Error.Write("***** IV all 0 (length " + iv.Length + ") *****"); } else { parameters = new ParametersWithIV(parameters, iv); } } } else if (mechanism.StartsWith("PBEwithSHA-1")) { PbeParametersGenerator generator = MakePbeGenerator( (string)algorithmType[mechanism], new Sha1Digest(), keyBytes, salt, iterationCount); if (mechanism.Equals("PBEwithSHA-1and128bitRC4")) { parameters = generator.GenerateDerivedParameters("RC4", 128); } else if (mechanism.Equals("PBEwithSHA-1and40bitRC4")) { parameters = generator.GenerateDerivedParameters("RC4", 40); } else if (mechanism.Equals("PBEwithSHA-1and3-keyDESEDE-CBC")) { parameters = generator.GenerateDerivedParameters("DESEDE", 192, 64); } else if (mechanism.Equals("PBEwithSHA-1and2-keyDESEDE-CBC")) { parameters = generator.GenerateDerivedParameters("DESEDE", 128, 64); } else if (mechanism.Equals("PBEwithSHA-1and128bitRC2-CBC")) { parameters = generator.GenerateDerivedParameters("RC2", 128, 64); } else if (mechanism.Equals("PBEwithSHA-1and40bitRC2-CBC")) { parameters = generator.GenerateDerivedParameters("RC2", 40, 64); } else if (mechanism.Equals("PBEwithSHA-1andDES-CBC")) { parameters = generator.GenerateDerivedParameters("DES", 64, 64); } else if (mechanism.Equals("PBEwithSHA-1andRC2-CBC")) { parameters = generator.GenerateDerivedParameters("RC2", 64, 64); } else if (mechanism.Equals("PBEwithSHA-1and128bitAES-CBC-BC")) { parameters = generator.GenerateDerivedParameters("AES", 128, 128); } else if (mechanism.Equals("PBEwithSHA-1and192bitAES-CBC-BC")) { parameters = generator.GenerateDerivedParameters("AES", 192, 128); } else if (mechanism.Equals("PBEwithSHA-1and256bitAES-CBC-BC")) { parameters = generator.GenerateDerivedParameters("AES", 256, 128); } } else if (mechanism.StartsWith("PBEwithSHA-256")) { PbeParametersGenerator generator = MakePbeGenerator( (string)algorithmType[mechanism], new Sha256Digest(), keyBytes, salt, iterationCount); if (mechanism.Equals("PBEwithSHA-256and128bitAES-CBC-BC")) { parameters = generator.GenerateDerivedParameters("AES", 128, 128); } else if (mechanism.Equals("PBEwithSHA-256and192bitAES-CBC-BC")) { parameters = generator.GenerateDerivedParameters("AES", 192, 128); } else if (mechanism.Equals("PBEwithSHA-256and256bitAES-CBC-BC")) { parameters = generator.GenerateDerivedParameters("AES", 256, 128); } } else if (mechanism.StartsWith("PBEwithMD5")) { PbeParametersGenerator generator = MakePbeGenerator( (string)algorithmType[mechanism], new MD5Digest(), keyBytes, salt, iterationCount); if (mechanism.Equals("PBEwithMD5andDES-CBC")) { parameters = generator.GenerateDerivedParameters("DES", 64, 64); } else if (mechanism.Equals("PBEwithMD5andRC2-CBC")) { parameters = generator.GenerateDerivedParameters("RC2", 64, 64); } else if (mechanism.Equals("PBEwithMD5and128bitAES-CBC-OpenSSL")) { parameters = generator.GenerateDerivedParameters("AES", 128, 128); } else if (mechanism.Equals("PBEwithMD5and192bitAES-CBC-OpenSSL")) { parameters = generator.GenerateDerivedParameters("AES", 192, 128); } else if (mechanism.Equals("PBEwithMD5and256bitAES-CBC-OpenSSL")) { parameters = generator.GenerateDerivedParameters("AES", 256, 128); } } else if (mechanism.StartsWith("PBEwithMD2")) { PbeParametersGenerator generator = MakePbeGenerator( (string)algorithmType[mechanism], new MD2Digest(), keyBytes, salt, iterationCount); if (mechanism.Equals("PBEwithMD2andDES-CBC")) { parameters = generator.GenerateDerivedParameters("DES", 64, 64); } else if (mechanism.Equals("PBEwithMD2andRC2-CBC")) { parameters = generator.GenerateDerivedParameters("RC2", 64, 64); } } else if (mechanism.StartsWith("PBEwithHmac")) { string digestName = mechanism.Substring("PBEwithHmac".Length); IDigest digest = DigestUtilities.GetDigest(digestName); PbeParametersGenerator generator = MakePbeGenerator( (string)algorithmType[mechanism], digest, keyBytes, salt, iterationCount); int bitLen = digest.GetDigestSize() * 8; parameters = generator.GenerateDerivedMacParameters(bitLen); } Array.Clear(keyBytes, 0, keyBytes.Length); return(FixDesParity(mechanism, parameters)); }
public static ICipherParameters GenerateCipherParameters(string algorithm, char[] password, bool wrongPkcs12Zero, Asn1Encodable pbeParameters) { string text = (string)algorithms.get_Item((object)Platform.ToUpperInvariant(algorithm)); byte[] array = null; byte[] salt = null; int iterationCount = 0; if (IsPkcs12(text)) { Pkcs12PbeParams instance = Pkcs12PbeParams.GetInstance(pbeParameters); salt = instance.GetIV(); iterationCount = instance.Iterations.IntValue; array = PbeParametersGenerator.Pkcs12PasswordToBytes(password, wrongPkcs12Zero); } else if (!IsPkcs5Scheme2(text)) { PbeParameter instance2 = PbeParameter.GetInstance(pbeParameters); salt = instance2.GetSalt(); iterationCount = instance2.IterationCount.IntValue; array = PbeParametersGenerator.Pkcs5PasswordToBytes(password); } ICipherParameters parameters = null; if (IsPkcs5Scheme2(text)) { PbeS2Parameters instance3 = PbeS2Parameters.GetInstance(pbeParameters.ToAsn1Object()); AlgorithmIdentifier encryptionScheme = instance3.EncryptionScheme; DerObjectIdentifier algorithm2 = encryptionScheme.Algorithm; Asn1Object obj = encryptionScheme.Parameters.ToAsn1Object(); Pbkdf2Params instance4 = Pbkdf2Params.GetInstance(instance3.KeyDerivationFunc.Parameters.ToAsn1Object()); byte[] array2; if (algorithm2.Equals(PkcsObjectIdentifiers.RC2Cbc)) { RC2CbcParameter instance5 = RC2CbcParameter.GetInstance(obj); array2 = instance5.GetIV(); } else { array2 = Asn1OctetString.GetInstance(obj).GetOctets(); } salt = instance4.GetSalt(); iterationCount = instance4.IterationCount.IntValue; array = PbeParametersGenerator.Pkcs5PasswordToBytes(password); int keySize = ((instance4.KeyLength != null) ? (instance4.KeyLength.IntValue * 8) : GeneratorUtilities.GetDefaultKeySize(algorithm2)); PbeParametersGenerator pbeParametersGenerator = MakePbeGenerator((string)algorithmType.get_Item((object)text), null, array, salt, iterationCount); parameters = pbeParametersGenerator.GenerateDerivedParameters(algorithm2.Id, keySize); if (array2 != null && !Arrays.AreEqual(array2, new byte[array2.Length])) { parameters = new ParametersWithIV(parameters, array2); } } else if (Platform.StartsWith(text, "PBEwithSHA-1")) { PbeParametersGenerator pbeParametersGenerator2 = MakePbeGenerator((string)algorithmType.get_Item((object)text), new Sha1Digest(), array, salt, iterationCount); if (text.Equals("PBEwithSHA-1and128bitAES-CBC-BC")) { parameters = pbeParametersGenerator2.GenerateDerivedParameters("AES", 128, 128); } else if (text.Equals("PBEwithSHA-1and192bitAES-CBC-BC")) { parameters = pbeParametersGenerator2.GenerateDerivedParameters("AES", 192, 128); } else if (text.Equals("PBEwithSHA-1and256bitAES-CBC-BC")) { parameters = pbeParametersGenerator2.GenerateDerivedParameters("AES", 256, 128); } else if (text.Equals("PBEwithSHA-1and128bitRC4")) { parameters = pbeParametersGenerator2.GenerateDerivedParameters("RC4", 128); } else if (text.Equals("PBEwithSHA-1and40bitRC4")) { parameters = pbeParametersGenerator2.GenerateDerivedParameters("RC4", 40); } else if (text.Equals("PBEwithSHA-1and3-keyDESEDE-CBC")) { parameters = pbeParametersGenerator2.GenerateDerivedParameters("DESEDE", 192, 64); } else if (text.Equals("PBEwithSHA-1and2-keyDESEDE-CBC")) { parameters = pbeParametersGenerator2.GenerateDerivedParameters("DESEDE", 128, 64); } else if (text.Equals("PBEwithSHA-1and128bitRC2-CBC")) { parameters = pbeParametersGenerator2.GenerateDerivedParameters("RC2", 128, 64); } else if (text.Equals("PBEwithSHA-1and40bitRC2-CBC")) { parameters = pbeParametersGenerator2.GenerateDerivedParameters("RC2", 40, 64); } else if (text.Equals("PBEwithSHA-1andDES-CBC")) { parameters = pbeParametersGenerator2.GenerateDerivedParameters("DES", 64, 64); } else if (text.Equals("PBEwithSHA-1andRC2-CBC")) { parameters = pbeParametersGenerator2.GenerateDerivedParameters("RC2", 64, 64); } } else if (Platform.StartsWith(text, "PBEwithSHA-256")) { PbeParametersGenerator pbeParametersGenerator3 = MakePbeGenerator((string)algorithmType.get_Item((object)text), new Sha256Digest(), array, salt, iterationCount); if (text.Equals("PBEwithSHA-256and128bitAES-CBC-BC")) { parameters = pbeParametersGenerator3.GenerateDerivedParameters("AES", 128, 128); } else if (text.Equals("PBEwithSHA-256and192bitAES-CBC-BC")) { parameters = pbeParametersGenerator3.GenerateDerivedParameters("AES", 192, 128); } else if (text.Equals("PBEwithSHA-256and256bitAES-CBC-BC")) { parameters = pbeParametersGenerator3.GenerateDerivedParameters("AES", 256, 128); } } else if (Platform.StartsWith(text, "PBEwithMD5")) { PbeParametersGenerator pbeParametersGenerator4 = MakePbeGenerator((string)algorithmType.get_Item((object)text), new MD5Digest(), array, salt, iterationCount); if (text.Equals("PBEwithMD5andDES-CBC")) { parameters = pbeParametersGenerator4.GenerateDerivedParameters("DES", 64, 64); } else if (text.Equals("PBEwithMD5andRC2-CBC")) { parameters = pbeParametersGenerator4.GenerateDerivedParameters("RC2", 64, 64); } else if (text.Equals("PBEwithMD5and128bitAES-CBC-OpenSSL")) { parameters = pbeParametersGenerator4.GenerateDerivedParameters("AES", 128, 128); } else if (text.Equals("PBEwithMD5and192bitAES-CBC-OpenSSL")) { parameters = pbeParametersGenerator4.GenerateDerivedParameters("AES", 192, 128); } else if (text.Equals("PBEwithMD5and256bitAES-CBC-OpenSSL")) { parameters = pbeParametersGenerator4.GenerateDerivedParameters("AES", 256, 128); } } else if (Platform.StartsWith(text, "PBEwithMD2")) { PbeParametersGenerator pbeParametersGenerator5 = MakePbeGenerator((string)algorithmType.get_Item((object)text), new MD2Digest(), array, salt, iterationCount); if (text.Equals("PBEwithMD2andDES-CBC")) { parameters = pbeParametersGenerator5.GenerateDerivedParameters("DES", 64, 64); } else if (text.Equals("PBEwithMD2andRC2-CBC")) { parameters = pbeParametersGenerator5.GenerateDerivedParameters("RC2", 64, 64); } } else if (Platform.StartsWith(text, "PBEwithHmac")) { string algorithm3 = text.Substring("PBEwithHmac".get_Length()); IDigest digest = DigestUtilities.GetDigest(algorithm3); PbeParametersGenerator pbeParametersGenerator6 = MakePbeGenerator((string)algorithmType.get_Item((object)text), digest, array, salt, iterationCount); int keySize2 = digest.GetDigestSize() * 8; parameters = pbeParametersGenerator6.GenerateDerivedMacParameters(keySize2); } global::System.Array.Clear((global::System.Array)array, 0, array.Length); return(FixDesParity(text, parameters)); }