WebKit roll 128486:128550
[chromium-blink-merge.git] / crypto / ec_signature_creator_nss.cc
bloba85b1e94fecf20299494fcffdc95c7894fb375da
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/ec_signature_creator_impl.h"
7 #include <cryptohi.h>
8 #include <pk11pub.h>
9 #include <secerr.h>
10 #include <sechash.h>
11 #if defined(OS_POSIX)
12 #include <unistd.h>
13 #endif
15 #include "base/logging.h"
16 #include "crypto/ec_private_key.h"
17 #include "crypto/nss_util.h"
18 #include "crypto/scoped_nss_types.h"
20 namespace crypto {
22 namespace {
24 SECStatus SignData(SECItem* result,
25 SECItem* input,
26 SECKEYPrivateKey* key,
27 HASH_HashType hash_type) {
28 if (key->keyType != ecKey) {
29 DLOG(FATAL) << "Should be using an EC key.";
30 PORT_SetError(SEC_ERROR_INVALID_ARGS);
31 return SECFailure;
34 // Hash the input.
35 std::vector<uint8> hash_data(HASH_ResultLen(hash_type));
36 SECStatus rv = HASH_HashBuf(
37 hash_type, &hash_data[0], input->data, input->len);
38 if (rv != SECSuccess)
39 return rv;
40 SECItem hash = {siBuffer, &hash_data[0],
41 static_cast<unsigned int>(hash_data.size())};
43 // Compute signature of hash.
44 int signature_len = PK11_SignatureLen(key);
45 std::vector<uint8> signature_data(signature_len);
46 SECItem sig = {siBuffer, &signature_data[0],
47 static_cast<unsigned int>(signature_len)};
48 rv = PK11_Sign(key, &sig, &hash);
49 if (rv != SECSuccess)
50 return rv;
52 // DER encode the signature.
53 return DSAU_EncodeDerSigWithLen(result, &sig, sig.len);
56 } // namespace
58 ECSignatureCreatorImpl::ECSignatureCreatorImpl(ECPrivateKey* key)
59 : key_(key) {
60 EnsureNSSInit();
63 ECSignatureCreatorImpl::~ECSignatureCreatorImpl() {}
65 bool ECSignatureCreatorImpl::Sign(const uint8* data,
66 int data_len,
67 std::vector<uint8>* signature) {
68 // Data to be signed
69 SECItem secret;
70 secret.type = siBuffer;
71 secret.len = data_len;
72 secret.data = const_cast<unsigned char*>(data);
74 // SECItem to receive the output buffer.
75 SECItem result;
76 result.type = siBuffer;
77 result.len = 0;
78 result.data = NULL;
80 // Sign the secret data and save it to |result|.
81 SECStatus rv =
82 SignData(&result, &secret, key_->key(), HASH_AlgSHA1);
83 if (rv != SECSuccess) {
84 DLOG(ERROR) << "DerSignData: " << PORT_GetError();
85 return false;
88 // Copy the signed data into the output vector.
89 signature->assign(result.data, result.data + result.len);
90 SECITEM_FreeItem(&result, PR_FALSE /* only free |result.data| */);
91 return true;
94 } // namespace crypto