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