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