using System;
using System.Collections.Generic;
using Library;
using System.Text;

namespace MySystem
{
    public class EncryptHelper
    {

        public static string Encrypt1(SortedList<string, string> obj, string key)
        {
            string signstr = function.BuildQueryString(obj) + key;
            string sign = function.MD532(signstr).ToUpper();
            obj.Add("sign", sign);
            return AesEncrypt(Newtonsoft.Json.JsonConvert.SerializeObject(obj), key);
        }

        public static string[] Encrypt1(SortedList<string, object> obj, string key)
        {
            string signstr = "";
            foreach(string sub in obj.Keys)
            {
                if(sub == "pos_no" || sub == "merch_no")
                {
                    signstr += sub + "=" + Newtonsoft.Json.JsonConvert.SerializeObject(obj[sub]).Replace("\"", "") + "&";
                }
                else
                {
                    signstr += sub + "=" + obj[sub].ToString() + "&";
                }
            }
            signstr = signstr.TrimEnd('&');
            signstr += key;
            string sign = function.MD532(signstr).ToUpper();
            obj.Add("sign", sign);
            return new string[] {AesEncrypt(Newtonsoft.Json.JsonConvert.SerializeObject(obj), key), sign};
        }

        public static string AesEncrypt(string str, string key)
        {
            if (string.IsNullOrEmpty(str)) return null;
            Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str);

            System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
            {
                Key = Encoding.UTF8.GetBytes(key),
                Mode = System.Security.Cryptography.CipherMode.ECB,
                Padding = System.Security.Cryptography.PaddingMode.PKCS7
            };
            System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateEncryptor();
            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }

        public static string AesDecrypt(string str, string key)
        {
            if (string.IsNullOrEmpty(str)) return null;
            byte[] toEncryptArray = Convert.FromBase64String(str);

            System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
            {
                Key = Encoding.UTF8.GetBytes(key),
                Mode = System.Security.Cryptography.CipherMode.ECB,
                Padding = System.Security.Cryptography.PaddingMode.PKCS7,
            };

            System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateDecryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return Encoding.UTF8.GetString(resultArray);
        }

        
    }
}
