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

namespace IntegrationKSSS.WebService.Infrastructure.Cryptography;
internal static class AesExtension
{
    #region Methods
    internal static string DecryptString(this string cipherText, string key, byte[] IV)
    {
        if (cipherText == null || cipherText.Length <= 0) throw new ArgumentNullException(nameof(cipherText));
        if (key == null || key.Length <= 0) throw new ArgumentNullException(nameof(key));
        if (IV == null || IV.Length <= 0) throw new ArgumentNullException(nameof(IV));
        string plaintext = null;
        using (Aes aesAlg = Aes.Create())
        {
            aesAlg.Key = Encoding.UTF8.GetBytes(key);
            aesAlg.IV = IV;

            ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

            using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(cipherText)))
            {
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                    {
                        plaintext = srDecrypt.ReadToEnd();
                    }
                }
            }
        }

        return plaintext;
    } 
    #endregion
}