Serilog 日志加密

发布时间 2023-06-13 15:11:12作者: 守望星辰的夏天

1.安装Serilog.Sinks.File Nuget包

2.重写FileLifecycleHooks(使用加密流)或者重写ITextFormatter在里面加密

public class EncryLifecycleHooks : FileLifecycleHooks
    {
        /// <summary>
        /// 是否加密
        /// </summary>
        public bool IsEncryption { get; set; }

        public string Key { get; set; } = "125/*/056asdddd7d8d4d5d6d490****";


        public string IV { get; set; } = "iv12345678901234";

        public EncryLifecycleHooks(bool isEncryption, string key = "", string iV = "")
        {

            this.IsEncryption = isEncryption;
            if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(iV))
            {
                this.Key = key;
                this.IV = iV;
            }
        }

        public override void OnFileDeleting(string path)
        {
            base.OnFileDeleting(path);

        }

        public override Stream OnFileOpened(string path, Stream underlyingStream, Encoding encoding)
        {

            if (IsEncryption)
            {
                Aes aes = Aes.Create();
                // 设置加密密钥和初始化向量
                aes.Key = Encoding.UTF8.GetBytes(Key);
                aes.IV = Encoding.UTF8.GetBytes(IV);
                aes.Mode = CipherMode.ECB; // 使用适当的加密模式
                aes.Padding = PaddingMode.Zeros; // 使用适当的填充模式
                // 创建加密流
                CryptoStream cryptoStream = new CryptoStream(underlyingStream, aes.CreateEncryptor(), CryptoStreamMode.Write);
                return cryptoStream;
            }
            else
            {
                return base.OnFileOpened(path, underlyingStream, encoding);
            }
        }
    }