//http://stackoverflow.com/questions/34950611/how-to-create-a-pbkdf2-sha256-password-hash-in-c-sharp-bouncy-castle// public byte[] GeneratePbkdf2Sha256DerivedKey(string password, byte[] salt, int count, int dklen) { var pdb = new Pkcs5S2ParametersGenerator(new Sha256Digest()); //note Pkcs5PasswordToUtf8Bytes is the same as Encoding.UTF8.GetBytes(password) //changing it to keep it as bouncy pdb.Init(PbeParametersGenerator.Pkcs5PasswordToUtf8Bytes(password.ToCharArray()), salt, count); //if dklen == 32, then it is 256 (8 * 32) var key = (KeyParameter)pdb.GenerateDerivedMacParameters(8 * dklen); return(key.GetKey()); }
internal override KeyParameter GetEncoded( string algorithmOid) { Pkcs5S2ParametersGenerator gen = new Pkcs5S2ParametersGenerator(); gen.Init( PbeParametersGenerator.Pkcs5PasswordToBytes(password), salt, iterationCount); return((KeyParameter)gen.GenerateDerivedParameters( algorithmOid, CmsEnvelopedHelper.Instance.GetKeySize(algorithmOid))); }
/// <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())); }
private void Run2(int id, char[] password, byte[] salt, int iCount, byte[] result) { PbeParametersGenerator generator = new Pkcs12ParametersGenerator(new Sha1Digest()); generator.Init(PbeParametersGenerator.Pkcs12PasswordToBytes(password), salt, iCount); ParametersWithIV parameters = (ParametersWithIV) generator.GenerateDerivedParameters("DES", 64, 64); if (!Arrays.AreEqual(result, parameters.GetIV())) { Fail("id " + id + " Failed"); } }
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"); } }
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> /// 获取用户密钥 /// </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); }
/// <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)); }
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)); }
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)); }
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)); }
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)); }
/// <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 void WriteObject( object obj, string algorithm, char[] password, SecureRandom random) { if (obj == null) { throw new ArgumentNullException("obj"); } if (algorithm == null) { throw new ArgumentNullException("algorithm"); } if (password == null) { throw new ArgumentNullException("password"); } if (random == null) { throw new ArgumentNullException("random"); } byte[] keyData = null; if (obj is RsaPrivateCrtKeyParameters) { RsaPrivateCrtKeyParameters k = (RsaPrivateCrtKeyParameters)obj; keyData = PrivateKeyInfoFactory.CreatePrivateKeyInfo(k).PrivateKey.GetEncoded(); } else { // TODO Support other types? throw new ArgumentException("Object type not supported: " + obj.GetType().FullName, "obj"); } byte[] salt = new byte[8]; random.NextBytes(salt); OpenSslPbeParametersGenerator pGen = new OpenSslPbeParametersGenerator(); pGen.Init(PbeParametersGenerator.Pkcs5PasswordToBytes(password), salt); ICipherParameters secretKey = null; if (algorithm.ToUpper(CultureInfo.InvariantCulture).Equals("DESEDE")) { // generate key int keyLength = 24; secretKey = pGen.GenerateDerivedParameters(keyLength * 8); } else { throw new IOException("unknown algorithm in WriteObject"); } byte[] encData = null; // cipher try { IBufferedCipher c = CipherUtilities.GetCipher("DESede/CBC/PKCS5Padding"); c.Init(true, new ParametersWithIV(secretKey, salt)); encData = c.DoFinal(keyData); } catch (Exception e) { throw new IOException("exception using cipher: " + e.ToString()); } // write the data string type = "RSA PRIVATE KEY"; WriteHeader(type); writer.WriteLine("Proc-Type: 4,ENCRYPTED"); writer.Write("DEK-Info: DES-EDE3-CBC,"); WriteHexEncoded(salt); writer.WriteLine(); WriteBase64Encoded(encData); WriteFooter(type); }
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)); }
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 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 string DemonstrateStringEncryptionKeyBased(string plainText) { #region INITIALIZATION AesCryptoServiceProvider crypto = new AesCryptoServiceProvider { KeySize = 256 }; crypto.GenerateKey(); string randomKey = Convert.ToBase64String(crypto.Key); #endregion #region ENCRYPTION SecureRandom Random = new SecureRandom(); byte[] dataForEncryption = Encoding.UTF8.GetBytes(plainText); Pkcs5S2ParametersGenerator pkcs5S2ParametersGenerator = new Pkcs5S2ParametersGenerator(); byte[] salt = new byte[16]; Random.NextBytes(salt); pkcs5S2ParametersGenerator.Init(PbeParametersGenerator.Pkcs5PasswordToBytes(randomKey.ToCharArray()), salt, 10000); KeyParameter key = (KeyParameter)pkcs5S2ParametersGenerator.GenerateDerivedMacParameters(256); byte[] nonce = new byte[16]; Random.NextBytes(nonce); GcmBlockCipher gcmBlockCipher = new GcmBlockCipher(new AesEngine()); AeadParameters aeadParameters = new AeadParameters(new KeyParameter(key.GetKey()), 128, nonce, salt); gcmBlockCipher.Init(true, aeadParameters); //Generate ciphertext with authentication tag. byte[] cipherTextAsByteArray = new byte[gcmBlockCipher.GetOutputSize(dataForEncryption.Length)]; int length = gcmBlockCipher.ProcessBytes(dataForEncryption, 0, dataForEncryption.Length, cipherTextAsByteArray, 0); gcmBlockCipher.DoFinal(cipherTextAsByteArray, length); byte[] cipherTextBytes; // PREPEND SALT AND NONCE using (MemoryStream memoryStream = new MemoryStream()) { using (BinaryWriter binaryWriter = new BinaryWriter(memoryStream)) { binaryWriter.Write(salt); binaryWriter.Write(nonce); binaryWriter.Write(cipherTextAsByteArray); } cipherTextBytes = memoryStream.ToArray(); } string cipherText = Convert.ToBase64String(cipherTextBytes); #endregion #region DECRYPTION byte[] encryptedMessageAsByteArray = Convert.FromBase64String(cipherText); salt = new byte[16]; Array.Copy(encryptedMessageAsByteArray, salt, salt.Length); pkcs5S2ParametersGenerator.Init(PbeParametersGenerator.Pkcs5PasswordToBytes(randomKey.ToCharArray()), salt, 10000); using (BinaryReader binaryReader = new BinaryReader(new MemoryStream(encryptedMessageAsByteArray))) { salt = binaryReader.ReadBytes(salt.Length); nonce = binaryReader.ReadBytes(16); gcmBlockCipher = new GcmBlockCipher(new AesEngine()); aeadParameters = new AeadParameters(new KeyParameter(key.GetKey()), 128, nonce, salt); gcmBlockCipher.Init(false, aeadParameters); cipherTextAsByteArray = binaryReader.ReadBytes(encryptedMessageAsByteArray.Length - salt.Length - nonce.Length); byte[] decryptedTextAsByteArray = new byte[gcmBlockCipher.GetOutputSize(cipherTextAsByteArray.Length)]; // CHECK AUTHENTICATION try { length = gcmBlockCipher.ProcessBytes(cipherTextAsByteArray, 0, cipherTextAsByteArray.Length, decryptedTextAsByteArray, 0); gcmBlockCipher.DoFinal(decryptedTextAsByteArray, length); } catch (InvalidCipherTextException e) { Log.Error("Error: {0}", e.Message); return(null); } Log.Information("Decrypted and original plain text are the same: {0}", plainText.Equals(Encoding.UTF8.GetString(decryptedTextAsByteArray))); return(Encoding.UTF8.GetString(decryptedTextAsByteArray)); } #endregion }
public override void PerformTest() { int iCount = 100; byte[] salt = DigestUtilities.DoFinal(digest); PbeParametersGenerator pGen = new Pkcs12ParametersGenerator(digest); pGen.Init( PbeParametersGenerator.Pkcs12PasswordToBytes(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"); } // NB: We don't support retrieving parameters from cipher // // // // get the parameters // // // AlgorithmParameters param = c.getParameters(); // PBEParameterSpec spec = (PBEParameterSpec)param.getParameterSpec(PBEParameterSpec.class); // // if (!AreEqual(salt, spec.getSalt())) // { // Fail("" + algorithm + "failed salt test"); // } // // if (iCount != spec.getIterationCount()) // { // Fail("" + algorithm + "failed count test"); // } // NB: This section just repeats earlier test passing 'param' separately // // // // try using parameters // // // keySpec = new PBEKeySpec(password); // // c.Init(false, fact.generateSecret(keySpec), param); // // dec = c.DoFinal(enc); // // if (!AreEqual(salt, dec)) // { // Fail("" + algorithm + "failed encryption/decryption test"); // } }
public static ICipherParameters GenerateCipherParameters( string algorithm, char[] password, bool wrongPkcs12Zero, Asn1Encodable pbeParameters) { string mechanism = (string)algorithms[algorithm.ToUpper(CultureInfo.InvariantCulture)]; byte[] keyBytes; //string type = (string)algorithmType[mechanism]; byte[] salt; int iterationCount; if (IsPkcs12(mechanism)) { Pkcs12PbeParams pbeParams = Pkcs12PbeParams.GetInstance(pbeParameters); salt = pbeParams.GetIV(); iterationCount = pbeParams.Iterations.IntValue; keyBytes = PbeParametersGenerator.Pkcs12PasswordToBytes(password, wrongPkcs12Zero); } else if (IsPkcs5Scheme2(mechanism)) { Pbkdf2Params pbeParams = Pbkdf2Params.GetInstance(pbeParameters); salt = pbeParams.GetSalt(); iterationCount = pbeParams.IterationCount.IntValue; keyBytes = PbeParametersGenerator.Pkcs5PasswordToBytes(password); } else { PbeParameter pbeParams = PbeParameter.GetInstance(pbeParameters); salt = pbeParams.GetSalt(); iterationCount = pbeParams.IterationCount.IntValue; keyBytes = PbeParametersGenerator.Pkcs5PasswordToBytes(password); } ICipherParameters parameters = null; 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(parameters); }
public static string DemonstrateFileEncryption(string plainText, string password) { #region INITIALIZATION SecureRandom Random = new SecureRandom(); byte[] dataForEncryption = Encoding.UTF8.GetBytes(plainText); Pkcs5S2ParametersGenerator pkcs5S2ParametersGenerator = new Pkcs5S2ParametersGenerator(); byte[] salt = new byte[16]; Random.NextBytes(salt); pkcs5S2ParametersGenerator.Init(PbeParametersGenerator.Pkcs5PasswordToBytes(password.ToCharArray()), salt, 10000); KeyParameter key = (KeyParameter)pkcs5S2ParametersGenerator.GenerateDerivedMacParameters(256); byte[] nonce = new byte[16]; Random.NextBytes(nonce); GcmBlockCipher gcmBlockCipher = new GcmBlockCipher(new AesEngine()); AeadParameters aeadParameters = new AeadParameters(new KeyParameter(key.GetKey()), 128, nonce, salt); gcmBlockCipher.Init(true, aeadParameters); #endregion #region ENCRYPTION //Generate ciphertext with authentication tag. byte[] cipherTextAsByteArray = new byte[gcmBlockCipher.GetOutputSize(dataForEncryption.Length)]; int length = gcmBlockCipher.ProcessBytes(dataForEncryption, 0, dataForEncryption.Length, cipherTextAsByteArray, 0); gcmBlockCipher.DoFinal(cipherTextAsByteArray, length); byte[] output = null; //Put the pices of the message together. using (MemoryStream memoryStream = new MemoryStream()) { using (BinaryWriter binaryWriter = new BinaryWriter(memoryStream)) { binaryWriter.Write(salt); binaryWriter.Write(nonce); binaryWriter.Write(cipherTextAsByteArray); } output = memoryStream.ToArray(); } File.WriteAllBytes("encryptedFile.enc", output); #endregion #region DECRYPTION byte[] encryptedMessageAsByteArray = File.ReadAllBytes("encryptedFile.enc"); salt = new byte[16]; Array.Copy(encryptedMessageAsByteArray, salt, salt.Length); using (MemoryStream memoryStream = new MemoryStream(encryptedMessageAsByteArray)) using (BinaryReader binaryReader = new BinaryReader(memoryStream)) { salt = binaryReader.ReadBytes(salt.Length); nonce = binaryReader.ReadBytes(16); gcmBlockCipher = new GcmBlockCipher(new AesEngine()); aeadParameters = new AeadParameters(new KeyParameter(key.GetKey()), 128, nonce, salt); gcmBlockCipher.Init(false, aeadParameters); cipherTextAsByteArray = binaryReader.ReadBytes(encryptedMessageAsByteArray.Length - salt.Length - nonce.Length); byte[] decryptedTextAsByteArray = new byte[gcmBlockCipher.GetOutputSize(cipherTextAsByteArray.Length)]; try { //Authentication check. length = gcmBlockCipher.ProcessBytes(cipherTextAsByteArray, 0, cipherTextAsByteArray.Length, decryptedTextAsByteArray, 0); gcmBlockCipher.DoFinal(decryptedTextAsByteArray, length); } catch (InvalidCipherTextException e) { //Authentication failed. Log.Error("Error: {0}", e.Message); return(null); } Log.Information("Decrypted file content and original plain text are the same: {0}", plainText.Equals(Encoding.UTF8.GetString(decryptedTextAsByteArray))); return(Encoding.UTF8.GetString(decryptedTextAsByteArray)); } #endregion }
public static ICipherParameters GenerateCipherParameters( string algorithm, char[] password, bool wrongPkcs12Zero, Asn1Encodable pbeParameters) { string mechanism = (string)algorithms[algorithm.ToUpper(CultureInfo.InvariantCulture)]; byte[] keyBytes; // string type = (string)algorithmType[mechanism]; 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)) { Pbkdf2Params pbeParams = Pbkdf2Params.GetInstance(pbeParameters); salt = pbeParams.GetSalt(); iterationCount = pbeParams.IterationCount.IntValue; keyBytes = PbeParametersGenerator.Pkcs5PasswordToBytes(password); } else { PbeParameter pbeParams = PbeParameter.GetInstance(pbeParameters); salt = pbeParams.GetSalt(); iterationCount = pbeParams.IterationCount.IntValue; keyBytes = PbeParametersGenerator.Pkcs5PasswordToBytes(password); } ICipherParameters parameters = null; if (mechanism.StartsWith("PBEwithSHA-1")) { PbeParametersGenerator generator = MakePbeGenerator( (string)algorithmType[mechanism], new Sha1Digest(), keyBytes, salt, iterationCount); if (mechanism.Equals("PBEwithSHA-1and128bitRC4")) { parameters = generator.GenerateDerivedParameters(128); } else if (mechanism.Equals("PBEwithSHA-1and40bitRC4")) { parameters = generator.GenerateDerivedParameters(40); } else if (mechanism.Equals("PBEwithSHA-1and3-keyDESEDE-CBC")) { parameters = generator.GenerateDerivedParameters(192, 64); } else if (mechanism.Equals("PBEwithSHA-1and2-keyDESEDE-CBC")) { parameters = generator.GenerateDerivedParameters(128, 64); } else if (mechanism.Equals("PBEwithSHA-1and128bitRC2-CBC")) { parameters = generator.GenerateDerivedParameters(128, 64); } else if (mechanism.Equals("PBEwithSHA-1and40bitRC2-CBC")) { parameters = generator.GenerateDerivedParameters(40, 64); } else if (mechanism.Equals("PBEwithSHA-1andDES-CBC")) { parameters = generator.GenerateDerivedParameters(64, 64); } else if (mechanism.Equals("PBEwithSHA-1andRC2-CBC")) { parameters = generator.GenerateDerivedParameters(64, 64); } else if (mechanism.Equals("PBEwithSHA-1and128bitAES-CBC-BC")) { parameters = generator.GenerateDerivedParameters(128, 128); } else if (mechanism.Equals("PBEwithSHA-1and192bitAES-CBC-BC")) { parameters = generator.GenerateDerivedParameters(192, 128); } else if (mechanism.Equals("PBEwithSHA-1and256bitAES-CBC-BC")) { parameters = generator.GenerateDerivedParameters(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(128, 128); } else if (mechanism.Equals("PBEwithSHA-256and192bitAES-CBC-BC")) { parameters = generator.GenerateDerivedParameters(192, 128); } else if (mechanism.Equals("PBEwithSHA-256and256bitAES-CBC-BC")) { parameters = generator.GenerateDerivedParameters(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(64, 64); } else if (mechanism.Equals("PBEwithMD5andRC2-CBC")) { parameters = generator.GenerateDerivedParameters(64, 64); } else if (mechanism.Equals("PBEwithMD5and128bitAES-CBC-OpenSSL")) { parameters = generator.GenerateDerivedParameters(128, 128); } else if (mechanism.Equals("PBEwithMD5and192bitAES-CBC-OpenSSL")) { parameters = generator.GenerateDerivedParameters(192, 128); } else if (mechanism.Equals("PBEwithMD5and256bitAES-CBC-OpenSSL")) { parameters = generator.GenerateDerivedParameters(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(64, 64); } else if (mechanism.Equals("PBEwithMD2andRC2-CBC")) { parameters = generator.GenerateDerivedParameters(64, 64); } } else if (mechanism.StartsWith("PBEwithHmac")) { string digestName = mechanism.Substring("PBEwithHmac".Length); int keySize; switch (digestName) { case "SHA-1": keySize = 160; break; case "SHA-224": keySize = 224; break; case "SHA-256": keySize = 256; break; case "RipeMD128": keySize = 128; break; case "RipeMD160": keySize = 160; break; case "RipeMD256": keySize = 256; break; default: throw new ArgumentException("unrecognised algorithm: " + algorithm, "algorithm"); } IDigest digest = DigestUtilities.GetDigest(digestName); PbeParametersGenerator generator = MakePbeGenerator( (string)algorithmType[mechanism], digest, keyBytes, salt, iterationCount); parameters = generator.GenerateDerivedMacParameters(keySize); } Array.Clear(keyBytes, 0, keyBytes.Length); return(parameters); }