using NFine.Code;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace NFine.Application.Encrypt
{
   public class EnciphermentApp
    {
        public void Encryption(string ICSInspections)
        {
            try
            {
                string url = HttpContext.Current.Request.Url.Host;
                if (url != "localhost")
                {
                    throw new Exception("您无该操作权限,请联系管理员!");
                }
                var queryParam = ICSInspections.ToJObject();
                List<DbParameter> parameter = new List<DbParameter>();
                string DbTXT = queryParam["Encipherment"].ToString();
                string MD5DbTXT = ToMd5(DbTXT);
                SetValue("connstr", MD5DbTXT);
            }
            catch (Exception ex)
            {
                throw ex ;
            }
        }


        /// <summary>
        /// 根据Key修改Value
        /// </summary>
        /// <param name="key">要修改的Key</param>
        /// <param name="value">要修改为的值</param>
        public static void SetValue(string key, string value)
        {
            System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();
            xDoc.Load(HttpContext.Current.Server.MapPath("~/Configs/database.config"));
            System.Xml.XmlNode xNode;
            System.Xml.XmlElement xElem1;
            System.Xml.XmlElement xElem2;
            xNode = xDoc.SelectSingleNode("//connectionStrings");

            xElem1 = (System.Xml.XmlElement)xNode.SelectSingleNode("//add[@name='" + key + "']");
            if (xElem1 != null) xElem1.SetAttribute("connectionString", value);
            else
            {
                xElem2 = xDoc.CreateElement("add");
                xElem2.SetAttribute("name", key);
                xElem2.SetAttribute("connectionString", value);
                xNode.AppendChild(xElem2);
            }
            xDoc.Save(HttpContext.Current.Server.MapPath("~/Configs/database.config"));
        }

        #region 字符串加解密
        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ToMd5(string str)
        {
            return Encrypt(str, "&%#@?,:*_");
        }
        /// <summary>
        /// MD5解密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string FromMd5(string str)
        {
            //return str;
            return Decrypt(str, "&%#@?,:*_");
        }
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="strText"></param>
        /// <param name="strEncrKey"></param>
        /// <returns></returns>
        private static String Encrypt(String strText, String strEncrKey)
        {
            Byte[] byKey = { };
            Byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
            try
            {
                byKey = System.Text.Encoding.UTF8.GetBytes(strEncrKey.Substring(0, 8));
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                Byte[] inputByteArray = Encoding.UTF8.GetBytes(strText);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV),
           CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                return Convert.ToBase64String(ms.ToArray());
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="strText"></param>
        /// <param name="sDecrKey"></param>
        /// <returns></returns>
        private static String Decrypt(String strText, String sDecrKey)
        {
            Byte[] byKey = { };
            Byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
            Byte[] inputByteArray = new byte[strText.Length];
            try
            {
                byKey = System.Text.Encoding.UTF8.GetBytes(sDecrKey.Substring(0, 8));
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                inputByteArray = Convert.FromBase64String(strText);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV),
           CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                System.Text.Encoding encoding = System.Text.Encoding.UTF8;
                return encoding.GetString(ms.ToArray());
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        #endregion
    }
}