101 lines
2.6 KiB
C++
101 lines
2.6 KiB
C++
#include "Packet.hpp"
|
|
|
|
#include <stdexcept>
|
|
#include <cstring>
|
|
|
|
#include "SecurityMode.hpp"
|
|
|
|
|
|
namespace drp::packet::base {
|
|
|
|
|
|
/*
|
|
GenericPacketContent decryptPacketContentAes(const GenericPacket& packet) {
|
|
GenericPacketContent decryptedPacketContent {};
|
|
|
|
const auto& [key, iv] = keysAes[serverAddress];
|
|
|
|
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
|
|
if (EVP_DecryptInit_ex(
|
|
ctx,
|
|
EVP_aes_256_cbc(),
|
|
nullptr,
|
|
key,
|
|
iv
|
|
) != 1)
|
|
throw std::runtime_error("[Client] Could not initialize the EVP_CIPHER_CTX.");
|
|
|
|
int packetContentLength;
|
|
|
|
if (EVP_DecryptUpdate(
|
|
ctx,
|
|
reinterpret_cast<std::uint8_t*>(&decryptedPacketContent),
|
|
&packetContentLength,
|
|
reinterpret_cast<const std::uint8_t*>(&packet.encryptedContent),
|
|
sizeof(packet)
|
|
) != 1)
|
|
throw std::runtime_error("[Client] Could not encrypt the plaintext.");
|
|
|
|
if (EVP_DecryptFinal_ex(
|
|
ctx,
|
|
reinterpret_cast<std::uint8_t*>(&decryptedPacketContent + packetContentLength),
|
|
&packetContentLength
|
|
) != 1)
|
|
throw std::runtime_error("[Client] Could not decrypt the final plaintext.");
|
|
|
|
EVP_CIPHER_CTX_free(ctx);
|
|
|
|
return decryptedPacketContent;
|
|
}
|
|
*/
|
|
|
|
|
|
inline Packet::Packet(
|
|
const Context& context,
|
|
const std::uint8_t channel,
|
|
SecurityMode securityMode,
|
|
const PacketContent& content
|
|
) {
|
|
this->channel = channel;
|
|
this->securityMode = static_cast<std::uint8_t>(securityMode);
|
|
|
|
switch (securityMode) {
|
|
case SecurityMode::PLAIN:
|
|
this->content = static_cast<auto>(content);
|
|
break;
|
|
case SecurityMode::RSA:
|
|
this->content = encryptRsa(context, content);
|
|
break;
|
|
case SecurityMode::AES:
|
|
this->content = encryptAes(context, content);
|
|
break;
|
|
default:
|
|
throw std::invalid_argument("Invalid security mode.");
|
|
}
|
|
}
|
|
|
|
|
|
PacketContent Packet::getContent(
|
|
const Context& context,
|
|
const sockaddr_storage& address,
|
|
socklen_t addressLength
|
|
) const {
|
|
PacketContent content {};
|
|
|
|
switch (static_cast<SecurityMode>(this->securityMode)) {
|
|
case SecurityMode::PLAIN:
|
|
std::memcpy(&content, &this->content, sizeof(PacketContent));
|
|
return content;
|
|
case SecurityMode::RSA:
|
|
content = decryptRsa(context, this->content, address, addressLength);
|
|
return content;
|
|
case SecurityMode::AES:
|
|
content = decryptAes(context, this->content);
|
|
return content;
|
|
default:
|
|
throw std::invalid_argument("Invalid security mode.");
|
|
}
|
|
}
|
|
|
|
|
|
}
|