[email protected] | 301415e | 2008-09-04 19:00:37 | [diff] [blame] | 1 | // 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 | |
| 11 | namespace base { |
| 12 | |
[email protected] | fbcfafe | 2008-09-08 13:58:10 | [diff] [blame] | 13 | struct HMACPlatformData { |
| 14 | std::string key_; |
| 15 | }; |
| 16 | |
[email protected] | 301415e | 2008-09-04 19:00:37 | [diff] [blame] | 17 | HMAC::HMAC(HashAlgorithm hash_alg, const unsigned char* key, int key_length) |
[email protected] | fbcfafe | 2008-09-08 13:58:10 | [diff] [blame] | 18 | : hash_alg_(hash_alg), plat_(new HMACPlatformData()) { |
| 19 | plat_->key_.assign(reinterpret_cast<const char*>(key), key_length); |
[email protected] | 301415e | 2008-09-04 19:00:37 | [diff] [blame] | 20 | } |
| 21 | |
| 22 | HMAC::~HMAC() { |
| 23 | // Zero out key copy. |
[email protected] | fbcfafe | 2008-09-08 13:58:10 | [diff] [blame] | 24 | plat_->key_.assign(plat_->key_.length(), std::string::value_type()); |
| 25 | plat_->key_.clear(); |
| 26 | plat_->key_.reserve(0); |
[email protected] | 301415e | 2008-09-04 19:00:37 | [diff] [blame] | 27 | } |
| 28 | |
| 29 | bool 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] | fbcfafe | 2008-09-08 13:58:10 | [diff] [blame] | 50 | plat_->key_.data(), plat_->key_.length(), data.data(), data.length(), |
[email protected] | 301415e | 2008-09-04 19:00:37 | [diff] [blame] | 51 | digest); |
| 52 | |
| 53 | return true; |
| 54 | } |
| 55 | |
| 56 | } // namespace base |