blob: 335d6a7f65193eec7b4cc36876b8c449cebc289d [file] [log] [blame]
// Copyright 2016 The Fuchsia Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef COBALT_ENCODER_CLIENT_SECRET_H_
#define COBALT_ENCODER_CLIENT_SECRET_H_
#include <string>
#include <utility>
#include <vector>
#include "util/crypto_util/random.h"
#include "util/crypto_util/types.h"
namespace cobalt {
namespace encoder {
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) { 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.
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();
const byte* data() const { return 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() {}
std::vector<byte> bytes_;
};
} // namespace encoder
} // namespace cobalt
#endif // COBALT_ENCODER_CLIENT_SECRET_H_