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/pickle.h"
10 #include "base/rand_util.h"
11 #include "base/strings/stringprintf.h"
12 #include "third_party/abseil-cpp/absl/types/optional.h"
17 Token Token::CreateRandom() {
20 // Use base::RandBytes instead of crypto::RandBytes, because crypto calls the
21 // base version directly, and to prevent the dependency from base/ to crypto/.
22 base::RandBytes(&token, sizeof(token));
26 std::string Token::ToString() const {
27 return base::StringPrintf("%016" PRIX64 "%016" PRIX64, words_[0], words_[1]);
31 absl::optional<Token> Token::FromString(StringPiece string_representation) {
32 if (string_representation.size() != 32) {
36 for (size_t i = 0; i < 2; i++) {
38 // This j loop is similar to HexStringToUInt64 but we are intentionally
39 // strict about case, accepting 'A' but rejecting 'a'.
40 for (size_t j = 0; j < 16; j++) {
41 const char c = string_representation[(16 * i) + j];
42 if (('0' <= c) && (c <= '9')) {
43 word = (word << 4) | static_cast<uint64_t>(c - '0');
44 } else if (('A' <= c) && (c <= 'F')) {
45 word = (word << 4) | static_cast<uint64_t>(c - 'A' + 10);
52 return absl::optional<Token>(absl::in_place, words[0], words[1]);
55 void WriteTokenToPickle(Pickle* pickle, const Token& token) {
56 pickle->WriteUInt64(token.high());
57 pickle->WriteUInt64(token.low());
60 absl::optional<Token> ReadTokenFromPickle(PickleIterator* pickle_iterator) {
62 if (!pickle_iterator->ReadUInt64(&high))
66 if (!pickle_iterator->ReadUInt64(&low))
69 return Token(high, low);