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 #ifndef CHROME_BROWSER_PREFS_PREF_HASH_CALCULATOR_H_ 6 #define CHROME_BROWSER_PREFS_PREF_HASH_CALCULATOR_H_ 7 8 #include <string> 9 10 #include "base/basictypes.h" 11 #include "base/callback.h" 12 #include "base/memory/scoped_ptr.h" 13 14 namespace base { 15 class Value; 16 } // namespace base 17 18 // Calculates and validates preference value hashes. 19 class PrefHashCalculator { 20 public: 21 enum ValidationResult { 22 INVALID, 23 VALID, 24 // Valid under a deprecated but as secure algorithm. 25 VALID_SECURE_LEGACY, 26 // Valid under a deprecated and less secure algorithm. 27 VALID_WEAK_LEGACY, 28 }; 29 30 typedef base::Callback<std::string(const std::string& modern_device_id)> 31 GetLegacyDeviceIdCallback; 32 33 // Constructs a PrefHashCalculator using |seed| and |device_id|. The same 34 // parameters must be used in order to successfully validate generated hashes. 35 // |device_id| may be empty. 36 PrefHashCalculator(const std::string& seed, const std::string& device_id); 37 38 // Same as the constructor above, but also specifies that 39 // |get_legacy_device_id_callback| should be used rather than the default to 40 // obtain the legacy device id if required. 41 PrefHashCalculator( 42 const std::string& seed, 43 const std::string& device_id, 44 const GetLegacyDeviceIdCallback& get_legacy_device_id_callback); 45 46 ~PrefHashCalculator(); 47 48 // Calculates a hash value for the supplied preference |path| and |value|. 49 // |value| may be null if the preference has no value. 50 std::string Calculate(const std::string& path, const base::Value* value) 51 const; 52 53 // Validates the provided preference hash using current and legacy hashing 54 // algorithms. 55 ValidationResult Validate(const std::string& path, 56 const base::Value* value, 57 const std::string& hash) const; 58 59 private: 60 // Returns the legacy device id based off of |raw_device_id_|. This method 61 // lazily gets the legacy device id via |get_legacy_device_id_callback_| and 62 // caches the result in |legacy_device_id_instance_| for future retrievals. 63 std::string RetrieveLegacyDeviceId() const; 64 65 const std::string seed_; 66 const std::string device_id_; 67 68 // The raw device id from which the legacy device id will be derived if 69 // required. 70 const std::string raw_device_id_; 71 72 const GetLegacyDeviceIdCallback get_legacy_device_id_callback_; 73 74 // A cache for the legacy device id which is hard to compute and thus lazily 75 // computed when/if required (computing the original value for this instance 76 // is allowed in const methods). 77 mutable scoped_ptr<const std::string> legacy_device_id_instance_; 78 79 DISALLOW_COPY_AND_ASSIGN(PrefHashCalculator); 80 }; 81 82 #endif // CHROME_BROWSER_PREFS_PREF_HASH_CALCULATOR_H_ 83