Move clients of BrowserContextKeyedService to using KeyedService (#3)
[chromium-blink-merge.git] / crypto / hmac_nss.cc
blobe14282c916616ce1146dd8b2820f0d5226f5b482
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"
7 #include <nss.h>
8 #include <pk11pub.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"
15 namespace crypto {
17 struct HMACPlatformData {
18 CK_MECHANISM_TYPE mechanism_;
19 ScopedPK11Slot slot_;
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.
26 switch (hash_alg_) {
27 case SHA1:
28 plat_->mechanism_ = CKM_SHA_1_HMAC;
29 break;
30 case SHA256:
31 plat_->mechanism_ = CKM_SHA256_HMAC;
32 break;
33 default:
34 NOTREACHED() << "Unsupported hash algorithm";
35 break;
39 HMAC::~HMAC() {
42 bool HMAC::Init(const unsigned char *key, size_t key_length) {
43 EnsureNSSInit();
45 if (plat_->slot_.get()) {
46 // Init must not be called more than twice on the same HMAC object.
47 NOTREACHED();
48 return false;
51 plat_->slot_.reset(PK11_GetInternalSlot());
52 if (!plat_->slot_.get()) {
53 NOTREACHED();
54 return false;
57 SECItem key_item;
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(),
63 plat_->mechanism_,
64 PK11_OriginUnwrap,
65 CKA_SIGN,
66 &key_item,
67 NULL));
68 if (!plat_->sym_key_.get()) {
69 NOTREACHED();
70 return false;
73 return true;
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.
81 NOTREACHED();
82 return false;
85 SECItem param = { siBuffer, NULL, 0 };
86 ScopedPK11Context context(PK11_CreateContextBySymKey(plat_->mechanism_,
87 CKA_SIGN,
88 plat_->sym_key_.get(),
89 &param));
90 if (!context.get()) {
91 NOTREACHED();
92 return false;
95 if (PK11_DigestBegin(context.get()) != SECSuccess) {
96 NOTREACHED();
97 return false;
100 if (PK11_DigestOp(context.get(),
101 reinterpret_cast<const unsigned char*>(data.data()),
102 data.length()) != SECSuccess) {
103 NOTREACHED();
104 return false;
107 unsigned int len = 0;
108 if (PK11_DigestFinal(context.get(),
109 digest, &len, digest_length) != SECSuccess) {
110 NOTREACHED();
111 return false;
114 return true;
117 } // namespace crypto