| // Copyright 2016 The Fuchsia Authors. All rights reserved. |
| // Use of this source code is governed by a BSD-style license that can be |
| // found in the LICENSE file. |
| |
| #ifndef COBALT_SRC_SYSTEM_DATA_CLIENT_SECRET_H_ |
| #define COBALT_SRC_SYSTEM_DATA_CLIENT_SECRET_H_ |
| |
| #include <string> |
| #include <utility> |
| #include <vector> |
| |
| #include "src/lib/crypto_util/random.h" |
| #include "src/lib/crypto_util/types.h" |
| |
| namespace cobalt::system_data { |
| |
| using crypto::byte; |
| |
| // A ClientSecret is a wrapper around an array of bytes containing |
| // random bytes from a CSPRNG. Clients should invoke GenerateNewSecret() |
| // once, and then permanently and securely save the token returned by |
| // GetToken(). After that clients should reconstruct the token using |
| // FromToken(). |
| // |
| // Tokens are passed into several different methods in the Encoder API. |
| class ClientSecret { |
| public: |
| // Move constructor |
| ClientSecret(ClientSecret&& other) noexcept { bytes_ = std::move(other.bytes_); } |
| |
| // Copy constructor |
| ClientSecret(const ClientSecret& other) { bytes_ = other.bytes_; } |
| |
| bool operator==(const ClientSecret& other) const { |
| if (!valid() || !other.valid()) { |
| return false; |
| } |
| return bytes_ == other.bytes_; |
| } |
| |
| bool operator!=(const ClientSecret& other) const { return !operator==(other); } |
| |
| // Returns a ClientSecret with freshly generated bytes. |
| static ClientSecret GenerateNewSecret(); |
| |
| // Returns a ClientSecret with bytes decoded from |token|. If token is not |
| // valid then the returned ClientSecret will have valid() == false. |
| static ClientSecret FromToken(const std::string& token); |
| |
| // Is this ClientSecret valid? An invalid ClientSecret may occur when an |
| // invalid token is passed to FromToken(), or after a move occurs. |
| [[nodiscard]] bool valid() const { return !bytes_.empty(); } |
| |
| // Returns a token that may be used to reconstitute this ClientSecret |
| // using the FromToken() function. Returns the empty string if this |
| // ClientSecret is not valid. |
| // |
| // This method is not thread safe. |
| std::string GetToken(); |
| |
| [[nodiscard]] const byte* data() const { return reinterpret_cast<const byte*>(bytes_.data()); } |
| |
| static const size_t kNumSecretBytes = 16; |
| |
| // For internal testing use only. Does not take ownership of |rand|. |
| // Uses |rand| to generate the new secret. |
| static ClientSecret GenerateNewSecret(crypto::Random* rand); |
| |
| private: |
| // Private default constructor |
| ClientSecret() = default; |
| std::string bytes_; |
| }; |
| |
| } // namespace cobalt::system_data |
| |
| namespace cobalt::encoder { |
| |
| using system_data::ClientSecret; |
| |
| } // namespace cobalt::encoder |
| |
| #endif // COBALT_SRC_SYSTEM_DATA_CLIENT_SECRET_H_ |