blob: aa7423f88d2781dfda160b4d0f2294ea25c0368e [file] [log] [blame]
Avi Drissmane4622aa2022-09-08 20:36:061// Copyright 2016 The Chromium Authors
tguilbert4a5ac602016-09-19 21:11:252// 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
Hans Wennborg9f3bb63d2020-04-21 11:12:387#include <ostream>
8
Maksim Ivanov6177f0e2022-12-14 00:32:499#include "base/check.h"
tguilbert4a5ac602016-09-19 21:11:2510#include "base/format_macros.h"
11#include "base/rand_util.h"
Liza Burakovae7e943012021-07-16 14:09:0512#include "build/build_config.h"
13
Xiaohan Wang38e4ebb2022-01-19 06:57:4314#if !BUILDFLAG(IS_NACL)
Liza Burakovae7e943012021-07-16 14:09:0515#include "third_party/boringssl/src/include/openssl/mem.h"
16#endif
tguilbert4a5ac602016-09-19 21:11:2517
18namespace base {
19
Ken Rockot8c6991c72018-11-07 21:23:1920UnguessableToken::UnguessableToken(const base::Token& token) : token_(token) {}
tguilbert4a5ac602016-09-19 21:11:2521
22// static
23UnguessableToken UnguessableToken::Create() {
Maksim Ivanov6177f0e2022-12-14 00:32:4924 Token token = Token::CreateRandom();
25 DCHECK(!token.is_zero());
26 return UnguessableToken(token);
tguilbert4a5ac602016-09-19 21:11:2527}
28
29// static
Daniel Cheng1f3b3e22018-08-04 18:54:0130const UnguessableToken& UnguessableToken::Null() {
Avi Drissmanded77172021-07-02 18:23:0031 static const UnguessableToken null_token{};
32 return null_token;
Daniel Cheng1f3b3e22018-08-04 18:54:0133}
34
35// static
Andrew Williams228be95c2023-01-26 15:13:0136absl::optional<UnguessableToken> UnguessableToken::Deserialize(uint64_t high,
37 uint64_t low) {
Andrew Williams6e56276f2023-01-05 16:53:4438 // 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
Liza Burakovae7e943012021-07-16 14:09:0548bool UnguessableToken::operator==(const UnguessableToken& other) const {
Xiaohan Wang38e4ebb2022-01-19 06:57:4349#if BUILDFLAG(IS_NACL)
Liza Burakovae7e943012021-07-16 14:09:0550 // BoringSSL is unavailable for NaCl builds so it remains timing dependent.
51 return token_ == other.token_;
52#else
53 auto bytes = token_.AsBytes();
54 auto other_bytes = other.token_.AsBytes();
55 return CRYPTO_memcmp(bytes.data(), other_bytes.data(), bytes.size()) == 0;
56#endif
57}
58
tguilbert13be8a32016-09-20 02:04:5059std::ostream& operator<<(std::ostream& out, const UnguessableToken& token) {
Pavel Feldman7bbfbc82017-12-29 01:42:5660 return out << "(" << token.ToString() << ")";
tguilbert13be8a32016-09-20 02:04:5061}
62
tguilbert4a5ac602016-09-19 21:11:2563} // namespace base