Workaround for TestMakeWebKeyboardEventWindowsKeyCode
[chromium-blink-merge.git] / crypto / signature_creator_openssl.cc
blob7a1349b5a5a845919f0312ba0cc715c7d7438db5
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"
17 namespace crypto {
19 namespace {
21 const EVP_MD* ToOpenSSLDigest(SignatureCreator::HashAlgorithm hash_alg) {
22 switch (hash_alg) {
23 case SignatureCreator::SHA1:
24 return EVP_sha1();
25 case SignatureCreator::SHA256:
26 return EVP_sha256();
28 return NULL;
31 int ToOpenSSLDigestType(SignatureCreator::HashAlgorithm hash_alg) {
32 switch (hash_alg) {
33 case SignatureCreator::SHA1:
34 return NID_sha1;
35 case SignatureCreator::SHA256:
36 return NID_sha256;
38 return NID_undef;
41 } // namespace
43 // static
44 SignatureCreator* SignatureCreator::Create(RSAPrivateKey* key,
45 HashAlgorithm hash_alg) {
46 OpenSSLErrStackTracer err_tracer(FROM_HERE);
47 scoped_ptr<SignatureCreator> result(new SignatureCreator);
48 result->key_ = key;
49 const EVP_MD* const digest = ToOpenSSLDigest(hash_alg);
50 DCHECK(digest);
51 if (!digest) {
52 return NULL;
54 if (!EVP_SignInit_ex(result->sign_context_, digest, NULL))
55 return NULL;
56 return result.release();
59 // static
60 bool SignatureCreator::Sign(RSAPrivateKey* key,
61 HashAlgorithm hash_alg,
62 const uint8* data,
63 int data_len,
64 std::vector<uint8>* signature) {
65 ScopedRSA rsa_key(EVP_PKEY_get1_RSA(key->key()));
66 if (!rsa_key)
67 return false;
68 signature->resize(RSA_size(rsa_key.get()));
70 unsigned int len = 0;
71 if (!RSA_sign(ToOpenSSLDigestType(hash_alg), data, data_len,
72 vector_as_array(signature), &len, rsa_key.get())) {
73 signature->clear();
74 return false;
76 signature->resize(len);
77 return true;
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));
98 unsigned int len = 0;
99 int rv = EVP_SignFinal(sign_context_, vector_as_array(signature), &len, key);
100 if (!rv) {
101 signature->clear();
102 return false;
104 signature->resize(len);
105 return true;
108 } // namespace crypto