Index: base/nonce.h |
diff --git a/base/nonce.h b/base/nonce.h |
new file mode 100644 |
index 0000000000000000000000000000000000000000..4d3656c41278beddcd041c6e7256d6da29e5c746 |
--- /dev/null |
+++ b/base/nonce.h |
@@ -0,0 +1,77 @@ |
+// Copyright 2016 The Chromium Authors. All rights reserved. |
+// Use of this source code is governed by a BSD-style license that can be |
+// found in the LICENSE file. |
+ |
+#ifndef BASE_NONCE_H_ |
+#define BASE_NONCE_H_ |
+ |
+#include <stdint.h> |
+#include <string.h> |
+#include <tuple> |
+ |
+#include "base/base_export.h" |
+#include "base/hash.h" |
+ |
+namespace base { |
+ |
+// An Nonce is a cryptographically strong, randomly generated, unguessable 128 |
+// bit token. |
+// |
+// TO CREATE NEW NONCES, ONLY USE GENERATE()! |
+// The Generate() function is guaranteed to be cryptographically strong random. |
+// Deserialize() is only meant to deserialize Nonces that were created via |
+// Generate(), and sent accross processes as two uint64_t. |
+class BASE_EXPORT Nonce { |
+ public: |
+ // Generates a unique, strongly random, unguessable nonce. |
+ // USE THIS FUNCTION TO GENERATE NEW NONCES. |
+ static Nonce Generate(); |
+ |
+ // Returns a nonce built from the high/low bytes provided. |
+ // It should only be used in deserialization scenarios. |
+ static Nonce Deserialize(uint64_t high, uint64_t low); |
+ |
+ // Creates a null Nonce. |
Tom Sepez
2016/09/13 18:20:41
Actually, wouldn't this create an uninitialized no
tguilbert
2016/09/13 20:20:19
It does create a (0,0) Nonce (and I have a UT to m
Tom Sepez
2016/09/13 21:29:39
Ok, yes if the ctor is called, so your test Nonce(
|
+ Nonce() = default; |
+ |
+ bool is_null() const { return high_ == 0 && low_ == 0; } |
+ |
+ uint64_t high() const { return high_; } |
+ |
+ uint64_t low() const { return low_; } |
+ |
+ std::string ToString() const; |
+ |
+ bool operator<(const Nonce& other) const { |
+ return std::tie(high_, low_) < std::tie(other.high_, other.low_); |
+ } |
+ |
+ bool operator==(const Nonce& other) const { |
+ return high_ == other.high_ && low_ == other.low_; |
+ } |
+ |
+ bool operator!=(const Nonce& other) const { return !operator==(other); } |
+ |
+ private: |
+ Nonce(uint64_t high, uint64_t low); |
+ |
+ // Note: Two uint64_t are used instead of uint8_t[16], in order to have a |
+ // simpler ToString() and is_null(). |
+ uint64_t high_; |
+ uint64_t low_; |
+}; |
+ |
+// For use in std::unorderer_map. |
+struct NonceHash { |
+ size_t operator()(const base::Nonce& nonce) const { |
+ return base::HashInts64(nonce.high(), nonce.low()); |
+ } |
+}; |
+ |
+// If base::Nonce is not a POD, the IPC serialization logic should be revisited, |
+// since it might no longer be possible to memcpy base::Nonce safely. |
+static_assert(std::is_pod<Nonce>::value, "base::Nonce should be of POD type."); |
+ |
+} // namespace base |
+ |
+#endif // BASE_NONCE_H_ |