Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / components / webcrypto / algorithms / ecdsa.cc
blob18857c77a488d9cc397b69b68d2d33483285e845
1 // Copyright 2014 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.
5 #include <openssl/ec.h>
6 #include <openssl/ec_key.h>
7 #include <openssl/evp.h>
9 #include "base/logging.h"
10 #include "base/stl_util.h"
11 #include "components/webcrypto/algorithm_implementation.h"
12 #include "components/webcrypto/algorithms/ec.h"
13 #include "components/webcrypto/algorithms/util_openssl.h"
14 #include "components/webcrypto/crypto_data.h"
15 #include "components/webcrypto/generate_key_result.h"
16 #include "components/webcrypto/key.h"
17 #include "components/webcrypto/status.h"
18 #include "components/webcrypto/webcrypto_util.h"
19 #include "crypto/openssl_util.h"
20 #include "crypto/scoped_openssl_types.h"
21 #include "crypto/secure_util.h"
22 #include "third_party/WebKit/public/platform/WebCryptoAlgorithmParams.h"
23 #include "third_party/WebKit/public/platform/WebCryptoKey.h"
24 #include "third_party/WebKit/public/platform/WebCryptoKeyAlgorithm.h"
26 namespace webcrypto {
28 namespace {
30 // Extracts the OpenSSL key and digest from a WebCrypto key + algorithm. The
31 // returned pkey pointer will remain valid as long as |key| is alive.
32 Status GetPKeyAndDigest(const blink::WebCryptoAlgorithm& algorithm,
33 const blink::WebCryptoKey& key,
34 EVP_PKEY** pkey,
35 const EVP_MD** digest) {
36 *pkey = GetEVP_PKEY(key);
37 *digest = GetDigest(algorithm.ecdsaParams()->hash().id());
38 if (!*digest)
39 return Status::ErrorUnsupported();
40 return Status::Success();
43 // Gets the EC key's order size in bytes.
44 Status GetEcGroupOrderSize(EVP_PKEY* pkey, size_t* order_size_bytes) {
45 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
47 crypto::ScopedEC_KEY ec(EVP_PKEY_get1_EC_KEY(pkey));
48 if (!ec.get())
49 return Status::ErrorUnexpected();
51 const EC_GROUP* group = EC_KEY_get0_group(ec.get());
53 crypto::ScopedBIGNUM order(BN_new());
54 if (!EC_GROUP_get_order(group, order.get(), NULL))
55 return Status::OperationError();
57 *order_size_bytes = BN_num_bytes(order.get());
58 return Status::Success();
61 // Formats a DER-encoded signature (ECDSA-Sig-Value as specified in RFC 3279) to
62 // the signature format expected by WebCrypto (raw concatenated "r" and "s").
64 // TODO(eroman): Where is the specification for WebCrypto's signature format?
65 Status ConvertDerSignatureToWebCryptoSignature(
66 EVP_PKEY* key,
67 std::vector<uint8_t>* signature) {
68 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
70 const unsigned char* der_data = vector_as_array(signature);
71 crypto::ScopedECDSA_SIG ecdsa_sig(
72 d2i_ECDSA_SIG(NULL, &der_data, static_cast<long>(signature->size())));
73 if (!ecdsa_sig.get())
74 return Status::ErrorUnexpected();
76 // |der_data| is updated to point to past the end of the DER structure.
77 if (der_data != vector_as_array(signature) + signature->size())
78 return Status::ErrorUnexpected();
80 // Determine the maximum length of r and s.
81 size_t order_size_bytes;
82 Status status = GetEcGroupOrderSize(key, &order_size_bytes);
83 if (status.IsError())
84 return status;
86 signature->resize(order_size_bytes * 2);
88 if (!BN_bn2bin_padded(vector_as_array(signature), order_size_bytes,
89 ecdsa_sig.get()->r)) {
90 return Status::ErrorUnexpected();
93 if (!BN_bn2bin_padded(&(*signature)[order_size_bytes], order_size_bytes,
94 ecdsa_sig.get()->s)) {
95 return Status::ErrorUnexpected();
98 return Status::Success();
101 // Formats a WebCrypto ECDSA signature to a DER-encoded signature
102 // (ECDSA-Sig-Value as specified in RFC 3279).
104 // TODO(eroman): What is the specification for WebCrypto's signature format?
106 // If the signature length is incorrect (not 2 * order_size), then
107 // Status::Success() is returned and |*incorrect_length| is set to true;
109 // Otherwise on success, der_signature is filled with a ASN.1 encoded
110 // ECDSA-Sig-Value.
111 Status ConvertWebCryptoSignatureToDerSignature(
112 EVP_PKEY* key,
113 const CryptoData& signature,
114 std::vector<uint8_t>* der_signature,
115 bool* incorrect_length) {
116 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
118 // Determine the length of r and s.
119 size_t order_size_bytes;
120 Status status = GetEcGroupOrderSize(key, &order_size_bytes);
121 if (status.IsError())
122 return status;
124 // If the size of the signature is incorrect, verification must fail. Success
125 // is returned here rather than an error, so that the caller can fail
126 // verification with a boolean, rather than reject the promise with an
127 // exception.
128 if (signature.byte_length() != 2 * order_size_bytes) {
129 *incorrect_length = true;
130 return Status::Success();
133 *incorrect_length = false;
135 // Construct an ECDSA_SIG from |signature|.
136 crypto::ScopedECDSA_SIG ecdsa_sig(ECDSA_SIG_new());
137 if (!ecdsa_sig)
138 return Status::OperationError();
140 if (!BN_bin2bn(signature.bytes(), order_size_bytes, ecdsa_sig->r) ||
141 !BN_bin2bn(signature.bytes() + order_size_bytes, order_size_bytes,
142 ecdsa_sig->s)) {
143 return Status::ErrorUnexpected();
146 // Determine the size of the DER-encoded signature.
147 int der_encoding_size = i2d_ECDSA_SIG(ecdsa_sig.get(), NULL);
148 if (der_encoding_size < 0)
149 return Status::OperationError();
151 // DER-encode the signature.
152 der_signature->resize(der_encoding_size);
153 uint8_t* result = vector_as_array(der_signature);
154 if (0 > i2d_ECDSA_SIG(ecdsa_sig.get(), &result))
155 return Status::OperationError();
157 return Status::Success();
160 class EcdsaImplementation : public EcAlgorithm {
161 public:
162 EcdsaImplementation()
163 : EcAlgorithm(blink::WebCryptoKeyUsageVerify,
164 blink::WebCryptoKeyUsageSign) {}
166 const char* GetJwkAlgorithm(
167 const blink::WebCryptoNamedCurve curve) const override {
168 switch (curve) {
169 case blink::WebCryptoNamedCurveP256:
170 return "ES256";
171 case blink::WebCryptoNamedCurveP384:
172 return "ES384";
173 case blink::WebCryptoNamedCurveP521:
174 // This is not a typo! ES512 means P-521 with SHA-512.
175 return "ES512";
176 default:
177 return NULL;
181 Status Sign(const blink::WebCryptoAlgorithm& algorithm,
182 const blink::WebCryptoKey& key,
183 const CryptoData& data,
184 std::vector<uint8_t>* buffer) const override {
185 if (key.type() != blink::WebCryptoKeyTypePrivate)
186 return Status::ErrorUnexpectedKeyType();
188 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
189 crypto::ScopedEVP_MD_CTX ctx(EVP_MD_CTX_create());
191 EVP_PKEY* private_key = NULL;
192 const EVP_MD* digest = NULL;
193 Status status = GetPKeyAndDigest(algorithm, key, &private_key, &digest);
194 if (status.IsError())
195 return status;
197 // NOTE: A call to EVP_DigestSignFinal() with a NULL second parameter
198 // returns a maximum allocation size, while the call without a NULL returns
199 // the real one, which may be smaller.
200 size_t sig_len = 0;
201 if (!ctx.get() ||
202 !EVP_DigestSignInit(ctx.get(), NULL, digest, NULL, private_key) ||
203 !EVP_DigestSignUpdate(ctx.get(), data.bytes(), data.byte_length()) ||
204 !EVP_DigestSignFinal(ctx.get(), NULL, &sig_len)) {
205 return Status::OperationError();
208 buffer->resize(sig_len);
209 if (!EVP_DigestSignFinal(ctx.get(), vector_as_array(buffer), &sig_len))
210 return Status::OperationError();
211 buffer->resize(sig_len);
213 // ECDSA signing in BoringSSL outputs a DER-encoded (r,s). WebCrypto however
214 // expects a padded bitstring that is r concatenated to s. Convert to the
215 // expected format.
216 return ConvertDerSignatureToWebCryptoSignature(private_key, buffer);
219 Status Verify(const blink::WebCryptoAlgorithm& algorithm,
220 const blink::WebCryptoKey& key,
221 const CryptoData& signature,
222 const CryptoData& data,
223 bool* signature_match) const override {
224 if (key.type() != blink::WebCryptoKeyTypePublic)
225 return Status::ErrorUnexpectedKeyType();
227 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
228 crypto::ScopedEVP_MD_CTX ctx(EVP_MD_CTX_create());
230 EVP_PKEY* public_key = NULL;
231 const EVP_MD* digest = NULL;
232 Status status = GetPKeyAndDigest(algorithm, key, &public_key, &digest);
233 if (status.IsError())
234 return status;
236 std::vector<uint8_t> der_signature;
237 bool incorrect_length_signature = false;
238 status = ConvertWebCryptoSignatureToDerSignature(
239 public_key, signature, &der_signature, &incorrect_length_signature);
240 if (status.IsError())
241 return status;
243 if (incorrect_length_signature) {
244 *signature_match = false;
245 return Status::Success();
248 if (!EVP_DigestVerifyInit(ctx.get(), NULL, digest, NULL, public_key) ||
249 !EVP_DigestVerifyUpdate(ctx.get(), data.bytes(), data.byte_length())) {
250 return Status::OperationError();
253 *signature_match =
254 1 == EVP_DigestVerifyFinal(ctx.get(), vector_as_array(&der_signature),
255 der_signature.size());
256 return Status::Success();
260 } // namespace
262 scoped_ptr<AlgorithmImplementation> CreateEcdsaImplementation() {
263 return make_scoped_ptr(new EcdsaImplementation);
266 } // namespace webcrypto