xref: /aosp_15_r20/external/cronet/net/third_party/quiche/src/quiche/quic/core/crypto/p256_key_exchange.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright (c) 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef QUICHE_QUIC_CORE_CRYPTO_P256_KEY_EXCHANGE_H_
6 #define QUICHE_QUIC_CORE_CRYPTO_P256_KEY_EXCHANGE_H_
7 
8 #include <cstdint>
9 #include <string>
10 
11 #include "absl/strings/string_view.h"
12 #include "openssl/base.h"
13 #include "quiche/quic/core/crypto/key_exchange.h"
14 #include "quiche/quic/platform/api/quic_export.h"
15 
16 namespace quic {
17 
18 // P256KeyExchange implements a SynchronousKeyExchange using elliptic-curve
19 // Diffie-Hellman on NIST P-256.
20 class QUICHE_EXPORT P256KeyExchange : public SynchronousKeyExchange {
21  public:
22   ~P256KeyExchange() override;
23 
24   // New generates a private key and then creates new key-exchange object.
25   static std::unique_ptr<P256KeyExchange> New();
26 
27   // New creates a new key-exchange object from a private key. If |private_key|
28   // is invalid, nullptr is returned.
29   static std::unique_ptr<P256KeyExchange> New(absl::string_view private_key);
30 
31   // NewPrivateKey returns a private key, suitable for passing to |New|.
32   // If |NewPrivateKey| can't generate a private key, it returns an empty
33   // string.
34   static std::string NewPrivateKey();
35 
36   // SynchronousKeyExchange interface.
37   bool CalculateSharedKeySync(absl::string_view peer_public_value,
38                               std::string* shared_key) const override;
39   absl::string_view public_value() const override;
type()40   QuicTag type() const override { return kP256; }
41 
42  private:
43   enum {
44     // A P-256 field element consists of 32 bytes.
45     kP256FieldBytes = 32,
46     // A P-256 point in uncompressed form consists of 0x04 (to denote
47     // that the point is uncompressed) followed by two, 32-byte field
48     // elements.
49     kUncompressedP256PointBytes = 1 + 2 * kP256FieldBytes,
50     // The first byte in an uncompressed P-256 point.
51     kUncompressedECPointForm = 0x04,
52   };
53 
54   // P256KeyExchange wraps |private_key|, and expects |public_key| consists of
55   // |kUncompressedP256PointBytes| bytes.
56   P256KeyExchange(bssl::UniquePtr<EC_KEY> private_key,
57                   const uint8_t* public_key);
58   P256KeyExchange(const P256KeyExchange&) = delete;
59   P256KeyExchange& operator=(const P256KeyExchange&) = delete;
60 
61   bssl::UniquePtr<EC_KEY> private_key_;
62   // The public key stored as an uncompressed P-256 point.
63   uint8_t public_key_[kUncompressedP256PointBytes];
64 };
65 
66 }  // namespace quic
67 
68 #endif  // QUICHE_QUIC_CORE_CRYPTO_P256_KEY_EXCHANGE_H_
69