chromeos: bluetooth: add BluetoothInputClient
[chromium-blink-merge.git] / crypto / ec_signature_creator_nss.cc
blob933f1cccf3d329c033d8240056133bedf9ce1696
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.h"
7 #include <cryptohi.h>
8 #include <pk11pub.h>
9 #include <secerr.h>
10 #include <sechash.h>
12 #include "base/logging.h"
13 #include "crypto/ec_private_key.h"
14 #include "crypto/nss_util.h"
15 #include "crypto/scoped_nss_types.h"
17 namespace crypto {
19 namespace {
21 SECStatus SignData(SECItem* result,
22 SECItem* input,
23 SECKEYPrivateKey* key,
24 HASH_HashType hash_type) {
25 if (key->keyType != ecKey) {
26 DLOG(FATAL) << "Should be using an EC key.";
27 PORT_SetError(SEC_ERROR_INVALID_ARGS);
28 return SECFailure;
31 // Hash the input.
32 std::vector<uint8> hash_data(HASH_ResultLen(hash_type));
33 SECStatus rv = HASH_HashBuf(
34 hash_type, &hash_data[0], input->data, input->len);
35 if (rv != SECSuccess)
36 return rv;
37 SECItem hash = {siBuffer, &hash_data[0], hash_data.size()};
39 // Compute signature of hash.
40 int signature_len = PK11_SignatureLen(key);
41 std::vector<uint8> signature_data(signature_len);
42 SECItem sig = {siBuffer, &signature_data[0], signature_len};
43 rv = PK11_Sign(key, &sig, &hash);
44 if (rv != SECSuccess)
45 return rv;
47 // DER encode the signature.
48 return DSAU_EncodeDerSigWithLen(result, &sig, sig.len);
51 } // namespace
53 // static
54 ECSignatureCreator* ECSignatureCreator::Create(ECPrivateKey* key) {
55 return new ECSignatureCreator(key);
58 ECSignatureCreator::ECSignatureCreator(ECPrivateKey* key)
59 : key_(key) {
60 EnsureNSSInit();
63 ECSignatureCreator::~ECSignatureCreator() { }
65 bool ECSignatureCreator::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