1 // Copyright 2018 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/token.h"
6
7 #include <inttypes.h>
8
9 #include <array>
10 #include <optional>
11 #include <string_view>
12
13 #include "base/check.h"
14 #include "base/hash/hash.h"
15 #include "base/pickle.h"
16 #include "base/rand_util.h"
17 #include "base/strings/stringprintf.h"
18
19 namespace base {
20
21 // static
CreateRandom()22 Token Token::CreateRandom() {
23 Token token;
24
25 // Use base::RandBytes instead of crypto::RandBytes, because crypto calls the
26 // base version directly, and to prevent the dependency from base/ to crypto/.
27 RandBytes(byte_span_from_ref(token));
28
29 CHECK(!token.is_zero());
30
31 return token;
32 }
33
ToString() const34 std::string Token::ToString() const {
35 return StringPrintf("%016" PRIX64 "%016" PRIX64, words_[0], words_[1]);
36 }
37
38 // static
FromString(std::string_view string_representation)39 std::optional<Token> Token::FromString(std::string_view string_representation) {
40 if (string_representation.size() != 32) {
41 return std::nullopt;
42 }
43 std::array<uint64_t, 2> words;
44 for (size_t i = 0; i < 2; i++) {
45 uint64_t word = 0;
46 // This j loop is similar to HexStringToUInt64 but we are intentionally
47 // strict about case, accepting 'A' but rejecting 'a'.
48 for (size_t j = 0; j < 16; j++) {
49 const char c = string_representation[(16 * i) + j];
50 if (('0' <= c) && (c <= '9')) {
51 word = (word << 4) | static_cast<uint64_t>(c - '0');
52 } else if (('A' <= c) && (c <= 'F')) {
53 word = (word << 4) | static_cast<uint64_t>(c - 'A' + 10);
54 } else {
55 return std::nullopt;
56 }
57 }
58 words[i] = word;
59 }
60 return std::optional<Token>(std::in_place, words[0], words[1]);
61 }
62
WriteTokenToPickle(Pickle * pickle,const Token & token)63 void WriteTokenToPickle(Pickle* pickle, const Token& token) {
64 pickle->WriteUInt64(token.high());
65 pickle->WriteUInt64(token.low());
66 }
67
ReadTokenFromPickle(PickleIterator * pickle_iterator)68 std::optional<Token> ReadTokenFromPickle(PickleIterator* pickle_iterator) {
69 uint64_t high;
70 if (!pickle_iterator->ReadUInt64(&high))
71 return std::nullopt;
72
73 uint64_t low;
74 if (!pickle_iterator->ReadUInt64(&low))
75 return std::nullopt;
76
77 return Token(high, low);
78 }
79
operator ()(const Token & token) const80 size_t TokenHash::operator()(const Token& token) const {
81 return HashInts64(token.high(), token.low());
82 }
83
84 } // namespace base
85