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
);
55 result
->sign_context_
= SGN_NewContext(ToNSSSigOid(hash_alg
), key
->key());
56 if (!result
->sign_context_
) {
61 SECStatus rv
= SGN_Begin(result
->sign_context_
);
62 if (rv
!= SECSuccess
) {
67 return result
.release();
71 bool SignatureCreator::Sign(RSAPrivateKey
* key
,
72 HashAlgorithm hash_alg
,
75 std::vector
<uint8
>* signature
) {
77 data_item
.type
= siBuffer
;
78 data_item
.data
= const_cast<unsigned char*>(data
);
79 data_item
.len
= data_len
;
81 SECItem signature_item
;
82 SECStatus rv
= SGN_Digest(key
->key(), ToNSSHashOid(hash_alg
), &signature_item
,
84 if (rv
!= SECSuccess
) {
88 signature
->assign(signature_item
.data
,
89 signature_item
.data
+ signature_item
.len
);
90 SECITEM_FreeItem(&signature_item
, PR_FALSE
);
94 bool SignatureCreator::Update(const uint8
* data_part
, int data_part_len
) {
95 SECStatus rv
= SGN_Update(sign_context_
, data_part
, data_part_len
);
96 if (rv
!= SECSuccess
) {
104 bool SignatureCreator::Final(std::vector
<uint8
>* signature
) {
105 SECItem signature_item
;
106 SECStatus rv
= SGN_End(sign_context_
, &signature_item
);
107 if (rv
!= SECSuccess
) {
110 signature
->assign(signature_item
.data
,
111 signature_item
.data
+ signature_item
.len
);
112 SECITEM_FreeItem(&signature_item
, PR_FALSE
);
116 SignatureCreator::SignatureCreator()
118 sign_context_(NULL
) {
122 } // namespace crypto