OLD | NEW |
---|---|
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. | 1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. |
2 // Use of this source code is governed by a BSD-style license that can be | 2 // Use of this source code is governed by a BSD-style license that can be |
3 // found in the LICENSE file. | 3 // found in the LICENSE file. |
4 | 4 |
5 #include "components/variations/metrics_util.h" | 5 #include "components/variations/metrics_util.h" |
6 | 6 |
7 #include "base/logging.h" | |
8 #include "base/md5.h" | |
7 #include "base/sha1.h" | 9 #include "base/sha1.h" |
8 #include "base/sys_byteorder.h" | 10 #include "base/sys_byteorder.h" |
9 | 11 |
10 namespace metrics { | 12 namespace metrics { |
11 | 13 |
14 namespace { | |
15 | |
16 // Converts the 8-byte prefix of an MD5 hash into a uint64 value. | |
17 inline uint64 HashToUInt64(const std::string& hash) { | |
18 uint64 value; | |
19 DCHECK_GE(hash.size(), sizeof(value)); | |
20 memcpy(&value, hash.data(), sizeof(value)); | |
21 return base::HostToNet64(value); | |
22 } | |
23 | |
24 } // namespace | |
25 | |
12 uint32 HashName(const std::string& name) { | 26 uint32 HashName(const std::string& name) { |
13 // SHA-1 is designed to produce a uniformly random spread in its output space, | 27 // SHA-1 is designed to produce a uniformly random spread in its output space, |
14 // even for nearly-identical inputs. | 28 // even for nearly-identical inputs. |
15 unsigned char sha1_hash[base::kSHA1Length]; | 29 unsigned char sha1_hash[base::kSHA1Length]; |
16 base::SHA1HashBytes(reinterpret_cast<const unsigned char*>(name.c_str()), | 30 base::SHA1HashBytes(reinterpret_cast<const unsigned char*>(name.c_str()), |
17 name.size(), | 31 name.size(), |
18 sha1_hash); | 32 sha1_hash); |
19 | 33 |
20 uint32 bits; | 34 uint32 bits; |
21 COMPILE_ASSERT(sizeof(bits) < sizeof(sha1_hash), need_more_data); | 35 COMPILE_ASSERT(sizeof(bits) < sizeof(sha1_hash), need_more_data); |
22 memcpy(&bits, sha1_hash, sizeof(bits)); | 36 memcpy(&bits, sha1_hash, sizeof(bits)); |
23 | 37 |
24 return base::ByteSwapToLE32(bits); | 38 return base::ByteSwapToLE32(bits); |
25 } | 39 } |
26 | 40 |
41 uint64 HashMetricName(const std::string& name) { | |
42 // Create an MD5 hash of the given |name|, represented as a byte buffer | |
43 // encoded as an std::string. | |
44 base::MD5Context context; | |
45 base::MD5Init(&context); | |
46 base::MD5Update(&context, name); | |
47 | |
48 base::MD5Digest digest; | |
49 base::MD5Final(&digest, &context); | |
50 | |
51 std::string hash_str(reinterpret_cast<char*>(digest.a), arraysize(digest.a)); | |
52 uint64 hash = HashToUInt64(hash_str); | |
Alexei Svitkine (slow)
2014/02/05 18:07:01
Nit: Just return this directly.
Steven Holte
2014/02/05 22:44:37
Done.
| |
53 | |
54 return hash; | |
55 } | |
56 | |
27 } // namespace metrics | 57 } // namespace metrics |
OLD | NEW |