1 // Copyright 2013 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 "net/cert/ct_log_verifier.h"
7 #include <openssl/evp.h>
8 #include <openssl/x509.h>
10 #include "base/logging.h"
11 #include "crypto/openssl_util.h"
12 #include "crypto/scoped_openssl_types.h"
13 #include "crypto/sha2.h"
14 #include "net/cert/signed_tree_head.h"
20 const EVP_MD
* GetEvpAlg(ct::DigitallySigned::HashAlgorithm alg
) {
22 case ct::DigitallySigned::HASH_ALGO_MD5
:
24 case ct::DigitallySigned::HASH_ALGO_SHA1
:
26 case ct::DigitallySigned::HASH_ALGO_SHA224
:
28 case ct::DigitallySigned::HASH_ALGO_SHA256
:
30 case ct::DigitallySigned::HASH_ALGO_SHA384
:
32 case ct::DigitallySigned::HASH_ALGO_SHA512
:
34 case ct::DigitallySigned::HASH_ALGO_NONE
:
43 CTLogVerifier::~CTLogVerifier() {
44 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
47 EVP_PKEY_free(public_key_
);
50 bool CTLogVerifier::Init(const base::StringPiece
& public_key
) {
51 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
53 const uint8_t* ptr
= reinterpret_cast<const uint8_t*>(public_key
.data());
54 const uint8_t* end
= ptr
+ public_key
.size();
55 public_key_
= d2i_PUBKEY(nullptr, &ptr
, public_key
.size());
56 if (!public_key_
|| ptr
!= end
)
59 key_id_
= crypto::SHA256HashString(public_key
);
61 // Right now, only RSASSA-PKCS1v15 with SHA-256 and ECDSA with SHA-256 are
63 switch (EVP_PKEY_type(public_key_
->type
)) {
65 hash_algorithm_
= ct::DigitallySigned::HASH_ALGO_SHA256
;
66 signature_algorithm_
= ct::DigitallySigned::SIG_ALGO_RSA
;
69 hash_algorithm_
= ct::DigitallySigned::HASH_ALGO_SHA256
;
70 signature_algorithm_
= ct::DigitallySigned::SIG_ALGO_ECDSA
;
73 DVLOG(1) << "Unsupported key type: " << EVP_PKEY_type(public_key_
->type
);
77 // Extra sanity check: Require RSA keys of at least 2048 bits.
78 // EVP_PKEY_size returns the size in bytes. 256 = 2048-bit RSA key.
79 if (signature_algorithm_
== ct::DigitallySigned::SIG_ALGO_RSA
&&
80 EVP_PKEY_size(public_key_
) < 256) {
81 DVLOG(1) << "Too small a public key.";
88 bool CTLogVerifier::VerifySignature(const base::StringPiece
& data_to_sign
,
89 const base::StringPiece
& signature
) {
90 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
92 const EVP_MD
* hash_alg
= GetEvpAlg(hash_algorithm_
);
97 EVP_MD_CTX_init(&ctx
);
100 1 == EVP_DigestVerifyInit(&ctx
, NULL
, hash_alg
, NULL
, public_key_
) &&
101 1 == EVP_DigestVerifyUpdate(
102 &ctx
, data_to_sign
.data(), data_to_sign
.size()) &&
103 1 == EVP_DigestVerifyFinal(
105 reinterpret_cast<const uint8_t*>(signature
.data()),
108 EVP_MD_CTX_cleanup(&ctx
);