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

namespace Long.Utils.Encryptor;

/// <summary>
/// DES加密器：用于加密和解密字符串
/// </summary>
public class DESEncryptor
{
    private const string _defaultKey = "Long";
    private static byte[] _rgbIV = new byte[8] { 2, 4, 8, 16, 32, 64, 128, 255 };

    /// <summary>
    /// 加密
    /// </summary>
    /// <param name="data">数据</param>
    /// <param name="key">密钥</param>
    /// <returns>加密结果字符串</returns>
    public static string Encrypt(string data, string key = _defaultKey)
    {
        if (data == null || string.IsNullOrEmpty(data.Trim()))
        {
            return string.Empty;
        }
        try
        {
            byte[] bytes = Encoding.UTF8.GetBytes(key.Substring(0, key.Length > 8 ? 8 : key.Length).PadRight(8, '0'));
            var des = DES.Create();
            byte[] bytes2 = Encoding.UTF8.GetBytes(data);
            MemoryStream memoryStream = new MemoryStream();
            CryptoStream cryptoStream = new CryptoStream(memoryStream, des.CreateEncryptor(bytes, _rgbIV), CryptoStreamMode.Write);
            cryptoStream.Write(bytes2, 0, bytes2.Length);
            cryptoStream.FlushFinalBlock();
            return Convert.ToBase64String(memoryStream.ToArray());
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            return string.Empty;
        }
    }

    /// <summary>
    /// 解密
    /// </summary>
    /// <param name="data">数据</param>
    /// <param name="key">密钥</param>
    /// <returns>解密结果字符串</returns>
    public static string Decrypt(string data, string key = _defaultKey)
    {
        if (data == null || string.IsNullOrEmpty(data.Trim()))
        {
            return string.Empty;
        }
        try
        {
            byte[] bytes = Encoding.UTF8.GetBytes(key.Substring(0, key.Length > 8 ? 8 : key.Length).PadRight(8, '0'));
            var des = DES.Create();
            byte[] array = Convert.FromBase64String(data);
            MemoryStream memoryStream = new MemoryStream();
            CryptoStream cryptoStream = new CryptoStream(memoryStream, des.CreateDecryptor(bytes, _rgbIV), CryptoStreamMode.Write);
            cryptoStream.Write(array, 0, array.Length);
            cryptoStream.FlushFinalBlock();
            return Encoding.UTF8.GetString(memoryStream.ToArray());
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            return string.Empty;
        }
    }
}
