unguessable_token.cc 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Copyright 2016 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "base/unguessable_token.h"
  5. #include <ostream>
  6. #include "base/format_macros.h"
  7. #include "base/rand_util.h"
  8. #include "build/build_config.h"
  9. #if !BUILDFLAG(IS_NACL)
  10. #include "third_party/boringssl/src/include/openssl/mem.h"
  11. #endif
  12. namespace base {
  13. UnguessableToken::UnguessableToken(const base::Token& token) : token_(token) {}
  14. // static
  15. UnguessableToken UnguessableToken::Create() {
  16. return UnguessableToken(Token::CreateRandom());
  17. }
  18. // static
  19. const UnguessableToken& UnguessableToken::Null() {
  20. static const UnguessableToken null_token{};
  21. return null_token;
  22. }
  23. // static
  24. UnguessableToken UnguessableToken::Deserialize(uint64_t high, uint64_t low) {
  25. // Receiving a zeroed out UnguessableToken from another process means that it
  26. // was never initialized via Create(). The real check for this is in the
  27. // StructTraits in mojo/public/cpp/base/unguessable_token_mojom_traits.cc
  28. // where a zero-ed out token will fail to deserialize. This DCHECK is a
  29. // backup check.
  30. DCHECK(!(high == 0 && low == 0));
  31. return UnguessableToken(Token{high, low});
  32. }
  33. bool UnguessableToken::operator==(const UnguessableToken& other) const {
  34. #if BUILDFLAG(IS_NACL)
  35. // BoringSSL is unavailable for NaCl builds so it remains timing dependent.
  36. return token_ == other.token_;
  37. #else
  38. auto bytes = token_.AsBytes();
  39. auto other_bytes = other.token_.AsBytes();
  40. return CRYPTO_memcmp(bytes.data(), other_bytes.data(), bytes.size()) == 0;
  41. #endif
  42. }
  43. std::ostream& operator<<(std::ostream& out, const UnguessableToken& token) {
  44. return out << "(" << token.ToString() << ")";
  45. }
  46. } // namespace base