feanz
9/5/2013 - 8:12 PM

Symmetric Crypto

Symmetric Crypto

public static class SymmetricExtensions
  {
		private const ushort _iteration = 1000;
		private const int _saltSize = 8;

		public static byte[] Encrypt(this byte[] plainTextData, string password)
		{
			byte[] encryptedData = null;
			using (var provider = new RijndaelManaged())
			{
				provider.Mode = CipherMode.CBC;
				provider.Padding = PaddingMode.PKCS7;

				provider.GenerateIV();

				var derivedKey = new Rfc2898DeriveBytes(password, _saltSize, _iteration);
				provider.Key = derivedKey.GetBytes(provider.KeySize >> 3);


				using (var memStream = new MemoryStream(plainTextData.Length))
				{
					memStream.Write(provider.IV, 0, 16);
					memStream.Write(derivedKey.Salt, 0, 8);

					using (var encryptor = provider.CreateEncryptor(provider.Key, provider.IV))
					{
						using (var cryptoStream = new CryptoStream(memStream, encryptor, CryptoStreamMode.Write))
						{
							cryptoStream.Write(plainTextData, 0, plainTextData.Length);
							cryptoStream.FlushFinalBlock();
						}
					}
					encryptedData = memStream.ToArray();
				}
			}
			return encryptedData;
		}

		public static string Encrypt(this string plainText, string key)
		{
			var plainTextData = Encoding.UTF8.GetBytes(plainText);

			var cipherData = plainTextData.Encrypt(key);

			return Convert.ToBase64String(cipherData);
		}

		public static string Decrypt(this string cipherText, string key)
		{
			var cipherData = Convert.FromBase64String(cipherText);

			var plainTextData = cipherData.Decrypt(key);

			return Encoding.UTF8.GetString(plainTextData);
		}

		public static string Nice(this byte[] data)
		{
			return data.Aggregate("", (current, b) => current + " " + b.ToString());
		}

		public static byte[] Decrypt(this byte[] cipherData, string password)
		{
			var decryptedData = new byte[cipherData.Length];

			using (var provider = new RijndaelManaged())
			{
				provider.Mode = CipherMode.CBC;
				provider.Padding = PaddingMode.PKCS7;

				using (var memStream = new MemoryStream(cipherData))
				{
					var iv = new byte[16];
					memStream.Read(iv, 0, 16);

					var salt = new byte[8];
					memStream.Read(salt, 0, 8);

					var derivedKey = new Rfc2898DeriveBytes(password, salt);
					provider.Key = derivedKey.GetBytes(provider.KeySize >> 3);

					int byteCount = 0;
					using (var decryptor = provider.CreateDecryptor(provider.Key, iv))
					{
						using (var cryptoStream = new CryptoStream(memStream, decryptor, CryptoStreamMode.Read))
						{
							byteCount = cryptoStream.Read(decryptedData, 0, decryptedData.Length);
						}
					}

					Array.Resize(ref decryptedData, byteCount);
				}
			}
			return decryptedData;
		}