using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Xml;
using SdaWSCryptoClient;

namespace MOH_CRA_XCRMS_Service.Common
{
    public static class XmlCrypting
    {
        /// <summary>
        /// Encrypt xml using encryption key and pack content with encryption key id, oid and iv
        /// </summary>
        /// <param name="element">Source xml to be encrypted</param>
        /// <param name="key">Encryption key</param>
        /// <param name="keyId">KeyId to be packed in encrypted content</param>
        internal static void EncryptXml(this XmlElement element, byte[] key, long keyId)
        {
            using (var aescp = new AesCryptoServiceProvider
            {
                Mode = CipherMode.CBC,
                KeySize = 256
            })
            {
                aescp.GenerateIV();

                byte[] iv = aescp.IV;
                byte[] elementArray = Encoding.UTF8.GetBytes(element.InnerXml);

                ICryptoTransform encryptor = aescp.CreateEncryptor(key, iv);
                byte[] encryptedData = encryptor.TransformFinalBlock(elementArray, 0, elementArray.Length);

                Oid oid = new Oid("aes256");

                encryptedData = SdaEncryptedDataBuilder.BuildEncryptedData(oid.Value, encryptedData, iv, keyId);

                element.InnerXml = Convert.ToBase64String(encryptedData);
            }
        }

        /// <summary>
        /// Decrypt xml using encryption key and pack content with encryption key id, oid and iv
        /// </summary>
        /// <param name="element">Source xml to be decrypted</param>
        /// <param name="key">Encryption key</param>
        internal static void DecryptXml(this XmlElement element, byte[] key)
        {
            using (var aescp = new AesCryptoServiceProvider
            {
                Mode = CipherMode.CBC,
                KeySize = 256
            })
            {
                string sdata = element.InnerXml;
                byte[] edata = Convert.FromBase64String(sdata);

                var sdaed = new SdaEncryptedData(edata);

                byte[] iv = sdaed.IV;

                ICryptoTransform decryptor = aescp.CreateDecryptor(key, iv);

                edata = sdaed.EncryptedContent;

                byte[] data = decryptor.TransformFinalBlock(edata, 0, edata.Length);

                element.InnerXml = Encoding.UTF8.GetString(data);
            }
        }
  
    }
}