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"
11 #include "base/logging.h"
12 #include "base/memory/scoped_ptr.h"
13 #include "crypto/nss_util.h"
14 #include "crypto/rsa_private_key.h"
20 SECOidTag
ToNSSSigOid(SignatureCreator::HashAlgorithm hash_alg
) {
22 case SignatureCreator::SHA1
:
23 return SEC_OID_PKCS1_SHA1_WITH_RSA_ENCRYPTION
;
24 case SignatureCreator::SHA256
:
25 return SEC_OID_PKCS1_SHA256_WITH_RSA_ENCRYPTION
;
27 return SEC_OID_UNKNOWN
;
30 SECOidTag
ToNSSHashOid(SignatureCreator::HashAlgorithm hash_alg
) {
32 case SignatureCreator::SHA1
:
34 case SignatureCreator::SHA256
:
35 return SEC_OID_SHA256
;
37 return SEC_OID_UNKNOWN
;
42 SignatureCreator::~SignatureCreator() {
44 SGN_DestroyContext(sign_context_
, PR_TRUE
);
50 SignatureCreator
* SignatureCreator::Create(RSAPrivateKey
* key
,
51 HashAlgorithm hash_alg
) {
52 scoped_ptr
<SignatureCreator
> result(new SignatureCreator
);
53 result
->sign_context_
= SGN_NewContext(ToNSSSigOid(hash_alg
), key
->key());
54 if (!result
->sign_context_
) {
59 SECStatus rv
= SGN_Begin(result
->sign_context_
);
60 if (rv
!= SECSuccess
) {
65 return result
.release();
69 bool SignatureCreator::Sign(RSAPrivateKey
* key
,
70 HashAlgorithm hash_alg
,
73 std::vector
<uint8
>* signature
) {
75 data_item
.type
= siBuffer
;
76 data_item
.data
= const_cast<unsigned char*>(data
);
77 data_item
.len
= data_len
;
79 SECItem signature_item
;
80 SECStatus rv
= SGN_Digest(key
->key(), ToNSSHashOid(hash_alg
), &signature_item
,
82 if (rv
!= SECSuccess
) {
86 signature
->assign(signature_item
.data
,
87 signature_item
.data
+ signature_item
.len
);
88 SECITEM_FreeItem(&signature_item
, PR_FALSE
);
92 bool SignatureCreator::Update(const uint8
* data_part
, int data_part_len
) {
93 SECStatus rv
= SGN_Update(sign_context_
, data_part
, data_part_len
);
94 if (rv
!= SECSuccess
) {
102 bool SignatureCreator::Final(std::vector
<uint8
>* signature
) {
103 SECItem signature_item
;
104 SECStatus rv
= SGN_End(sign_context_
, &signature_item
);
105 if (rv
!= SECSuccess
) {
108 signature
->assign(signature_item
.data
,
109 signature_item
.data
+ signature_item
.len
);
110 SECITEM_FreeItem(&signature_item
, PR_FALSE
);
114 SignatureCreator::SignatureCreator() : sign_context_(NULL
) {
118 } // namespace crypto