blob: 668b3066271074a4cd96b1b045c332c430912921 [file] [log] [blame]
[email protected]301415e2008-09-04 19:00:371// Copyright (c) 2008 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.
4
5#include "base/hmac.h"
6
7#include <CommonCrypto/CommonHMAC.h>
8
9#include "base/logging.h"
10
11namespace base {
12
[email protected]fbcfafe2008-09-08 13:58:1013struct HMACPlatformData {
14 std::string key_;
15};
16
[email protected]301415e2008-09-04 19:00:3717HMAC::HMAC(HashAlgorithm hash_alg, const unsigned char* key, int key_length)
[email protected]fbcfafe2008-09-08 13:58:1018 : hash_alg_(hash_alg), plat_(new HMACPlatformData()) {
19 plat_->key_.assign(reinterpret_cast<const char*>(key), key_length);
[email protected]301415e2008-09-04 19:00:3720}
21
22HMAC::~HMAC() {
23 // Zero out key copy.
[email protected]fbcfafe2008-09-08 13:58:1024 plat_->key_.assign(plat_->key_.length(), std::string::value_type());
25 plat_->key_.clear();
26 plat_->key_.reserve(0);
[email protected]301415e2008-09-04 19:00:3727}
28
29bool HMAC::Sign(const std::string& data,
30 unsigned char* digest,
31 int digest_length) {
32 CCHmacAlgorithm algorithm;
33 int algorithm_digest_length;
34 switch (hash_alg_) {
35 case SHA1:
36 algorithm = kCCHmacAlgSHA1;
37 algorithm_digest_length = CC_SHA1_DIGEST_LENGTH;
38 break;
39 default:
40 NOTREACHED();
41 return false;
42 }
43
44 if (digest_length < algorithm_digest_length) {
45 NOTREACHED();
46 return false;
47 }
48
49 CCHmac(algorithm,
[email protected]fbcfafe2008-09-08 13:58:1050 plat_->key_.data(), plat_->key_.length(), data.data(), data.length(),
[email protected]301415e2008-09-04 19:00:3751 digest);
52
53 return true;
54}
55
56} // namespace base