• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2016 The Chromium Authors
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 "base/unguessable_token.h"
6 
7 #include <ostream>
8 #include <string_view>
9 
10 #include "base/check.h"
11 #include "base/format_macros.h"
12 #include "base/rand_util.h"
13 #include "build/build_config.h"
14 
15 #if !BUILDFLAG(IS_NACL)
16 #include "third_party/boringssl/src/include/openssl/mem.h"
17 #endif
18 
19 namespace base {
20 
UnguessableToken(const base::Token & token)21 UnguessableToken::UnguessableToken(const base::Token& token) : token_(token) {}
22 
23 // static
Create()24 UnguessableToken UnguessableToken::Create() {
25   Token token = Token::CreateRandom();
26   DCHECK(!token.is_zero());
27   return UnguessableToken(token);
28 }
29 
30 // static
Null()31 const UnguessableToken& UnguessableToken::Null() {
32   static const UnguessableToken null_token{};
33   return null_token;
34 }
35 
36 // static
Deserialize(uint64_t high,uint64_t low)37 std::optional<UnguessableToken> UnguessableToken::Deserialize(uint64_t high,
38                                                               uint64_t low) {
39   // Receiving a zeroed out UnguessableToken from another process means that it
40   // was never initialized via Create(). Since this method might also be used to
41   // create an UnguessableToken from data on disk, we will handle this case more
42   // gracefully since data could have been corrupted.
43   if (high == 0 && low == 0) {
44     return std::nullopt;
45   }
46   return UnguessableToken(Token{high, low});
47 }
48 
49 // static
DeserializeFromString(std::string_view string_representation)50 std::optional<UnguessableToken> UnguessableToken::DeserializeFromString(
51     std::string_view string_representation) {
52   auto token = Token::FromString(string_representation);
53   // A zeroed out token means that it's not initialized via Create().
54   if (!token.has_value() || token.value().is_zero()) {
55     return std::nullopt;
56   }
57   return UnguessableToken(token.value());
58 }
59 
operator ==(const UnguessableToken & lhs,const UnguessableToken & rhs)60 bool operator==(const UnguessableToken& lhs, const UnguessableToken& rhs) {
61 #if BUILDFLAG(IS_NACL)
62   // BoringSSL is unavailable for NaCl builds so it remains timing dependent.
63   return lhs.token_ == rhs.token_;
64 #else
65   auto bytes = lhs.token_.AsBytes();
66   auto other_bytes = rhs.token_.AsBytes();
67   return CRYPTO_memcmp(bytes.data(), other_bytes.data(), bytes.size()) == 0;
68 #endif
69 }
70 
operator <<(std::ostream & out,const UnguessableToken & token)71 std::ostream& operator<<(std::ostream& out, const UnguessableToken& token) {
72   return out << "(" << token.ToString() << ")";
73 }
74 
75 }  // namespace base
76