Home | History | Annotate | Download | only in profile_resetter
      1 // Copyright 2013 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 "chrome/browser/profile_resetter/jtl_foundation.h"
      6 
      7 #include "base/logging.h"
      8 #include "base/strings/string_number_conversions.h"
      9 #include "base/strings/string_util.h"
     10 
     11 namespace jtl_foundation {
     12 
     13 Hasher::Hasher(const std::string& seed) : hmac_(crypto::HMAC::SHA256) {
     14   if (!hmac_.Init(seed))
     15     NOTREACHED();
     16 }
     17 
     18 Hasher::~Hasher() {}
     19 
     20 std::string Hasher::GetHash(const std::string& input) const {
     21   if (cached_hashes_.find(input) == cached_hashes_.end()) {
     22     // Calculate value.
     23     unsigned char digest[kHashSizeInBytes];
     24     if (!hmac_.Sign(input, digest, arraysize(digest))) {
     25       NOTREACHED();
     26       return std::string();
     27     }
     28     // Instead of using the full SHA256, we only use the hex encoding of the
     29     // first 16 bytes.
     30     cached_hashes_[input] = base::HexEncode(digest, kHashSizeInBytes / 2);
     31     DCHECK_EQ(kHashSizeInBytes, cached_hashes_[input].size());
     32   }
     33   return cached_hashes_[input];
     34 }
     35 
     36 // static
     37 bool Hasher::IsHash(const std::string& maybe_hash) {
     38   if (maybe_hash.size() != kHashSizeInBytes)
     39     return false;
     40   for (std::string::const_iterator it = maybe_hash.begin();
     41        it != maybe_hash.end(); ++it) {
     42     if (!IsHexDigit(*it))
     43       return false;
     44   }
     45   return true;
     46 }
     47 
     48 }  // namespace jtl_foundation
     49