美文网首页
C++ SDPLOG 加密日志

C++ SDPLOG 加密日志

作者: BillZhang88 | 来源:发表于2023-09-21 10:28 被阅读0次

继承 public spdlog::formatter
实现类:

···
EncryptionFormatter.h

include <spdlog/fmt/fmt.h>

include <spdlog/formatter.h>

include <spdlog/details/log_msg.h>

using namespace spdlog;

class EncryptionFormatter : public spdlog::formatter {
public:
// 重写基类中的虚函数,实现自定义的日志格式化逻辑
std::string encrypt(const std::string& plaintext, const std::string& key, const std::string& iv);
void decrypt(std::string &msg);

 using spdlog::formatter::formatter;

std::unique_ptr<spdlog::formatter> clone() const override
{
    return std::make_unique<EncryptionFormatter>(*this); // 创建并返回新的 EncryptionFormatter 对象
}

void format(const details::log_msg &msg,memory_buf_t &dest) override; 

};

实现类:

include "EncryptionFormatter.h"

include <spdlog/fmt/ostr.h>

include <spdlog/formatter.h>

include <iostream>

include <openssl/aes.h>

include <string>

include <spdlog/spdlog.h>

std::string EncryptionFormatter ::encrypt(const std::string &plaintext, const std::string &key, const std::string &iv)
{
std::string ciphertext;

AES_KEY aesKey;
AES_set_encrypt_key((const unsigned char *)key.c_str(), 128, &aesKey);

// 获取加密后的长度并分配内存
int encryptedLength = ((plaintext.length() + AES_BLOCK_SIZE) / AES_BLOCK_SIZE) * AES_BLOCK_SIZE;
unsigned char *encryptedData = new unsigned char[encryptedLength];

// 加密数据
AES_cbc_encrypt((const unsigned char *)plaintext.c_str(), encryptedData, plaintext.length(),
                &aesKey, (unsigned char *)iv.c_str(), AES_ENCRYPT);

// 将加密后的数据存储在字符串中
ciphertext.assign(reinterpret_cast<char *>(encryptedData), encryptedLength);

// 释放内存
delete[] encryptedData;

return ciphertext;

}
void EncryptionFormatter::format(const details::log_msg &msg,memory_buf_t &dest)
{
// 获取原始的日志消息
std::string logMsg = msg.payload.data();

// 执行加密逻辑,这里是示例代码,请根据您的实际需求进行替换

std::string key = "1234567890123456";
std::string iv = "abcdefghijklmnop";

std::string encryptedMsg = encrypt(logMsg, key, iv);

// formatter::format(msg, dest);

// 追加加密后的消息内容
fmt::format_to(dest, " [Encrypted: {}]", encryptedMsg);

}
···

相关文章

网友评论

      本文标题:C++ SDPLOG 加密日志

      本文链接:https://www.haomeiwen.com/subject/mmqzvdtx.html