1 // Copyright (c) 2011 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/hmac.h"
10 #include "base/logging.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "crypto/nss_util.h"
13 #include "crypto/scoped_nss_types.h"
17 struct HMACPlatformData
{
18 CK_MECHANISM_TYPE mechanism_
;
20 ScopedPK11SymKey sym_key_
;
23 HMAC::HMAC(HashAlgorithm hash_alg
)
24 : hash_alg_(hash_alg
), plat_(new HMACPlatformData()) {
25 // Only SHA-1 and SHA-256 hash algorithms are supported.
28 plat_
->mechanism_
= CKM_SHA_1_HMAC
;
31 plat_
->mechanism_
= CKM_SHA256_HMAC
;
34 NOTREACHED() << "Unsupported hash algorithm";
42 bool HMAC::Init(const unsigned char *key
, size_t key_length
) {
45 if (plat_
->slot_
.get()) {
46 // Init must not be called more than twice on the same HMAC object.
51 plat_
->slot_
.reset(PK11_GetInternalSlot());
52 if (!plat_
->slot_
.get()) {
58 key_item
.type
= siBuffer
;
59 key_item
.data
= const_cast<unsigned char*>(key
); // NSS API isn't const.
60 key_item
.len
= key_length
;
62 plat_
->sym_key_
.reset(PK11_ImportSymKey(plat_
->slot_
.get(),
68 if (!plat_
->sym_key_
.get()) {
76 bool HMAC::Sign(const base::StringPiece
& data
,
77 unsigned char* digest
,
78 size_t digest_length
) const {
79 if (!plat_
->sym_key_
.get()) {
80 // Init has not been called before Sign.
85 SECItem param
= { siBuffer
, NULL
, 0 };
86 ScopedPK11Context
context(PK11_CreateContextBySymKey(plat_
->mechanism_
,
88 plat_
->sym_key_
.get(),
95 if (PK11_DigestBegin(context
.get()) != SECSuccess
) {
100 if (PK11_DigestOp(context
.get(),
101 reinterpret_cast<const unsigned char*>(data
.data()),
102 data
.length()) != SECSuccess
) {
107 unsigned int len
= 0;
108 if (PK11_DigestFinal(context
.get(),
109 digest
, &len
, digest_length
) != SECSuccess
) {
117 } // namespace crypto