proxygen
X25519.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2018-present, Facebook, Inc.
3  * All rights reserved.
4  *
5  * This source code is licensed under the BSD-style license found in the
6  * LICENSE file in the root directory of this source tree.
7  */
8 
10 
11 #include <fizz/crypto/Utils.h>
12 
13 #include <folly/Conv.h>
14 #include <sodium.h>
15 
16 using namespace folly;
17 
18 namespace fizz {
19 
20 void X25519KeyExchange::generateKeyPair() {
21  auto privKey = PrivKey();
22  auto pubKey = PubKey();
23  auto err = crypto_box_curve25519xsalsa20poly1305_keypair(
24  pubKey.data(), privKey.data());
25  if (err != 0) {
26  throw std::runtime_error(to<std::string>("Could not generate keys ", err));
27  }
28  privKey_ = std::move(privKey);
29  pubKey_ = std::move(pubKey);
30 }
31 
32 std::unique_ptr<IOBuf> X25519KeyExchange::getKeyShare() const {
33  if (!privKey_ || !pubKey_) {
34  throw std::runtime_error("Key not generated");
35  }
36  return IOBuf::copyBuffer(pubKey_->data(), pubKey_->size());
37 }
38 
39 std::unique_ptr<folly::IOBuf> X25519KeyExchange::generateSharedSecret(
40  folly::ByteRange keyShare) const {
41  if (!privKey_ || !pubKey_) {
42  throw std::runtime_error("Key not generated");
43  }
44  if (keyShare.size() != crypto_scalarmult_BYTES) {
45  throw std::runtime_error("Invalid external public key");
46  }
47  auto key = IOBuf::create(crypto_scalarmult_BYTES);
48  key->append(crypto_scalarmult_BYTES);
49  int err =
50  crypto_scalarmult(key->writableData(), privKey_->data(), keyShare.data());
51  if (err != 0) {
52  throw std::runtime_error("Invalid point");
53  }
54  return key;
55 }
56 } // namespace fizz
static std::unique_ptr< IOBuf > create(std::size_t capacity)
Definition: IOBuf.cpp:229
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
constexpr size_type size() const
Definition: Range.h:431
—— Concurrent Priority Queue Implementation ——
Definition: AtomicBitSet.h:29
std::array< uint8_t, crypto_scalarmult_BYTES > PubKey
Definition: X25519.h:33
constexpr Iter data() const
Definition: Range.h:446
Definition: Actions.h:16
std::array< uint8_t, crypto_scalarmult_SCALARBYTES > PrivKey
Definition: X25519.h:32
static std::unique_ptr< IOBuf > copyBuffer(const void *buf, std::size_t size, std::size_t headroom=0, std::size_t minTailroom=0)
Definition: IOBuf.h:1587