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