lokinet/llarp/service/async_key_exchange.cpp

80 lines
2.6 KiB
C++
Raw Normal View History

#include <service/async_key_exchange.hpp>
#include <crypto/crypto.hpp>
#include <crypto/types.hpp>
2019-09-01 12:38:03 +00:00
#include <util/meta/memfn.hpp>
2019-09-01 13:26:16 +00:00
#include <util/thread/logic.hpp>
2019-07-30 23:42:13 +00:00
#include <utility>
namespace llarp
{
namespace service
{
2019-07-30 23:42:13 +00:00
AsyncKeyExchange::AsyncKeyExchange(
std::shared_ptr< Logic > l, ServiceInfo r, const Identity& localident,
const PQPubKey& introsetPubKey, const Introduction& remote,
IDataHandler* h, const ConvoTag& t, ProtocolType proto)
: logic(std::move(l))
, m_remote(std::move(r))
, m_LocalIdentity(localident)
, frame(std::make_shared< ProtocolFrame >())
, introPubKey(introsetPubKey)
, remoteIntro(remote)
, handler(h)
, tag(t)
{
2019-06-11 16:44:05 +00:00
msg.proto = proto;
}
void
AsyncKeyExchange::Result(std::shared_ptr< AsyncKeyExchange > self)
{
// put values
2019-08-02 09:27:27 +00:00
self->handler->PutSenderFor(self->msg.tag, self->m_remote, false);
self->handler->PutCachedSessionKeyFor(self->msg.tag, self->sharedKey);
self->handler->PutIntroFor(self->msg.tag, self->remoteIntro);
self->handler->PutReplyIntroFor(self->msg.tag, self->msg.introReply);
self->hook(self->frame);
}
void
AsyncKeyExchange::Encrypt(std::shared_ptr< AsyncKeyExchange > self)
{
// derive ntru session key component
SharedSecret K;
auto crypto = CryptoManager::instance();
crypto->pqe_encrypt(self->frame->C, K, self->introPubKey);
// randomize Nonce
self->frame->N.Randomize();
// compure post handshake session key
// PKE (A, B, N)
SharedSecret sharedSecret;
2019-06-02 21:19:10 +00:00
path_dh_func dh_client = util::memFn(&Crypto::dh_client, crypto);
if(!self->m_LocalIdentity.KeyExchange(dh_client, sharedSecret,
self->m_remote, self->frame->N))
{
LogError("failed to derive x25519 shared key component");
}
std::array< byte_t, 64 > tmp = {{0}};
// K
std::copy(K.begin(), K.end(), tmp.begin());
// H (K + PKE(A, B, N))
std::copy(sharedSecret.begin(), sharedSecret.end(), tmp.begin() + 32);
crypto->shorthash(self->sharedKey, llarp_buffer_t(tmp));
// set tag
self->msg.tag = self->tag;
// set sender
self->msg.sender = self->m_LocalIdentity.pub;
// set version
self->msg.version = LLARP_PROTO_VERSION;
// encrypt and sign
if(self->frame->EncryptAndSign(self->msg, K, self->m_LocalIdentity))
LogicCall(self->logic, std::bind(&AsyncKeyExchange::Result, self));
else
{
LogError("failed to encrypt and sign");
}
}
} // namespace service
} // namespace llarp