ec_private_key.cc 7.31 KB
Newer Older
1
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 3 4 5 6
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "crypto/ec_private_key.h"

7 8
#include <stddef.h>
#include <stdint.h>
9

10 11
#include <utility>

12
#include "base/logging.h"
13
#include "crypto/openssl_util.h"
14 15 16 17 18 19 20 21 22
#include "third_party/boringssl/src/include/openssl/bio.h"
#include "third_party/boringssl/src/include/openssl/bn.h"
#include "third_party/boringssl/src/include/openssl/bytestring.h"
#include "third_party/boringssl/src/include/openssl/ec.h"
#include "third_party/boringssl/src/include/openssl/ec_key.h"
#include "third_party/boringssl/src/include/openssl/evp.h"
#include "third_party/boringssl/src/include/openssl/mem.h"
#include "third_party/boringssl/src/include/openssl/pkcs12.h"
#include "third_party/boringssl/src/include/openssl/x509.h"
23 24 25

namespace crypto {

26
namespace {
27

28 29 30 31 32 33 34 35 36 37
// Function pointer definition, for injecting the required key export function
// into ExportKeyWithBio, below. |bio| is a temporary memory BIO object, and
// |key| is a handle to the input key object. Return 1 on success, 0 otherwise.
// NOTE: Used with OpenSSL functions, which do not comply with the Chromium
//       style guide, hence the unusual parameter placement / types.
typedef int (*ExportBioFunction)(BIO* bio, const void* key);

// Helper to export |key| into |output| via the specified ExportBioFunction.
bool ExportKeyWithBio(const void* key,
                      ExportBioFunction export_fn,
38
                      std::vector<uint8_t>* output) {
39 40 41
  if (!key)
    return false;

42
  bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_mem()));
43
  if (!bio)
44 45 46 47 48
    return false;

  if (!export_fn(bio.get(), key))
    return false;

49 50 51
  const uint8_t* data;
  size_t len;
  if (!BIO_mem_contents(bio.get(), &data, &len))
52 53 54 55
    return false;

  output->assign(data, data + len);
  return true;
56 57
}

58 59
}  // namespace

60
ECPrivateKey::~ECPrivateKey() {}
61

62
// static
63
std::unique_ptr<ECPrivateKey> ECPrivateKey::Create() {
64 65
  OpenSSLErrStackTracer err_tracer(FROM_HERE);

66 67
  bssl::UniquePtr<EC_KEY> ec_key(
      EC_KEY_new_by_curve_name(NID_X9_62_prime256v1));
68 69
  if (!ec_key || !EC_KEY_generate_key(ec_key.get()))
    return nullptr;
70

thakis's avatar
thakis committed
71
  std::unique_ptr<ECPrivateKey> result(new ECPrivateKey());
72 73
  result->key_.reset(EVP_PKEY_new());
  if (!result->key_ || !EVP_PKEY_set1_EC_KEY(result->key_.get(), ec_key.get()))
74
    return nullptr;
75

76
  CHECK_EQ(EVP_PKEY_EC, EVP_PKEY_id(result->key_.get()));
77
  return result;
78 79
}

80 81 82 83 84 85 86
// static
std::unique_ptr<ECPrivateKey> ECPrivateKey::CreateFromPrivateKeyInfo(
    const std::vector<uint8_t>& input) {
  OpenSSLErrStackTracer err_tracer(FROM_HERE);

  CBS cbs;
  CBS_init(&cbs, input.data(), input.size());
87
  bssl::UniquePtr<EVP_PKEY> pkey(EVP_parse_private_key(&cbs));
88 89 90
  if (!pkey || CBS_len(&cbs) != 0 || EVP_PKEY_id(pkey.get()) != EVP_PKEY_EC)
    return nullptr;

91
  std::unique_ptr<ECPrivateKey> result(new ECPrivateKey());
92
  result->key_ = std::move(pkey);
93 94 95
  return result;
}

96
// static
97
std::unique_ptr<ECPrivateKey> ECPrivateKey::CreateFromEncryptedPrivateKeyInfo(
98 99
    const std::vector<uint8_t>& encrypted_private_key_info,
    const std::vector<uint8_t>& subject_public_key_info) {
100 101 102 103
  // NOTE: The |subject_public_key_info| can be ignored here, it is only
  // useful for the NSS implementation (which uses the public key's SHA1
  // as a lookup key when storing the private one in its store).
  if (encrypted_private_key_info.empty())
104
    return nullptr;
105 106 107

  OpenSSLErrStackTracer err_tracer(FROM_HERE);

108 109
  const uint8_t* data = &encrypted_private_key_info[0];
  const uint8_t* ptr = data;
110
  bssl::UniquePtr<X509_SIG> p8_encrypted(
111
      d2i_X509_SIG(nullptr, &ptr, encrypted_private_key_info.size()));
112
  if (!p8_encrypted || ptr != data + encrypted_private_key_info.size())
113
    return nullptr;
114

115 116 117 118 119 120 121 122 123
  // Hack for reading keys generated by an older version of the OpenSSL code.
  // Some implementations encode the empty password as "\0\0" (passwords are
  // normally encoded in big-endian UCS-2 with a NUL terminator) and some
  // encode as the empty string. PKCS8_decrypt distinguishes the two by whether
  // the password is nullptr.
  bssl::UniquePtr<PKCS8_PRIV_KEY_INFO> p8_decrypted(
      PKCS8_decrypt(p8_encrypted.get(), "", 0));
  if (!p8_decrypted)
    p8_decrypted.reset(PKCS8_decrypt(p8_encrypted.get(), nullptr, 0));
124 125

  if (!p8_decrypted)
126
    return nullptr;
127 128

  // Create a new EVP_PKEY for it.
129
  std::unique_ptr<ECPrivateKey> result(new ECPrivateKey());
130 131
  result->key_.reset(EVP_PKCS82PKEY(p8_decrypted.get()));
  if (!result->key_ || EVP_PKEY_id(result->key_.get()) != EVP_PKEY_EC)
132
    return nullptr;
133

134 135 136 137 138
  return result;
}

std::unique_ptr<ECPrivateKey> ECPrivateKey::Copy() const {
  std::unique_ptr<ECPrivateKey> copy(new ECPrivateKey());
139
  if (key_) {
140 141
    EVP_PKEY_up_ref(key_.get());
    copy->key_.reset(key_.get());
142
  }
143
  return copy;
144 145
}

146 147 148 149
bool ECPrivateKey::ExportPrivateKey(std::vector<uint8_t>* output) const {
  OpenSSLErrStackTracer err_tracer(FROM_HERE);
  uint8_t* der;
  size_t der_len;
150 151 152
  bssl::ScopedCBB cbb;
  if (!CBB_init(cbb.get(), 0) ||
      !EVP_marshal_private_key(cbb.get(), key_.get()) ||
153 154 155 156 157 158 159 160 161 162
      !CBB_finish(cbb.get(), &der, &der_len)) {
    return false;
  }
  output->assign(der, der + der_len);
  OPENSSL_free(der);
  return true;
}

bool ECPrivateKey::ExportEncryptedPrivateKey(
    std::vector<uint8_t>* output) const {
163 164
  OpenSSLErrStackTracer err_tracer(FROM_HERE);
  // Convert into a PKCS#8 object.
165
  bssl::UniquePtr<PKCS8_PRIV_KEY_INFO> pkcs8(EVP_PKEY2PKCS8(key_.get()));
166
  if (!pkcs8)
167 168 169 170 171 172
    return false;

  // Encrypt the object.
  // NOTE: NSS uses SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_3KEY_TRIPLE_DES_CBC
  // so use NID_pbe_WithSHA1And3_Key_TripleDES_CBC which should be the OpenSSL
  // equivalent.
173
  bssl::UniquePtr<X509_SIG> encrypted(
174 175
      PKCS8_encrypt(NID_pbe_WithSHA1And3_Key_TripleDES_CBC, nullptr, nullptr, 0,
                    nullptr, 0, 1, pkcs8.get()));
176
  if (!encrypted)
177 178 179 180 181 182
    return false;

  // Write it into |*output|
  return ExportKeyWithBio(encrypted.get(),
                          reinterpret_cast<ExportBioFunction>(i2d_PKCS8_bio),
                          output);
183 184
}

185
bool ECPrivateKey::ExportPublicKey(std::vector<uint8_t>* output) const {
186
  OpenSSLErrStackTracer err_tracer(FROM_HERE);
187 188
  uint8_t *der;
  size_t der_len;
189
  bssl::ScopedCBB cbb;
190
  if (!CBB_init(cbb.get(), 0) ||
191
      !EVP_marshal_public_key(cbb.get(), key_.get()) ||
192 193 194 195 196 197
      !CBB_finish(cbb.get(), &der, &der_len)) {
    return false;
  }
  output->assign(der, der + der_len);
  OPENSSL_free(der);
  return true;
198 199
}

200
bool ECPrivateKey::ExportRawPublicKey(std::string* output) const {
201
  OpenSSLErrStackTracer err_tracer(FROM_HERE);
202

203 204
  // Export the x and y field elements as 32-byte, big-endian numbers. (This is
  // the same as X9.62 uncompressed form without the leading 0x04 byte.)
205 206 207
  EC_KEY* ec_key = EVP_PKEY_get0_EC_KEY(key_.get());
  bssl::UniquePtr<BIGNUM> x(BN_new());
  bssl::UniquePtr<BIGNUM> y(BN_new());
208 209 210 211 212 213 214
  uint8_t buf[64];
  if (!x || !y ||
      !EC_POINT_get_affine_coordinates_GFp(EC_KEY_get0_group(ec_key),
                                           EC_KEY_get0_public_key(ec_key),
                                           x.get(), y.get(), nullptr) ||
      !BN_bn2bin_padded(buf, 32, x.get()) ||
      !BN_bn2bin_padded(buf + 32, 32, y.get())) {
215
    return false;
216
  }
217

218
  output->assign(reinterpret_cast<const char*>(buf), sizeof(buf));
219 220 221
  return true;
}

222
ECPrivateKey::ECPrivateKey() {}
223

224
}  // namespace crypto