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"
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"
24 SECStatus
SignData(SECItem
* result
,
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
);
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
);
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
);
52 // DER encode the signature.
53 return DSAU_EncodeDerSigWithLen(result
, &sig
, sig
.len
);
58 ECSignatureCreatorImpl::ECSignatureCreatorImpl(ECPrivateKey
* key
)
63 ECSignatureCreatorImpl::~ECSignatureCreatorImpl() {}
65 bool ECSignatureCreatorImpl::Sign(const uint8
* data
,
67 std::vector
<uint8
>* signature
) {
70 secret
.type
= siBuffer
;
71 secret
.len
= data_len
;
72 secret
.data
= const_cast<unsigned char*>(data
);
74 // SECItem to receive the output buffer.
76 result
.type
= siBuffer
;
80 // Sign the secret data and save it to |result|.
82 SignData(&result
, &secret
, key_
->key(), HASH_AlgSHA1
);
83 if (rv
!= SECSuccess
) {
84 DLOG(ERROR
) << "DerSignData: " << PORT_GetError();
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| */);