Upload upstream chromium 67.0.3396
[platform/framework/web/chromium-efl.git] / crypto / ec_signature_creator_impl.cc
1 // Copyright (c) 2012 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 "crypto/ec_signature_creator_impl.h"
6
7 #include <stddef.h>
8 #include <stdint.h>
9
10 #include "base/logging.h"
11 #include "crypto/ec_private_key.h"
12 #include "crypto/openssl_util.h"
13 #include "third_party/boringssl/src/include/openssl/bn.h"
14 #include "third_party/boringssl/src/include/openssl/ec.h"
15 #include "third_party/boringssl/src/include/openssl/ecdsa.h"
16 #include "third_party/boringssl/src/include/openssl/evp.h"
17 #include "third_party/boringssl/src/include/openssl/sha.h"
18
19 namespace crypto {
20
21 ECSignatureCreatorImpl::ECSignatureCreatorImpl(ECPrivateKey* key)
22     : key_(key) {
23   EnsureOpenSSLInit();
24 }
25
26 ECSignatureCreatorImpl::~ECSignatureCreatorImpl() = default;
27
28 bool ECSignatureCreatorImpl::Sign(const uint8_t* data,
29                                   int data_len,
30                                   std::vector<uint8_t>* signature) {
31   OpenSSLErrStackTracer err_tracer(FROM_HERE);
32   bssl::ScopedEVP_MD_CTX ctx;
33   size_t sig_len = 0;
34   if (!ctx.get() ||
35       !EVP_DigestSignInit(ctx.get(), nullptr, EVP_sha256(), nullptr,
36                           key_->key()) ||
37       !EVP_DigestSignUpdate(ctx.get(), data, data_len) ||
38       !EVP_DigestSignFinal(ctx.get(), nullptr, &sig_len)) {
39     return false;
40   }
41
42   signature->resize(sig_len);
43   if (!EVP_DigestSignFinal(ctx.get(), &signature->front(), &sig_len))
44     return false;
45
46   // NOTE: A call to EVP_DigestSignFinal() with a nullptr second parameter
47   // returns a maximum allocation size, while the call without a nullptr
48   // returns the real one, which may be smaller.
49   signature->resize(sig_len);
50   return true;
51 }
52
53 bool ECSignatureCreatorImpl::DecodeSignature(
54     const std::vector<uint8_t>& der_sig,
55     std::vector<uint8_t>* out_raw_sig) {
56   OpenSSLErrStackTracer err_tracer(FROM_HERE);
57   // Create ECDSA_SIG object from DER-encoded data.
58   bssl::UniquePtr<ECDSA_SIG> ecdsa_sig(
59       ECDSA_SIG_from_bytes(der_sig.data(), der_sig.size()));
60   if (!ecdsa_sig.get())
61     return false;
62
63   // The result is made of two 32-byte vectors.
64   const size_t kMaxBytesPerBN = 32;
65   std::vector<uint8_t> result(2 * kMaxBytesPerBN);
66
67   if (!BN_bn2bin_padded(&result[0], kMaxBytesPerBN, ecdsa_sig->r) ||
68       !BN_bn2bin_padded(&result[kMaxBytesPerBN], kMaxBytesPerBN,
69                         ecdsa_sig->s)) {
70     return false;
71   }
72   out_raw_sig->swap(result);
73   return true;
74 }
75
76 }  // namespace crypto