lokinet/include/llarp/encrypted.hpp

125 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-06-11 13:25:10 +00:00
namespace llarp
{
/// encrypted buffer base type
struct Encrypted
{
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&
operator=(llarp_buffer_t buf)
{
if(_data)
delete[] _data;
2018-08-14 21:17:18 +00:00
_data = nullptr;
2018-06-22 00:25:30 +00:00
_sz = buf.sz;
2018-08-14 21:17:18 +00:00
if(_sz)
{
_data = new byte_t[_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-06-21 12:55:02 +00:00
if(_data && _sz)
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-06-21 12:55:02 +00:00
if(_data)
delete[] _data;
_sz = strbuf.sz;
_data = new byte_t[_sz];
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();
}
byte_t* _data = nullptr;
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
#endif