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
);
49 const EVP_MD
* const digest
= ToOpenSSLDigest(hash_alg
);
54 if (!EVP_SignInit_ex(result
->sign_context_
, digest
, NULL
))
56 return result
.release();
60 bool SignatureCreator::Sign(RSAPrivateKey
* key
,
61 HashAlgorithm hash_alg
,
64 std::vector
<uint8
>* signature
) {
65 ScopedRSA
rsa_key(EVP_PKEY_get1_RSA(key
->key()));
68 signature
->resize(RSA_size(rsa_key
.get()));
71 if (!RSA_sign(ToOpenSSLDigestType(hash_alg
), data
, data_len
,
72 vector_as_array(signature
), &len
, rsa_key
.get())) {
76 signature
->resize(len
);
80 SignatureCreator::SignatureCreator()
81 : sign_context_(EVP_MD_CTX_create()) {
84 SignatureCreator::~SignatureCreator() {
85 EVP_MD_CTX_destroy(sign_context_
);
88 bool SignatureCreator::Update(const uint8
* data_part
, int data_part_len
) {
89 OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
90 return EVP_SignUpdate(sign_context_
, data_part
, data_part_len
) == 1;
93 bool SignatureCreator::Final(std::vector
<uint8
>* signature
) {
94 OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
95 EVP_PKEY
* key
= key_
->key();
96 signature
->resize(EVP_PKEY_size(key
));
99 int rv
= EVP_SignFinal(sign_context_
, vector_as_array(signature
), &len
, key
);
104 signature
->resize(len
);
108 } // namespace crypto