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.
5 #include "crypto/signature_creator.h"
7 #include <openssl/evp.h>
8 #include <openssl/rsa.h>
10 #include "base/logging.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "base/stl_util.h"
13 #include "crypto/openssl_util.h"
14 #include "crypto/rsa_private_key.h"
15 #include "crypto/scoped_openssl_types.h"
21 const EVP_MD
* ToOpenSSLDigest(SignatureCreator::HashAlgorithm hash_alg
) {
23 case SignatureCreator::SHA1
:
25 case SignatureCreator::SHA256
:
31 int ToOpenSSLDigestType(SignatureCreator::HashAlgorithm hash_alg
) {
33 case SignatureCreator::SHA1
:
35 case SignatureCreator::SHA256
:
44 SignatureCreator
* SignatureCreator::Create(RSAPrivateKey
* key
,
45 HashAlgorithm hash_alg
) {
46 OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
47 scoped_ptr
<SignatureCreator
> result(new SignatureCreator
);
48 const EVP_MD
* const digest
= ToOpenSSLDigest(hash_alg
);
53 if (!EVP_DigestSignInit(result
->sign_context_
, NULL
, digest
, NULL
,
57 return result
.release();
61 bool SignatureCreator::Sign(RSAPrivateKey
* key
,
62 HashAlgorithm hash_alg
,
65 std::vector
<uint8
>* signature
) {
66 ScopedRSA
rsa_key(EVP_PKEY_get1_RSA(key
->key()));
69 signature
->resize(RSA_size(rsa_key
.get()));
72 if (!RSA_sign(ToOpenSSLDigestType(hash_alg
), data
, data_len
,
73 vector_as_array(signature
), &len
, rsa_key
.get())) {
77 signature
->resize(len
);
81 SignatureCreator::SignatureCreator()
82 : sign_context_(EVP_MD_CTX_create()) {
85 SignatureCreator::~SignatureCreator() {
86 EVP_MD_CTX_destroy(sign_context_
);
89 bool SignatureCreator::Update(const uint8
* data_part
, int data_part_len
) {
90 OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
91 return !!EVP_DigestSignUpdate(sign_context_
, data_part
, data_part_len
);
94 bool SignatureCreator::Final(std::vector
<uint8
>* signature
) {
95 OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
97 // Determine the maximum length of the signature.
99 if (!EVP_DigestSignFinal(sign_context_
, NULL
, &len
)) {
103 signature
->resize(len
);
106 if (!EVP_DigestSignFinal(sign_context_
, vector_as_array(signature
), &len
)) {
110 signature
->resize(len
);
114 } // namespace crypto