using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace Edu.Common
{
    /// <summary> 
    /// DES 加解密
    /// </summary> 
    public class DES
    {
        private static readonly byte[] _webapikey = { 0xF1, 0x12, 0xA3, 0xD1, 0xBA, 0x54, 0x2A, 0x88 };
        private static readonly byte[] _webapiiv = { 0x04, 0xAE, 0x57, 0x83, 0x56, 0x28, 0x66, 0xA7 };

        /// <summary>
        /// DES加密（单向,只能C#用）
        /// </summary>
        /// <param name="EncryptString">加密字符串</param>
        /// <returns></returns>
        public static string Encrypt(string EncryptString)
        {
            return Encrypt(EncryptString, _webapikey, _webapiiv);
        }

        /// <summary>
        /// DES加密（单向,只能C#用）
        /// </summary>
        /// <param name="EncryptString">待加密的字符串</param>
        /// <param name="Key">加密密钥</param>
        /// <param name="IV">初始化加密函数的变量</param>
        /// <returns></returns>
        private static string Encrypt(string EncryptString, byte[] Key, byte[] IV)
        {
            byte[] inputByteArray = Encoding.UTF8.GetBytes(EncryptString);
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            MemoryStream mStream = new MemoryStream();
            CryptoStream cStream = new CryptoStream(mStream, des.CreateEncryptor(Key, IV), CryptoStreamMode.Write);
            cStream.Write(inputByteArray, 0, inputByteArray.Length);
            cStream.FlushFinalBlock();
            return Convert.ToBase64String(mStream.ToArray());
        }

        /// <summary>
        /// DES解密
        /// </summary>
        /// <param name="DecryptString">待解密的字符串</param>
        /// <returns>解密成功返回解密后的字符串,失败返源串</returns>
        public static string Decrypt(string DecryptString)
        {
            return Decrypt(DecryptString, _webapikey, _webapiiv);
        }

        /// <summary>
        /// DES解密
        /// </summary>
        /// <param name="DecryptString">待解密的字符串</param>
        /// <param name="Key">解密密钥,要求为8位,和加密密钥相同</param>
        /// <param name="IV">初始化加密函数的变量</param>
        /// <returns>解密成功返回解密后的字符串,失败返源串</returns>
        private static string Decrypt(string DecryptString, byte[] Key, byte[] IV)
        {
            try
            {
                byte[] inputByteArray = Convert.FromBase64String(DecryptString);
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();

                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, des.CreateDecryptor(Key, IV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Encoding.UTF8.GetString(mStream.ToArray());
            }
            catch
            {
                return "";
            }
        }
    }
}