/// <param name="algorithm">The symmertric algorithm (Aes, DES, RC2, Rijndael and TripleDES).</param> /// <param name="plainText">The plain text need to be encrypted.</param> /// <param name="key">The secret key to encrypt plain text.</param> /// <param name="iv">The iv should be 16 bytes.</param> /// <param name="salt">Salt to encrypt with.</param> /// <param name="pwdIterations">The number of iterations for plain text.</param> /// <param name="keySize">Size of the key.</param> /// <param name="cipherMode">The cipher mode.</param> /// <param name="paddingMode">The padding mode.</param> /// <returns></returns> public static byte[] Encrypt(SymmetricAlgorithm algorithm, byte[] plainText, string key, string iv, string salt, int pwdIterations, int keySize, CipherMode cipherMode, PaddingMode paddingMode) { if (null == plainText) throw new ArgumentNullException("plainText"); if (null == algorithm) throw new ArgumentNullException("algorithm"); if (String.IsNullOrEmpty(key)) throw new ArgumentNullException("key"); if (String.IsNullOrEmpty(iv)) throw new ArgumentNullException("iv"); if (String.IsNullOrEmpty(salt)) throw new ArgumentNullException("salt"); // Note the salt should be equal or greater that 64bit (8 byte). var rfc = new Rfc2898DeriveBytes(key, salt.ToByteArray(), pwdIterations); using (SymmetricAlgorithm symmAlgo = algorithm) { symmAlgo.Mode = cipherMode; //symmAlgo.Padding = paddingMode; byte[] cipherTextBytes = null; using (var encryptor = symmAlgo.CreateEncryptor( rfc.GetBytes(keySize / 8), iv.ToByteArray())) { using (var ms = new MemoryStream()) { using (var cs = new CryptoStream( ms, encryptor, CryptoStreamMode.Write)) { cs.Write(plainText, 0, plainText.Length); cs.FlushFinalBlock(); cipherTextBytes = ms.ToArray(); ms.Close(); cs.Close(); } } symmAlgo.Clear(); return cipherTextBytes; } } } |