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.
5 #include "base/token.h"
9 #include "base/check.h"
10 #include "base/hash/hash.h"
11 #include "base/pickle.h"
12 #include "base/rand_util.h"
13 #include "base/strings/string_piece.h"
14 #include "base/strings/stringprintf.h"
15 #include "third_party/abseil-cpp/absl/types/optional.h"
20 Token Token::CreateRandom() {
23 // Use base::RandBytes instead of crypto::RandBytes, because crypto calls the
24 // base version directly, and to prevent the dependency from base/ to crypto/.
25 base::RandBytes(&token, sizeof(token));
27 CHECK(!token.is_zero());
32 std::string Token::ToString() const {
33 return base::StringPrintf("%016" PRIX64 "%016" PRIX64, words_[0], words_[1]);
37 absl::optional<Token> Token::FromString(StringPiece string_representation) {
38 if (string_representation.size() != 32) {
42 for (size_t i = 0; i < 2; i++) {
44 // This j loop is similar to HexStringToUInt64 but we are intentionally
45 // strict about case, accepting 'A' but rejecting 'a'.
46 for (size_t j = 0; j < 16; j++) {
47 const char c = string_representation[(16 * i) + j];
48 if (('0' <= c) && (c <= '9')) {
49 word = (word << 4) | static_cast<uint64_t>(c - '0');
50 } else if (('A' <= c) && (c <= 'F')) {
51 word = (word << 4) | static_cast<uint64_t>(c - 'A' + 10);
58 return absl::optional<Token>(absl::in_place, words[0], words[1]);
61 void WriteTokenToPickle(Pickle* pickle, const Token& token) {
62 pickle->WriteUInt64(token.high());
63 pickle->WriteUInt64(token.low());
66 absl::optional<Token> ReadTokenFromPickle(PickleIterator* pickle_iterator) {
68 if (!pickle_iterator->ReadUInt64(&high))
72 if (!pickle_iterator->ReadUInt64(&low))
75 return Token(high, low);
78 size_t TokenHash::operator()(const Token& token) const {
79 return HashInts64(token.high(), token.low());