// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "device/fido/fido_parsing_utils.h" #include "base/check_op.h" #include "base/numerics/safe_conversions.h" #include "base/strings/stringprintf.h" namespace device { namespace fido_parsing_utils { namespace { constexpr bool AreSpansDisjoint(base::span lhs, base::span rhs) { return lhs.data() + lhs.size() <= rhs.data() || // [lhs)...[rhs) rhs.data() + rhs.size() <= lhs.data(); // [rhs)...[lhs) } } // namespace const char kEs256[] = "ES256"; std::vector Materialize(base::span span) { return std::vector(span.begin(), span.end()); } base::Optional> MaterializeOrNull( base::Optional> span) { if (span) return Materialize(*span); return base::nullopt; } void Append(std::vector* target, base::span in_values) { CHECK(AreSpansDisjoint(*target, in_values)); target->insert(target->end(), in_values.begin(), in_values.end()); } std::vector Extract(base::span span, size_t pos, size_t length) { return Materialize(ExtractSpan(span, pos, length)); } base::span ExtractSpan(base::span span, size_t pos, size_t length) { if (!(pos <= span.size() && length <= span.size() - pos)) return base::span(); return span.subspan(pos, length); } std::vector ExtractSuffix(base::span span, size_t pos) { return Materialize(ExtractSuffixSpan(span, pos)); } base::span ExtractSuffixSpan(base::span span, size_t pos) { if (pos > span.size()) return std::vector(); return span.subspan(pos); } std::vector> SplitSpan(base::span span, size_t max_chunk_size) { DCHECK_NE(0u, max_chunk_size); std::vector> chunks; const size_t num_chunks = (span.size() + max_chunk_size - 1) / max_chunk_size; chunks.reserve(num_chunks); while (!span.empty()) { const size_t chunk_size = std::min(span.size(), max_chunk_size); chunks.emplace_back(span.subspan(0, chunk_size)); span = span.subspan(chunk_size); } return chunks; } std::array CreateSHA256Hash( base::StringPiece data) { std::array hashed_data; crypto::SHA256HashString(data, hashed_data.data(), hashed_data.size()); return hashed_data; } base::StringPiece ConvertToStringPiece(base::span data) { return {reinterpret_cast(data.data()), data.size()}; } std::string ConvertBytesToUuid(base::span bytes) { uint64_t most_significant_bytes = 0; for (size_t i = 0; i < sizeof(uint64_t); i++) { most_significant_bytes |= base::strict_cast(bytes[i]) << 8 * (7 - i); } uint64_t least_significant_bytes = 0; for (size_t i = 0; i < sizeof(uint64_t); i++) { least_significant_bytes |= base::strict_cast(bytes[i + 8]) << 8 * (7 - i); } return base::StringPrintf( "%08x-%04x-%04x-%04x-%012llx", static_cast(most_significant_bytes >> 32), static_cast((most_significant_bytes >> 16) & 0x0000ffff), static_cast(most_significant_bytes & 0x0000ffff), static_cast(least_significant_bytes >> 48), least_significant_bytes & 0x0000ffff'ffffffffULL); } } // namespace fido_parsing_utils } // namespace device