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

namespace Siger.Middlelayer.Common.Helpers
{
    public class DesBuilder
    {
        private const string EncryptKey = "Siger018";
        private static readonly byte[] Keys = { 0x56, 0x34, 0x90, 0xCD, 0xEF, 0xAB, 0x12, 0x78};

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string Encrypt(string value)
        {
            if (string.IsNullOrEmpty(value)) return string.Empty;
            try
            {
                byte[] rgbKey = Encoding.UTF8.GetBytes(EncryptKey);
                byte[] rgbIv = Keys;
                byte[] inputByteArray = Encoding.UTF8.GetBytes(value);
                var dCsp = new DESCryptoServiceProvider();
                using (var stream = new MemoryStream())
                {
                    using (var cStream = new CryptoStream(stream, dCsp.CreateEncryptor(rgbKey, rgbIv), CryptoStreamMode.Write))
                    {
                        cStream.Write(inputByteArray, 0, inputByteArray.Length);
                        cStream.FlushFinalBlock();
                        var output = Convert.ToBase64String(stream.ToArray());
                        return output;
                    }
                }
            }
            catch
            {
                return value;
            }
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string Decrypt(string value)
        {
            if (string.IsNullOrEmpty(value)) return string.Empty;
            try
            {
                byte[] rgbKey = Encoding.UTF8.GetBytes(EncryptKey);
                byte[] rgbIv = Keys;
                byte[] inputByteArray = Convert.FromBase64String(value);
                var dcsp = new DESCryptoServiceProvider();
                using (var stream = new MemoryStream())
                {
                    using (var cStream = new CryptoStream(stream, dcsp.CreateDecryptor(rgbKey, rgbIv), CryptoStreamMode.Write))
                    {
                        cStream.Write(inputByteArray, 0, inputByteArray.Length);
                        cStream.FlushFinalBlock();
                        return Encoding.UTF8.GetString(stream.ToArray());
                    }
                }
            }
            catch
            {
                return value;
            }
        }
    }
}
