blob: 0eb690548ceea7aa529bb460f04e6e61e1ef7daf [file] [log] [blame]
// Copyright 2019 The Chromium OS 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 U2FD_UTIL_H_
#define U2FD_UTIL_H_
#include <algorithm>
#include <string>
#include <vector>
#include <base/optional.h>
#include <base/logging.h>
#include <crypto/scoped_openssl_types.h>
namespace u2f {
namespace util {
// Utility functions for copying data to/from vector<uint8_t>.
// Utility function to copy an object, as raw bytes, to a vector.
template <typename FromType>
void AppendToVector(const FromType& from, std::vector<uint8_t>* to) {
const uint8_t* from_bytes = reinterpret_cast<const uint8_t*>(&from);
std::copy(from_bytes, from_bytes + sizeof(from), std::back_inserter(*to));
// Specializations of above function for copying from vector and string.
template <>
void AppendToVector(const std::vector<uint8_t>& from, std::vector<uint8_t>* to);
template <>
void AppendToVector(const std::string& from, std::vector<uint8_t>* to);
// Utility function to copy bytes from a vector to an object. This is the
// inverse of AppendToVector.
template <typename ToType>
void VectorToObject(const std::vector<uint8_t>& from, ToType* to) {
// TODO(louiscollard): This, but nicer/safer.
memcpy(to, &from.front(), from.size());
// Utility function to copy part of a string to a vector.
void AppendSubstringToVector(const std::string& from,
int start,
int length,
std::vector<uint8_t>* to);
// Crypto utilities.
// Attempts to convert the specified ECDSA signature (specified as r and s
// values) to DER encoding; returns base::nullopt on error.
base::Optional<std::vector<uint8_t>> SignatureToDerBytes(const uint8_t* r,
const uint8_t* s);
// Returns the SHA-256 of the specified data.
std::vector<uint8_t> Sha256(const std::vector<uint8_t>& data);
} // namespace util
} // namespace u2f
#endif // U2FD_UTIL_H_