ipc/chromium/src/base/hmac_mac.cc

changeset 0
6474c204b198
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/ipc/chromium/src/base/hmac_mac.cc	Wed Dec 31 06:09:35 2014 +0100
     1.3 @@ -0,0 +1,69 @@
     1.4 +// Copyright (c) 2008 The Chromium Authors. All rights reserved.
     1.5 +// Use of this source code is governed by a BSD-style license that can be
     1.6 +// found in the LICENSE file.
     1.7 +
     1.8 +#include "base/hmac.h"
     1.9 +
    1.10 +#include <CommonCrypto/CommonHMAC.h>
    1.11 +
    1.12 +#include "base/logging.h"
    1.13 +
    1.14 +namespace base {
    1.15 +
    1.16 +struct HMACPlatformData {
    1.17 +  std::string key_;
    1.18 +};
    1.19 +
    1.20 +HMAC::HMAC(HashAlgorithm hash_alg)
    1.21 +    : hash_alg_(hash_alg), plat_(new HMACPlatformData()) {
    1.22 +  // Only SHA-1 digest is supported now.
    1.23 +  DCHECK(hash_alg_ == SHA1);
    1.24 +}
    1.25 +
    1.26 +bool HMAC::Init(const unsigned char *key, int key_length) {
    1.27 +  if (!plat_->key_.empty()) {
    1.28 +    // Init must not be called more than once on the same HMAC object.
    1.29 +    NOTREACHED();
    1.30 +    return false;
    1.31 +  }
    1.32 +
    1.33 +  plat_->key_.assign(reinterpret_cast<const char*>(key), key_length);
    1.34 +
    1.35 +  return true;
    1.36 +}
    1.37 +
    1.38 +HMAC::~HMAC() {
    1.39 +  // Zero out key copy.
    1.40 +  plat_->key_.assign(plat_->key_.length(), std::string::value_type());
    1.41 +  plat_->key_.clear();
    1.42 +  plat_->key_.reserve(0);
    1.43 +}
    1.44 +
    1.45 +bool HMAC::Sign(const std::string& data,
    1.46 +                unsigned char* digest,
    1.47 +                int digest_length) {
    1.48 +  CCHmacAlgorithm algorithm;
    1.49 +  int algorithm_digest_length;
    1.50 +  switch (hash_alg_) {
    1.51 +    case SHA1:
    1.52 +      algorithm = kCCHmacAlgSHA1;
    1.53 +      algorithm_digest_length = CC_SHA1_DIGEST_LENGTH;
    1.54 +      break;
    1.55 +    default:
    1.56 +      NOTREACHED();
    1.57 +      return false;
    1.58 +  }
    1.59 +
    1.60 +  if (digest_length < algorithm_digest_length) {
    1.61 +    NOTREACHED();
    1.62 +    return false;
    1.63 +  }
    1.64 +
    1.65 +  CCHmac(algorithm,
    1.66 +         plat_->key_.data(), plat_->key_.length(), data.data(), data.length(),
    1.67 +         digest);
    1.68 +
    1.69 +  return true;
    1.70 +}
    1.71 +
    1.72 +}  // namespace base

mercurial