OLD | NEW |
| (Empty) |
1 // Copyright 2015 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 #include <openssl/ec.h> | |
6 #include <openssl/ecdh.h> | |
7 #include <openssl/evp.h> | |
8 #include <stddef.h> | |
9 #include <stdint.h> | |
10 | |
11 #include <memory> | |
12 | |
13 #include "base/logging.h" | |
14 #include "base/strings/string_util.h" | |
15 #include "components/gcm_driver/crypto/p256_key_util.h" | |
16 #include "crypto/ec_private_key.h" | |
17 #include "crypto/scoped_openssl_types.h" | |
18 | |
19 namespace gcm { | |
20 | |
21 namespace { | |
22 | |
23 // A P-256 field element consists of 32 bytes. | |
24 const size_t kFieldBytes = 32; | |
25 | |
26 } // namespace | |
27 | |
28 bool ComputeSharedP256Secret(const base::StringPiece& private_key, | |
29 const base::StringPiece& public_key_x509, | |
30 const base::StringPiece& peer_public_key, | |
31 std::string* out_shared_secret) { | |
32 DCHECK(out_shared_secret); | |
33 | |
34 std::unique_ptr<crypto::ECPrivateKey> local_key_pair( | |
35 crypto::ECPrivateKey::CreateFromEncryptedPrivateKeyInfo( | |
36 "" /* no password */, | |
37 std::vector<uint8_t>(private_key.data(), | |
38 private_key.data() + private_key.size()), | |
39 std::vector<uint8_t>( | |
40 public_key_x509.data(), | |
41 public_key_x509.data() + public_key_x509.size()))); | |
42 | |
43 if (!local_key_pair) { | |
44 DLOG(ERROR) << "Unable to create the local key pair."; | |
45 return false; | |
46 } | |
47 | |
48 crypto::ScopedEC_KEY ec_private_key( | |
49 EVP_PKEY_get1_EC_KEY(local_key_pair->key())); | |
50 | |
51 if (!ec_private_key || !EC_KEY_check_key(ec_private_key.get())) { | |
52 DLOG(ERROR) << "The private key is invalid."; | |
53 return false; | |
54 } | |
55 | |
56 crypto::ScopedEC_POINT point( | |
57 EC_POINT_new(EC_KEY_get0_group(ec_private_key.get()))); | |
58 | |
59 if (!point || | |
60 !EC_POINT_oct2point(EC_KEY_get0_group(ec_private_key.get()), point.get(), | |
61 reinterpret_cast<const uint8_t*>( | |
62 peer_public_key.data()), | |
63 peer_public_key.size(), nullptr)) { | |
64 DLOG(ERROR) << "Can't convert peer public value to curve point."; | |
65 return false; | |
66 } | |
67 | |
68 uint8_t result[kFieldBytes]; | |
69 if (ECDH_compute_key(result, sizeof(result), point.get(), | |
70 ec_private_key.get(), nullptr) != sizeof(result)) { | |
71 DLOG(ERROR) << "Unable to compute the ECDH shared secret."; | |
72 return false; | |
73 } | |
74 | |
75 out_shared_secret->assign(reinterpret_cast<char*>(result), sizeof(result)); | |
76 return true; | |
77 } | |
78 | |
79 } // namespace gcm | |
OLD | NEW |