lokinet/include/llarp/encrypted.hpp

126 lines
2.0 KiB
C++
Raw Normal View History

2018-06-11 13:25:10 +00:00
#ifndef LLARP_ENCCRYPTED_HPP
#define LLARP_ENCCRYPTED_HPP
#include <llarp/bencode.h>
2018-06-11 13:25:10 +00:00
#include <llarp/buffer.h>
2018-06-12 16:45:12 +00:00
#include <sodium.h>
2018-06-19 17:11:24 +00:00
#include <vector>
2018-08-30 18:48:43 +00:00
#include <stdexcept>
2018-06-11 13:25:10 +00:00
namespace llarp
{
/// encrypted buffer base type
struct Encrypted
{
2018-08-30 18:48:43 +00:00
static const size_t MAX_SIZE = (1024 * 8);
2018-06-21 12:55:02 +00:00
Encrypted(Encrypted&&) = delete;
2018-08-09 19:02:17 +00:00
Encrypted(const Encrypted& other);
2018-06-22 00:25:30 +00:00
Encrypted();
2018-06-11 13:25:10 +00:00
Encrypted(const byte_t* buf, size_t sz);
Encrypted(size_t sz);
2018-06-21 12:55:02 +00:00
~Encrypted();
2018-06-11 13:25:10 +00:00
bool
BEncode(llarp_buffer_t* buf) const
{
2018-06-21 12:55:02 +00:00
return bencode_write_bytestring(buf, _data, _sz);
}
2018-08-14 21:17:18 +00:00
Encrypted&
operator=(const Encrypted& other)
{
return (*this) = other.Buffer();
}
2018-06-22 00:25:30 +00:00
Encrypted&
2018-08-30 18:48:43 +00:00
operator=(const llarp_buffer_t& buf)
2018-06-22 00:25:30 +00:00
{
2018-08-30 18:48:43 +00:00
if(buf.sz > MAX_SIZE)
return *this;
_sz = buf.sz;
2018-08-14 21:17:18 +00:00
if(_sz)
{
memcpy(_data, buf.base, _sz);
}
2018-06-22 00:25:30 +00:00
UpdateBuffer();
return *this;
}
2018-06-20 12:34:48 +00:00
void
Fill(byte_t fill)
{
2018-06-21 12:55:02 +00:00
size_t idx = 0;
while(idx < _sz)
_data[idx++] = fill;
2018-06-20 12:34:48 +00:00
}
2018-06-12 16:45:12 +00:00
void
Randomize()
{
2018-09-06 11:46:19 +00:00
if(_sz)
2018-06-21 12:55:02 +00:00
randombytes(_data, _sz);
2018-06-12 16:45:12 +00:00
}
bool
BDecode(llarp_buffer_t* buf)
{
llarp_buffer_t strbuf;
if(!bencode_read_string(buf, &strbuf))
return false;
if(strbuf.sz == 0)
return false;
2018-08-30 18:48:43 +00:00
if(strbuf.sz > MAX_SIZE)
return false;
_sz = strbuf.sz;
2018-06-21 12:55:02 +00:00
memcpy(_data, strbuf.base, _sz);
UpdateBuffer();
return true;
}
2018-06-11 13:25:10 +00:00
llarp_buffer_t*
Buffer()
{
return &m_Buffer;
}
2018-06-22 00:25:30 +00:00
llarp_buffer_t
Buffer() const
{
return m_Buffer;
}
2018-06-19 17:11:24 +00:00
size_t
size()
{
2018-06-21 12:55:02 +00:00
return _sz;
2018-06-19 17:11:24 +00:00
}
size_t
size() const
{
2018-06-21 12:55:02 +00:00
return _sz;
2018-06-19 17:11:24 +00:00
}
byte_t*
data()
{
2018-06-21 12:55:02 +00:00
return _data;
2018-06-19 17:11:24 +00:00
}
2018-06-21 12:55:02 +00:00
protected:
void
UpdateBuffer()
{
m_Buffer.base = data();
m_Buffer.cur = data();
m_Buffer.sz = size();
}
2018-08-30 18:48:43 +00:00
byte_t _data[MAX_SIZE];
size_t _sz = 0;
2018-06-11 13:25:10 +00:00
llarp_buffer_t m_Buffer;
};
2018-06-19 17:11:24 +00:00
} // namespace llarp
2018-06-11 13:25:10 +00:00
2018-08-30 18:48:43 +00:00
#endif