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 absl::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 absl::nullopt;
44 }
45 return UnguessableToken(Token{high, low});
46 }
47
operator ==(const UnguessableToken & lhs,const UnguessableToken & rhs)48 bool operator==(const UnguessableToken& lhs, const UnguessableToken& rhs) {
49 #if BUILDFLAG(IS_NACL)
50 // BoringSSL is unavailable for NaCl builds so it remains timing dependent.
51 return lhs.token_ == rhs.token_;
52 #else
53 auto bytes = lhs.token_.AsBytes();
54 auto other_bytes = rhs.token_.AsBytes();
55 return CRYPTO_memcmp(bytes.data(), other_bytes.data(), bytes.size()) == 0;
56 #endif
57 }
58
operator <<(std::ostream & out,const UnguessableToken & token)59 std::ostream& operator<<(std::ostream& out, const UnguessableToken& token) {
60 return out << "(" << token.ToString() << ")";
61 }
62
63 } // namespace base
64