using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;

namespace EA.GameTalkMessages
{
	public class SymmetricCrypto
	{
		public static void ClearBytes(byte[] Buffer)
		{
			// Check arguments.
			if (Buffer == null)
			{
				throw new ArgumentException("Buffer");
			}

			// Set each byte in the buffer to 0.
			for (int x = 0; x <= Buffer.Length - 1; x++)
			{
				Buffer[x] = 0;
			}
		}

		public static byte[] CreateRandomSalt(int Length)
		{
			// Create a buffer
			byte[] randBytes;
			if (Length >= 1)
				randBytes = new byte[Length];
			else
				randBytes = new byte[1];

			// Create a new RNGCryptoServiceProvider.
			RNGCryptoServiceProvider rand = new RNGCryptoServiceProvider();
			// Fill the buffer with random bytes.
			rand.GetBytes(randBytes);
			// return the bytes.
			return randBytes;
		}

		public static byte[] EncryptPassword(string textPassword)
		{
			if (string.IsNullOrEmpty(textPassword))
				return null;

			byte[] pwd = Encoding.Unicode.GetBytes(textPassword);
			byte[] salt = CreateRandomSalt(7);
			// Create a TripleDESCryptoServiceProvider object.
			TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
			try
			{
				//Console.WriteLine("Creating a key with PasswordDeriveBytes...");

				// Create a PasswordDeriveBytes object and then create
				// a TripleDES key from the password and salt.
				PasswordDeriveBytes pdb = new PasswordDeriveBytes(pwd, salt);
				// Create the key and set it to the Key property
				// of the TripleDESCryptoServiceProvider object.
				//tdes.Key = pdb.CryptDeriveKey("TripleDES", "SHA1", 192, tdes.IV);
				return pdb.CryptDeriveKey("TripleDES", "SHA1", 192, tdes.IV);
			}
			catch
			{
				//Console.WriteLine(e.Message);
			}
			finally
			{
				// Clear the buffers
				ClearBytes(pwd);
				ClearBytes(salt);

				// Clear the key.
				tdes.Clear();
			}
			return null;
		}
	}
}
