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.
5 #include "base/unguessable_token.h"
9 #include "base/check.h"
10 #include "base/format_macros.h"
11 #include "base/rand_util.h"
12 #include "build/build_config.h"
14 #if !BUILDFLAG(IS_NACL)
15 #include "third_party/boringssl/src/include/openssl/mem.h"
20 UnguessableToken::UnguessableToken(const base::Token& token) : token_(token) {}
23 UnguessableToken UnguessableToken::Create() {
24 Token token = Token::CreateRandom();
25 DCHECK(!token.is_zero());
26 return UnguessableToken(token);
30 const UnguessableToken& UnguessableToken::Null() {
31 static const UnguessableToken null_token{};
36 absl::optional<UnguessableToken> UnguessableToken::Deserialize(uint64_t high,
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) {
45 return UnguessableToken(Token{high, low});
48 bool UnguessableToken::operator==(const UnguessableToken& other) const {
49 #if BUILDFLAG(IS_NACL)
50 // BoringSSL is unavailable for NaCl builds so it remains timing dependent.
51 return token_ == other.token_;
53 auto bytes = token_.AsBytes();
54 auto other_bytes = other.token_.AsBytes();
55 return CRYPTO_memcmp(bytes.data(), other_bytes.data(), bytes.size()) == 0;
59 std::ostream& operator<<(std::ostream& out, const UnguessableToken& token) {
60 return out << "(" << token.ToString() << ")";