Wed, 31 Dec 2014 06:09:35 +0100
Cloned upstream origin tor-browser at tor-browser-31.3.0esr-4.5-1-build1
revision ID fc1c9ff7c1b2defdbc039f12214767608f46423f for hacking purpose.
michael@0 | 1 | // Copyright (c) 2008 The Chromium Authors. All rights reserved. |
michael@0 | 2 | // Use of this source code is governed by a BSD-style license that can be |
michael@0 | 3 | // found in the LICENSE file. |
michael@0 | 4 | |
michael@0 | 5 | #include "base/hmac.h" |
michael@0 | 6 | |
michael@0 | 7 | #include <CommonCrypto/CommonHMAC.h> |
michael@0 | 8 | |
michael@0 | 9 | #include "base/logging.h" |
michael@0 | 10 | |
michael@0 | 11 | namespace base { |
michael@0 | 12 | |
michael@0 | 13 | struct HMACPlatformData { |
michael@0 | 14 | std::string key_; |
michael@0 | 15 | }; |
michael@0 | 16 | |
michael@0 | 17 | HMAC::HMAC(HashAlgorithm hash_alg) |
michael@0 | 18 | : hash_alg_(hash_alg), plat_(new HMACPlatformData()) { |
michael@0 | 19 | // Only SHA-1 digest is supported now. |
michael@0 | 20 | DCHECK(hash_alg_ == SHA1); |
michael@0 | 21 | } |
michael@0 | 22 | |
michael@0 | 23 | bool HMAC::Init(const unsigned char *key, int key_length) { |
michael@0 | 24 | if (!plat_->key_.empty()) { |
michael@0 | 25 | // Init must not be called more than once on the same HMAC object. |
michael@0 | 26 | NOTREACHED(); |
michael@0 | 27 | return false; |
michael@0 | 28 | } |
michael@0 | 29 | |
michael@0 | 30 | plat_->key_.assign(reinterpret_cast<const char*>(key), key_length); |
michael@0 | 31 | |
michael@0 | 32 | return true; |
michael@0 | 33 | } |
michael@0 | 34 | |
michael@0 | 35 | HMAC::~HMAC() { |
michael@0 | 36 | // Zero out key copy. |
michael@0 | 37 | plat_->key_.assign(plat_->key_.length(), std::string::value_type()); |
michael@0 | 38 | plat_->key_.clear(); |
michael@0 | 39 | plat_->key_.reserve(0); |
michael@0 | 40 | } |
michael@0 | 41 | |
michael@0 | 42 | bool HMAC::Sign(const std::string& data, |
michael@0 | 43 | unsigned char* digest, |
michael@0 | 44 | int digest_length) { |
michael@0 | 45 | CCHmacAlgorithm algorithm; |
michael@0 | 46 | int algorithm_digest_length; |
michael@0 | 47 | switch (hash_alg_) { |
michael@0 | 48 | case SHA1: |
michael@0 | 49 | algorithm = kCCHmacAlgSHA1; |
michael@0 | 50 | algorithm_digest_length = CC_SHA1_DIGEST_LENGTH; |
michael@0 | 51 | break; |
michael@0 | 52 | default: |
michael@0 | 53 | NOTREACHED(); |
michael@0 | 54 | return false; |
michael@0 | 55 | } |
michael@0 | 56 | |
michael@0 | 57 | if (digest_length < algorithm_digest_length) { |
michael@0 | 58 | NOTREACHED(); |
michael@0 | 59 | return false; |
michael@0 | 60 | } |
michael@0 | 61 | |
michael@0 | 62 | CCHmac(algorithm, |
michael@0 | 63 | plat_->key_.data(), plat_->key_.length(), data.data(), data.length(), |
michael@0 | 64 | digest); |
michael@0 | 65 | |
michael@0 | 66 | return true; |
michael@0 | 67 | } |
michael@0 | 68 | |
michael@0 | 69 | } // namespace base |