using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Security.Cryptography;
using System.Text;

namespace CaLib.Encryption
{
	/// <summary>
	/// Summary description for SSTCryptographer
	/// </summary>
	/// <see cref="http://www.codeproject.com/KB/security/simplestringencryption.aspx"/>
	public abstract class SSTCryptographer
	{
		/// <summary>
		/// Encrypt the given string using the specified key.
		/// </summary>
		/// <param name="strToEncrypt">The string to be encrypted.</param>
		/// <param name="strKey">The encryption key.</param>
		/// <returns>The encrypted string.</returns>
		/// <exception cref="System.Exception">問題があれば例外が投入される</exception>
		public static string Encrypt(string strToEncrypt, string strKey)
		{
			using (TripleDESCryptoServiceProvider objDESCrypto = new TripleDESCryptoServiceProvider())
			{
				using (MD5CryptoServiceProvider objHashMD5 = new MD5CryptoServiceProvider())
				{

					byte[] byteHash, byteBuff;
					string strTempKey = strKey;

					byteHash = objHashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(strTempKey));
					objDESCrypto.Key = byteHash;
					objDESCrypto.Mode = CipherMode.ECB; //CBC, CFB

					//byteBuff = ASCIIEncoding.ASCII.GetBytes(strToEncrypt);
					byteBuff = Encoding.UTF8.GetBytes(strToEncrypt);

					return Convert.ToBase64String(objDESCrypto.CreateEncryptor().TransformFinalBlock(byteBuff, 0, byteBuff.Length));
				}
			}
		}


		/// <summary>
		/// Decrypt the given string using the specified key.
		/// </summary>
		/// <param name="strEncrypted">The string to be decrypted.</param>
		/// <param name="strKey">The decryption key.</param>
		/// <returns>The decrypted string.</returns>
		/// <exception cref="System.Exception">問題があれば例外が投入される</exception>
		public static string Decrypt(string strEncrypted, string strKey)
		{
			using (TripleDESCryptoServiceProvider objDESCrypto = new TripleDESCryptoServiceProvider())
			{
				using (MD5CryptoServiceProvider objHashMD5 = new MD5CryptoServiceProvider())
				{
					byte[] byteHash, byteBuff;
					string strTempKey = strKey;

					byteHash = objHashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(strTempKey));
					objDESCrypto.Key = byteHash;
					objDESCrypto.Mode = CipherMode.ECB; //CBC, CFB

					byteBuff = Convert.FromBase64String(strEncrypted);
					//string strDecrypted = ASCIIEncoding.ASCII.GetString(objDESCrypto.CreateDecryptor().TransformFinalBlock(byteBuff, 0, byteBuff.Length));
					string strDecrypted = Encoding.UTF8.GetString(objDESCrypto.CreateDecryptor().TransformFinalBlock(byteBuff, 0, byteBuff.Length));
					return strDecrypted;
				}
			}
		}
	}


}