lokinet/llarp/crypto/encrypted_frame.hpp

93 lines
2.2 KiB
C++
Raw Normal View History

#ifndef LLARP_ENCRYPTED_FRAME_HPP
#define LLARP_ENCRYPTED_FRAME_HPP
#include <crypto/encrypted.hpp>
#include <crypto/types.hpp>
#include <util/buffer.hpp>
2019-07-30 23:42:13 +00:00
#include <utility>
#include <util/mem.h>
namespace llarp
{
static constexpr size_t EncryptedFrameOverheadSize = PUBKEYSIZE + TUNNONCESIZE + SHORTHASHSIZE;
2019-04-29 18:06:16 +00:00
static constexpr size_t EncryptedFrameBodySize = 128 * 6;
static constexpr size_t EncryptedFrameSize = EncryptedFrameOverheadSize + EncryptedFrameBodySize;
2018-06-21 12:55:02 +00:00
struct EncryptedFrame : public Encrypted<EncryptedFrameSize>
2018-12-20 16:49:05 +00:00
{
EncryptedFrame() : EncryptedFrame(EncryptedFrameBodySize)
2018-06-21 12:55:02 +00:00
{
}
2018-06-14 20:13:07 +00:00
EncryptedFrame(size_t sz)
: Encrypted<EncryptedFrameSize>(
std::min(sz, EncryptedFrameBodySize) + EncryptedFrameOverheadSize)
2018-06-11 13:25:10 +00:00
{
2018-06-21 12:55:02 +00:00
}
2019-02-19 15:06:39 +00:00
void
Resize(size_t sz)
{
if (sz <= EncryptedFrameSize)
2019-02-19 15:06:39 +00:00
{
_sz = sz;
UpdateBuffer();
}
}
bool
DoEncrypt(const SharedSecret& shared, bool noDH = false);
2018-06-10 14:05:48 +00:00
bool
DecryptInPlace(const SecretKey& seckey);
2018-06-11 13:25:10 +00:00
bool
DoDecrypt(const SharedSecret& shared);
2018-06-11 13:25:10 +00:00
bool
EncryptInPlace(const SecretKey& seckey, const PubKey& other);
2018-06-10 14:05:48 +00:00
};
/// TODO: can only handle 1 frame at a time
template <typename User>
2018-06-10 14:05:48 +00:00
struct AsyncFrameDecrypter
{
using User_ptr = std::shared_ptr<User>;
using DecryptHandler = std::function<void(llarp_buffer_t*, User_ptr)>;
2018-06-10 14:05:48 +00:00
void
Decrypt(User_ptr user)
2018-06-10 14:05:48 +00:00
{
if (target.DecryptInPlace(seckey))
2018-06-21 12:55:02 +00:00
{
auto buf = target.Buffer();
2018-12-20 16:49:05 +00:00
buf->cur = buf->base + EncryptedFrameOverheadSize;
result(buf, user);
2018-06-21 12:55:02 +00:00
}
2018-06-10 14:05:48 +00:00
else
result(nullptr, user);
2018-06-10 14:05:48 +00:00
}
AsyncFrameDecrypter(const SecretKey& secretkey, DecryptHandler h)
2019-07-30 23:42:13 +00:00
: result(std::move(h)), seckey(secretkey)
2018-06-10 14:05:48 +00:00
{
}
DecryptHandler result;
const SecretKey& seckey;
2018-12-20 16:49:05 +00:00
EncryptedFrame target;
2018-06-20 12:34:48 +00:00
using WorkFunc_t = std::function<void(void)>;
using WorkerFunction_t = std::function<void(WorkFunc_t)>;
2018-06-10 14:05:48 +00:00
void
AsyncDecrypt(const EncryptedFrame& frame, User_ptr u, WorkerFunction_t worker)
2018-06-10 14:05:48 +00:00
{
2019-04-30 12:22:15 +00:00
target = frame;
worker(std::bind(&AsyncFrameDecrypter<User>::Decrypt, this, std::move(u)));
2018-06-10 14:05:48 +00:00
}
};
2018-06-14 20:13:07 +00:00
} // namespace llarp
#endif