Files
Library/src/Crypto/Crypto.cpp
T

1104 lines
34 KiB
C++

#include <Void/Crypto/Crypto.hpp>
#include "BuiltinHash.hpp"
#include <array>
#include <cstdint>
#include <cstring>
#include <format>
#include <fstream>
#include <limits>
#include <optional>
#include <utility>
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
#include <openssl/core_names.h>
#include <openssl/crypto.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/kdf.h>
#include <openssl/params.h>
#endif
namespace Void::Crypto
{
namespace
{
thread_local FaultConfig g_fault_config{};
thread_local std::size_t g_fault_hits{0};
[[nodiscard]] std::optional<Void::Result::Error>
maybe_inject_fault(FaultOperation op, std::string_view operation)
{
if (g_fault_config.op == FaultOperation::none) {
return std::nullopt;
}
if (g_fault_config.op != FaultOperation::any &&
g_fault_config.op != op) {
return std::nullopt;
}
if (g_fault_hits < g_fault_config.fail_after) {
++g_fault_hits;
return std::nullopt;
}
++g_fault_hits;
return make_crypto_error(
g_fault_config.code,
std::format("{}: injected crypto backend fault", operation));
}
[[nodiscard]] bool spans_overlap(std::span<const std::byte> a,
std::span<const std::byte> b) noexcept
{
if (a.empty() || b.empty()) {
return false;
}
const auto a_begin = reinterpret_cast<std::uintptr_t>(a.data());
const auto a_end = a_begin + a.size();
const auto b_begin = reinterpret_cast<std::uintptr_t>(b.data());
const auto b_end = b_begin + b.size();
return a_begin < b_end && b_begin < a_end;
}
[[nodiscard]] bool use_builtin_hash(
HashAlgorithm algorithm, const ProviderOptions& provider) noexcept
{
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
if (provider.prefer_builtin ||
algorithm == HashAlgorithm::Blake2b256) {
return true;
}
return false;
#else
(void)algorithm;
(void)provider;
return true;
#endif
}
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
[[nodiscard]] const char*
algorithm_name(HashAlgorithm algorithm) noexcept
{
switch (algorithm) {
case HashAlgorithm::Sha1:
return "SHA1";
case HashAlgorithm::Sha256:
return "SHA256";
case HashAlgorithm::Sha512:
return "SHA512";
case HashAlgorithm::Blake2b256:
return nullptr;
case HashAlgorithm::Blake2b512:
return "BLAKE2B512";
}
return nullptr;
}
[[nodiscard]] const char*
propq_or_null(const ProviderOptions& provider) noexcept
{
return provider.property_query.empty()
? nullptr
: provider.property_query.c_str();
}
[[nodiscard]] Void::Result::Error
make_openssl_error(CryptoErrorCode code, std::string_view operation)
{
const unsigned long err_code = ERR_get_error();
ERR_clear_error();
if (err_code == 0) {
return make_crypto_error(code, std::string{operation});
}
std::array<char, 256> buffer{};
ERR_error_string_n(err_code, buffer.data(), buffer.size());
return make_crypto_error(
code, std::format("{}: {}", operation, buffer.data()));
}
using EvpMdPtr = std::unique_ptr<EVP_MD, decltype(&EVP_MD_free)>;
using EvpMdCtxPtr =
std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>;
using EvpPkeyPtr = std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)>;
using EvpMacPtr = std::unique_ptr<EVP_MAC, decltype(&EVP_MAC_free)>;
using EvpMacCtxPtr =
std::unique_ptr<EVP_MAC_CTX, decltype(&EVP_MAC_CTX_free)>;
using EvpKdfPtr = std::unique_ptr<EVP_KDF, decltype(&EVP_KDF_free)>;
using EvpKdfCtxPtr =
std::unique_ptr<EVP_KDF_CTX, decltype(&EVP_KDF_CTX_free)>;
[[nodiscard]] const unsigned char*
non_null_bytes(std::span<const std::byte> span) noexcept
{
static constexpr unsigned char kEmptyByte = 0;
return span.empty()
? &kEmptyByte
: reinterpret_cast<const unsigned char*>(span.data());
}
#endif
[[nodiscard]] Void::Result::Result<bool>
verify_ed25519_impl(std::span<const std::byte> message,
std::span<const std::byte> signature,
std::span<const std::byte> public_key,
const ProviderOptions& provider)
{
if (signature.size() != Ed25519SignatureSize) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_signature_size,
std::format("Crypto::verifyEd25519: signature must be {} "
"bytes",
Ed25519SignatureSize))};
}
if (public_key.size() != Ed25519PublicKeySize) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_key_size,
std::format("Crypto::verifyEd25519: public key must be {} "
"bytes",
Ed25519PublicKeySize))};
}
if (message.size() > CryptoLimits::kMaxOneShotMessageBytes) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::message_too_large,
std::format("Crypto::verifyEd25519: message exceeds {} "
"byte one-shot limit",
CryptoLimits::kMaxOneShotMessageBytes))};
}
if (auto fault = maybe_inject_fault(FaultOperation::ed25519_verify,
"Crypto::verifyEd25519");
fault.has_value()) {
return std::unexpected{std::move(*fault)};
}
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
if (provider.prefer_builtin) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::verifyEd25519: Ed25519 requires OpenSSL backend")};
}
ERR_clear_error();
const char* propq = propq_or_null(provider);
EvpPkeyPtr key{EVP_PKEY_new_raw_public_key_ex(
nullptr, "ED25519", propq,
non_null_bytes(public_key), public_key.size()),
&EVP_PKEY_free};
if (!key) {
const auto code =
provider.property_query.empty()
? CryptoErrorCode::backend_error
: CryptoErrorCode::provider_error;
return std::unexpected{make_openssl_error(
code, "Crypto::verifyEd25519: invalid public key or "
"unavailable provider")};
}
EvpMdCtxPtr context{EVP_MD_CTX_new(), &EVP_MD_CTX_free};
if (!context) {
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::verifyEd25519: EVP_MD_CTX_new failed")};
}
if (EVP_DigestVerifyInit_ex(context.get(), nullptr, nullptr,
nullptr, propq, key.get(),
nullptr) != 1) {
return std::unexpected{make_openssl_error(
CryptoErrorCode::provider_error,
"Crypto::verifyEd25519: initialization failed")};
}
const int result = EVP_DigestVerify(
context.get(), non_null_bytes(signature), signature.size(),
non_null_bytes(message), message.size());
if (result < 0) {
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::verifyEd25519 failed")};
}
ERR_clear_error();
return result == 1;
#else
(void)provider;
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::verifyEd25519: built without OpenSSL backend")};
#endif
}
} // namespace
bool has_openssl_backend() noexcept
{
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
return true;
#else
return false;
#endif
}
void secure_wipe(std::span<std::byte> buffer) noexcept
{
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
if (!buffer.empty()) {
OPENSSL_cleanse(buffer.data(), buffer.size());
}
#else
Detail::builtin_secure_wipe(buffer);
#endif
}
bool constant_time_equal(std::span<const std::byte> lhs,
std::span<const std::byte> rhs) noexcept
{
if (lhs.size() != rhs.size()) {
return false;
}
if (lhs.empty()) {
return true;
}
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
return CRYPTO_memcmp(lhs.data(), rhs.data(), lhs.size()) == 0;
#else
return Detail::builtin_constant_time_equal(lhs, rhs);
#endif
}
ScopedFaultGuard::ScopedFaultGuard(FaultConfig config) noexcept
: m_previous(g_fault_config), m_previous_hits(g_fault_hits)
{
g_fault_config = config;
g_fault_hits = 0;
}
ScopedFaultGuard::~ScopedFaultGuard() noexcept
{
g_fault_config = m_previous;
g_fault_hits = m_previous_hits;
}
struct Hasher::Impl {
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
EvpMdCtxPtr context{nullptr, &EVP_MD_CTX_free};
EvpMdPtr algorithm{nullptr, &EVP_MD_free};
#endif
Detail::BuiltinHasher builtin{};
bool using_builtin{false};
HasherState state{HasherState::Ready};
};
Hasher::Hasher(std::unique_ptr<Impl> impl) noexcept
: m_impl(std::move(impl))
{
}
Hasher::~Hasher() = default;
Hasher::Hasher(Hasher&&) noexcept = default;
Hasher& Hasher::operator=(Hasher&&) noexcept = default;
HasherState Hasher::state() const noexcept
{
return m_impl ? m_impl->state : HasherState::MovedFrom;
}
Void::Result::Result<Hasher> Hasher::create(HashAlgorithm algorithm)
{
return create(algorithm, ProviderOptions{});
}
Void::Result::Result<Hasher>
Hasher::create(HashAlgorithm algorithm, const ProviderOptions& provider)
{
switch (algorithm) {
case HashAlgorithm::Sha1:
case HashAlgorithm::Sha256:
case HashAlgorithm::Sha512:
case HashAlgorithm::Blake2b256:
case HashAlgorithm::Blake2b512:
break;
default:
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::Hasher: unsupported algorithm")};
}
if (auto fault = maybe_inject_fault(FaultOperation::hash_create,
"Crypto::Hasher::create");
fault.has_value()) {
return std::unexpected{std::move(*fault)};
}
if (use_builtin_hash(algorithm, provider)) {
if (!provider.property_query.empty()) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::provider_error,
"Crypto::Hasher: property_query unavailable on built-in "
"backend")};
}
auto impl = std::make_unique<Impl>();
if (!impl->builtin.init(algorithm)) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::backend_error,
"Crypto::Hasher: built-in initialization failed")};
}
impl->using_builtin = true;
impl->state = HasherState::Ready;
return Hasher{std::move(impl)};
}
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
const char* md_name = algorithm_name(algorithm);
if (md_name == nullptr) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::Hasher: unsupported OpenSSL digest algorithm")};
}
ERR_clear_error();
auto impl = std::make_unique<Impl>();
impl->algorithm = EvpMdPtr{
EVP_MD_fetch(nullptr, md_name, propq_or_null(provider)),
&EVP_MD_free};
if (!impl->algorithm) {
return std::unexpected{make_openssl_error(
CryptoErrorCode::provider_error,
"Crypto::Hasher: EVP_MD_fetch failed")};
}
impl->context = EvpMdCtxPtr{EVP_MD_CTX_new(), &EVP_MD_CTX_free};
if (!impl->context) {
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::Hasher: EVP_MD_CTX_new failed")};
}
if (EVP_DigestInit_ex2(impl->context.get(), impl->algorithm.get(),
nullptr) != 1) {
return std::unexpected{make_openssl_error(
CryptoErrorCode::provider_error,
"Crypto::Hasher: digest initialization failed")};
}
impl->using_builtin = false;
impl->state = HasherState::Ready;
return Hasher{std::move(impl)};
#else
return std::unexpected{make_crypto_error(
CryptoErrorCode::backend_error,
"Crypto::Hasher: OpenSSL backend unavailable")};
#endif
}
Void::Result::Result<void> Hasher::update(std::span<const std::byte> data)
{
if (!m_impl) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_state,
"Crypto::Hasher::update: hasher is moved-from")};
}
if (m_impl->state == HasherState::Finalized ||
m_impl->state == HasherState::Failed) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_state,
"Crypto::Hasher::update: hasher is finalized or failed")};
}
if (auto fault = maybe_inject_fault(FaultOperation::hash_update,
"Crypto::Hasher::update");
fault.has_value()) {
m_impl->state = HasherState::Failed;
return std::unexpected{std::move(*fault)};
}
if (m_impl->using_builtin) {
m_impl->builtin.update(data);
m_impl->state = HasherState::Updating;
return {};
}
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
if (!data.empty() &&
EVP_DigestUpdate(m_impl->context.get(), data.data(),
data.size()) != 1) {
m_impl->state = HasherState::Failed;
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::Hasher::update failed")};
}
m_impl->state = HasherState::Updating;
return {};
#else
m_impl->state = HasherState::Failed;
return std::unexpected{make_crypto_error(
CryptoErrorCode::backend_error,
"Crypto::Hasher::update: invalid backend")};
#endif
}
Void::Result::Result<void> Hasher::update(std::string_view data)
{
return update(std::as_bytes(std::span{data.data(), data.size()}));
}
Void::Result::Result<Digest> Hasher::finalize()
{
if (!m_impl) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_state,
"Crypto::Hasher::finalize: hasher is moved-from")};
}
if (m_impl->state == HasherState::Finalized ||
m_impl->state == HasherState::Failed) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_state,
"Crypto::Hasher::finalize: hasher is finalized or failed")};
}
if (auto fault = maybe_inject_fault(FaultOperation::hash_finalize,
"Crypto::Hasher::finalize");
fault.has_value()) {
m_impl->state = HasherState::Failed;
return std::unexpected{std::move(*fault)};
}
if (m_impl->using_builtin) {
Digest digest = m_impl->builtin.finalize();
m_impl->state = HasherState::Finalized;
return digest;
}
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
const int digest_size = EVP_MD_get_size(m_impl->algorithm.get());
if (digest_size <= 0) {
m_impl->state = HasherState::Failed;
return std::unexpected{make_crypto_error(
CryptoErrorCode::backend_error,
"Crypto::Hasher::finalize: invalid digest size")};
}
Digest digest(static_cast<std::size_t>(digest_size));
unsigned int written = 0;
if (EVP_DigestFinal_ex(m_impl->context.get(),
reinterpret_cast<unsigned char*>(digest.data()),
&written) != 1) {
m_impl->state = HasherState::Failed;
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::Hasher::finalize failed")};
}
m_impl->state = HasherState::Finalized;
digest.resize(written);
return digest;
#else
m_impl->state = HasherState::Failed;
return std::unexpected{make_crypto_error(
CryptoErrorCode::backend_error,
"Crypto::Hasher::finalize: invalid backend")};
#endif
}
auto hash(HashAlgorithm algorithm, std::span<const std::byte> data)
-> Void::Result::Result<Digest>
{
return hash(algorithm, data, ProviderOptions{});
}
auto hash(HashAlgorithm algorithm, std::span<const std::byte> data,
const ProviderOptions& provider) -> Void::Result::Result<Digest>
{
auto hasher = Hasher::create(algorithm, provider);
if (!hasher) {
return std::unexpected{hasher.error()};
}
if (auto updated = hasher->update(data); !updated) {
return std::unexpected{updated.error()};
}
return hasher->finalize();
}
auto hash(HashAlgorithm algorithm, std::string_view data)
-> Void::Result::Result<Digest>
{
return hash(algorithm,
std::as_bytes(std::span{data.data(), data.size()}));
}
auto hashFile(HashAlgorithm algorithm, const std::filesystem::path& path)
-> Void::Result::Result<Digest>
{
return hash_file(algorithm, path, ProviderOptions{});
}
auto hashFile(HashAlgorithm algorithm, const std::filesystem::path& path,
const ProviderOptions& provider)
-> Void::Result::Result<Digest>
{
return hash_file(algorithm, path, provider);
}
auto hash_file(HashAlgorithm algorithm, const std::filesystem::path& path)
-> Void::Result::Result<Digest>
{
return hash_file(algorithm, path, ProviderOptions{});
}
auto hash_file(HashAlgorithm algorithm, const std::filesystem::path& path,
const ProviderOptions& provider)
-> Void::Result::Result<Digest>
{
std::ifstream input{path, std::ios::binary};
if (!input.is_open()) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::io_error,
std::format("Crypto::hash_file: cannot open '{}'",
path.string()))};
}
auto hasher = Hasher::create(algorithm, provider);
if (!hasher) {
return std::unexpected{hasher.error()};
}
std::array<char, CryptoLimits::kStreamChunkBytes> buffer{};
while (input) {
input.read(buffer.data(),
static_cast<std::streamsize>(buffer.size()));
const auto count = input.gcount();
if (count > 0) {
const auto bytes = std::as_bytes(
std::span{buffer.data(), static_cast<std::size_t>(count)});
if (auto updated = hasher->update(bytes); !updated) {
return std::unexpected{updated.error()};
}
}
}
if (input.bad() || (!input.eof() && input.fail())) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::io_error,
std::format("Crypto::hash_file: I/O error reading '{}'",
path.string()))};
}
return hasher->finalize();
}
Void::Result::Result<Digest> sha1(std::span<const std::byte> data)
{
return hash(HashAlgorithm::Sha1, data);
}
Void::Result::Result<Digest> sha1(std::string_view data)
{
return hash(HashAlgorithm::Sha1, data);
}
Void::Result::Result<Digest> sha256(std::span<const std::byte> data)
{
return hash(HashAlgorithm::Sha256, data);
}
Void::Result::Result<Digest> sha256(std::string_view data)
{
return hash(HashAlgorithm::Sha256, data);
}
Void::Result::Result<Digest> sha512(std::span<const std::byte> data)
{
return hash(HashAlgorithm::Sha512, data);
}
Void::Result::Result<Digest> sha512(std::string_view data)
{
return hash(HashAlgorithm::Sha512, data);
}
Void::Result::Result<Digest> blake2b256(std::span<const std::byte> data)
{
return hash(HashAlgorithm::Blake2b256, data);
}
Void::Result::Result<Digest> blake2b256(std::string_view data)
{
return hash(HashAlgorithm::Blake2b256, data);
}
Void::Result::Result<Digest> blake2b512(std::span<const std::byte> data)
{
return hash(HashAlgorithm::Blake2b512, data);
}
Void::Result::Result<Digest> blake2b512(std::string_view data)
{
return hash(HashAlgorithm::Blake2b512, data);
}
Void::Result::Result<Digest> sha1File(const std::filesystem::path& path)
{
return hash_file(HashAlgorithm::Sha1, path);
}
Void::Result::Result<Digest> sha256File(const std::filesystem::path& path)
{
return hash_file(HashAlgorithm::Sha256, path);
}
Void::Result::Result<Digest> sha512File(const std::filesystem::path& path)
{
return hash_file(HashAlgorithm::Sha512, path);
}
Void::Result::Result<Digest> sha1_file(const std::filesystem::path& path)
{
return hash_file(HashAlgorithm::Sha1, path);
}
Void::Result::Result<Digest> sha256_file(const std::filesystem::path& path)
{
return hash_file(HashAlgorithm::Sha256, path);
}
Void::Result::Result<Digest> sha512_file(const std::filesystem::path& path)
{
return hash_file(HashAlgorithm::Sha512, path);
}
Void::Result::Result<Digest>
blake2b256_file(const std::filesystem::path& path)
{
return hash_file(HashAlgorithm::Blake2b256, path);
}
Void::Result::Result<Digest>
blake2b512_file(const std::filesystem::path& path)
{
return hash_file(HashAlgorithm::Blake2b512, path);
}
struct Ed25519PrivateKey::Impl {
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
EvpPkeyPtr pkey{nullptr, &EVP_PKEY_free};
#else
std::uint8_t unused{0};
#endif
};
Ed25519PrivateKey::Ed25519PrivateKey(std::unique_ptr<Impl> impl) noexcept
: m_impl(std::move(impl))
{
}
Ed25519PrivateKey::~Ed25519PrivateKey() = default;
Ed25519PrivateKey::Ed25519PrivateKey(Ed25519PrivateKey&&) noexcept =
default;
Ed25519PrivateKey&
Ed25519PrivateKey::operator=(Ed25519PrivateKey&&) noexcept = default;
bool Ed25519PrivateKey::valid() const noexcept
{
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
return m_impl != nullptr && m_impl->pkey != nullptr;
#else
return false;
#endif
}
Void::Result::Result<Ed25519PrivateKey>
Ed25519PrivateKey::generate(const ProviderOptions& provider)
{
if (auto fault = maybe_inject_fault(FaultOperation::ed25519_keygen,
"Crypto::Ed25519PrivateKey::generate");
fault.has_value()) {
return std::unexpected{std::move(*fault)};
}
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
if (provider.prefer_builtin) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::Ed25519PrivateKey::generate requires OpenSSL backend")};
}
ERR_clear_error();
EvpPkeyPtr key{
EVP_PKEY_Q_keygen(nullptr, propq_or_null(provider), "ED25519"),
&EVP_PKEY_free};
if (!key) {
return std::unexpected{make_openssl_error(
CryptoErrorCode::provider_error,
"Crypto::Ed25519PrivateKey::generate failed")};
}
auto impl = std::make_unique<Impl>();
impl->pkey = std::move(key);
return Ed25519PrivateKey{std::move(impl)};
#else
(void)provider;
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::Ed25519PrivateKey::generate: built without OpenSSL "
"backend")};
#endif
}
Void::Result::Result<Ed25519PrivateKey>
Ed25519PrivateKey::from_raw_seed(std::span<const std::byte> seed,
const ProviderOptions& provider)
{
if (seed.size() != Ed25519SeedSize) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_key_size,
std::format("Crypto::Ed25519PrivateKey::from_raw_seed: seed "
"must be {} bytes",
Ed25519SeedSize))};
}
if (auto fault = maybe_inject_fault(
FaultOperation::ed25519_import,
"Crypto::Ed25519PrivateKey::from_raw_seed");
fault.has_value()) {
return std::unexpected{std::move(*fault)};
}
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
if (provider.prefer_builtin) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::Ed25519PrivateKey::from_raw_seed requires OpenSSL "
"backend")};
}
ERR_clear_error();
EvpPkeyPtr key{EVP_PKEY_new_raw_private_key_ex(
nullptr, "ED25519", propq_or_null(provider),
non_null_bytes(seed), seed.size()),
&EVP_PKEY_free};
if (!key) {
return std::unexpected{make_openssl_error(
CryptoErrorCode::provider_error,
"Crypto::Ed25519PrivateKey::from_raw_seed failed")};
}
auto impl = std::make_unique<Impl>();
impl->pkey = std::move(key);
return Ed25519PrivateKey{std::move(impl)};
#else
(void)provider;
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::Ed25519PrivateKey::from_raw_seed: built without OpenSSL "
"backend")};
#endif
}
Void::Result::Result<Ed25519PublicKey> Ed25519PrivateKey::public_key() const
{
if (!valid()) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_state,
"Crypto::Ed25519PrivateKey::public_key: invalid or moved-from "
"key")};
}
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
Ed25519PublicKey pub;
std::size_t len = pub.bytes.size();
if (EVP_PKEY_get_raw_public_key(
m_impl->pkey.get(),
reinterpret_cast<unsigned char*>(pub.bytes.data()),
&len) != 1 ||
len != Ed25519PublicKeySize) {
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::Ed25519PrivateKey::public_key failed")};
}
return pub;
#else
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::Ed25519PrivateKey::public_key: built without OpenSSL "
"backend")};
#endif
}
Void::Result::Result<Ed25519Seed> Ed25519PrivateKey::export_raw_seed() const
{
if (!valid()) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_state,
"Crypto::Ed25519PrivateKey::export_raw_seed: invalid or "
"moved-from key")};
}
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
std::array<std::byte, Ed25519SeedSize> raw{};
std::size_t len = raw.size();
if (EVP_PKEY_get_raw_private_key(
m_impl->pkey.get(),
reinterpret_cast<unsigned char*>(raw.data()), &len) != 1 ||
len != Ed25519SeedSize) {
secure_wipe(raw);
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::Ed25519PrivateKey::export_raw_seed failed")};
}
auto result = Ed25519Seed::from_bytes(raw);
secure_wipe(raw);
return result;
#else
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::Ed25519PrivateKey::export_raw_seed: built without OpenSSL "
"backend")};
#endif
}
Void::Result::Result<Ed25519Signature>
sign_ed25519(std::span<const std::byte> message,
const Ed25519PrivateKey& private_key,
const ProviderOptions& provider)
{
if (!private_key.valid()) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_state,
"Crypto::sign_ed25519: private key is invalid or moved-from")};
}
if (message.size() > CryptoLimits::kMaxOneShotMessageBytes) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::message_too_large,
std::format("Crypto::sign_ed25519: message exceeds {} byte "
"one-shot limit",
CryptoLimits::kMaxOneShotMessageBytes))};
}
if (auto fault = maybe_inject_fault(FaultOperation::ed25519_sign,
"Crypto::sign_ed25519");
fault.has_value()) {
return std::unexpected{std::move(*fault)};
}
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
if (provider.prefer_builtin) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::sign_ed25519 requires OpenSSL backend")};
}
ERR_clear_error();
EvpMdCtxPtr context{EVP_MD_CTX_new(), &EVP_MD_CTX_free};
if (!context) {
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::sign_ed25519: EVP_MD_CTX_new failed")};
}
if (EVP_DigestSignInit_ex(context.get(), nullptr, nullptr, nullptr,
propq_or_null(provider),
private_key.m_impl->pkey.get(),
nullptr) != 1) {
return std::unexpected{make_openssl_error(
CryptoErrorCode::provider_error,
"Crypto::sign_ed25519: initialization failed")};
}
Ed25519Signature signature;
std::size_t sig_len = signature.bytes.size();
if (EVP_DigestSign(
context.get(),
reinterpret_cast<unsigned char*>(signature.bytes.data()),
&sig_len, non_null_bytes(message), message.size()) != 1 ||
sig_len != Ed25519SignatureSize) {
secure_wipe(signature.bytes);
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::sign_ed25519 failed")};
}
return signature;
#else
(void)provider;
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::sign_ed25519: built without OpenSSL backend")};
#endif
}
Void::Result::Result<bool> verifyEd25519(std::span<const std::byte> message,
std::span<const std::byte>
signature,
std::span<const std::byte>
publicKey)
{
return verify_ed25519_impl(message, signature, publicKey,
ProviderOptions{});
}
Void::Result::Result<bool>
verify_ed25519(std::span<const std::byte> message,
const Ed25519Signature& signature,
const Ed25519PublicKey& public_key,
const ProviderOptions& provider)
{
return verify_ed25519_impl(message, signature.view(), public_key.view(),
provider);
}
Void::Result::Result<void>
hmac_sha256_into(std::span<const std::byte> secret_key,
std::span<const std::byte> message,
std::span<std::byte> output,
const ProviderOptions& provider)
{
if (output.size() != HmacSha256Size) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_argument,
std::format("Crypto::hmac_sha256_into: output must be {} bytes",
HmacSha256Size))};
}
if (spans_overlap(secret_key, output) ||
spans_overlap(message, output)) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::overlapping_buffers,
"Crypto::hmac_sha256_into: output buffer overlaps input")};
}
if (auto fault = maybe_inject_fault(FaultOperation::hmac,
"Crypto::hmac_sha256_into");
fault.has_value()) {
secure_wipe(output);
return std::unexpected{std::move(*fault)};
}
if (use_builtin_hash(HashAlgorithm::Sha256, provider)) {
if (!provider.property_query.empty()) {
secure_wipe(output);
return std::unexpected{make_crypto_error(
CryptoErrorCode::provider_error,
"Crypto::hmac_sha256_into: property_query unavailable on "
"built-in backend")};
}
Detail::builtin_hmac_sha256(secret_key, message, output);
return {};
}
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
ERR_clear_error();
EvpMacPtr mac{EVP_MAC_fetch(nullptr, "HMAC", propq_or_null(provider)),
&EVP_MAC_free};
if (!mac) {
secure_wipe(output);
return std::unexpected{make_openssl_error(
CryptoErrorCode::provider_error,
"Crypto::hmac_sha256_into: EVP_MAC_fetch failed")};
}
EvpMacCtxPtr ctx{EVP_MAC_CTX_new(mac.get()), &EVP_MAC_CTX_free};
if (!ctx) {
secure_wipe(output);
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::hmac_sha256_into: EVP_MAC_CTX_new failed")};
}
char digest_name[] = "SHA256";
std::array<OSSL_PARAM, 2> params = {
OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST, digest_name,
0),
OSSL_PARAM_construct_end(),
};
if (EVP_MAC_init(ctx.get(), non_null_bytes(secret_key),
secret_key.size(), params.data()) != 1) {
secure_wipe(output);
return std::unexpected{make_openssl_error(
CryptoErrorCode::provider_error,
"Crypto::hmac_sha256_into: EVP_MAC_init failed")};
}
if (!message.empty() &&
EVP_MAC_update(ctx.get(), non_null_bytes(message),
message.size()) != 1) {
secure_wipe(output);
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::hmac_sha256_into: EVP_MAC_update failed")};
}
std::size_t out_len = 0;
if (EVP_MAC_final(ctx.get(),
reinterpret_cast<unsigned char*>(output.data()),
&out_len, output.size()) != 1 ||
out_len != HmacSha256Size) {
secure_wipe(output);
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::hmac_sha256_into: EVP_MAC_final failed")};
}
return {};
#else
secure_wipe(output);
return std::unexpected{make_crypto_error(
CryptoErrorCode::backend_error,
"Crypto::hmac_sha256_into: OpenSSL backend unavailable")};
#endif
}
Void::Result::Result<Digest> hmac_sha256(std::span<const std::byte> secret_key,
std::span<const std::byte> message,
const ProviderOptions& provider)
{
Digest out(HmacSha256Size);
if (auto res = hmac_sha256_into(secret_key, message, out, provider);
!res.has_value()) {
secure_wipe(out);
return std::unexpected{std::move(res.error())};
}
return out;
}
Void::Result::Result<void>
hkdf_sha256(std::span<const std::byte> secret_input,
std::span<const std::byte> salt,
std::span<const std::byte> context,
std::span<std::byte> secret_output,
const ProviderOptions& provider)
{
if (secret_output.empty()) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_argument,
"Crypto::hkdf_sha256: output buffer must be non-empty")};
}
if (secret_output.size() > CryptoLimits::kMaxHkdfOutputBytes) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::output_too_large,
std::format("Crypto::hkdf_sha256: output size exceeds {} byte "
"cap",
CryptoLimits::kMaxHkdfOutputBytes))};
}
if (spans_overlap(secret_input, secret_output) ||
spans_overlap(salt, secret_output) ||
spans_overlap(context, secret_output)) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::overlapping_buffers,
"Crypto::hkdf_sha256: output buffer overlaps input")};
}
if (auto fault = maybe_inject_fault(FaultOperation::hkdf,
"Crypto::hkdf_sha256");
fault.has_value()) {
secure_wipe(secret_output);
return std::unexpected{std::move(*fault)};
}
if (use_builtin_hash(HashAlgorithm::Sha256, provider)) {
if (!provider.property_query.empty()) {
secure_wipe(secret_output);
return std::unexpected{make_crypto_error(
CryptoErrorCode::provider_error,
"Crypto::hkdf_sha256: property_query unavailable on "
"built-in backend")};
}
Detail::builtin_hkdf_sha256(secret_input, salt, context,
secret_output);
return {};
}
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
ERR_clear_error();
EvpKdfPtr kdf{EVP_KDF_fetch(nullptr, "HKDF", propq_or_null(provider)),
&EVP_KDF_free};
if (!kdf) {
secure_wipe(secret_output);
return std::unexpected{make_openssl_error(
CryptoErrorCode::provider_error,
"Crypto::hkdf_sha256: EVP_KDF_fetch failed")};
}
EvpKdfCtxPtr ctx{EVP_KDF_CTX_new(kdf.get()), &EVP_KDF_CTX_free};
if (!ctx) {
secure_wipe(secret_output);
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::hkdf_sha256: EVP_KDF_CTX_new failed")};
}
char digest_name[] = "SHA256";
std::array<OSSL_PARAM, 5> params = {
OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST, digest_name,
0),
OSSL_PARAM_construct_octet_string(
OSSL_KDF_PARAM_KEY,
const_cast<unsigned char*>(non_null_bytes(secret_input)),
secret_input.size()),
OSSL_PARAM_construct_octet_string(
OSSL_KDF_PARAM_SALT,
const_cast<unsigned char*>(non_null_bytes(salt)), salt.size()),
OSSL_PARAM_construct_octet_string(
OSSL_KDF_PARAM_INFO,
const_cast<unsigned char*>(non_null_bytes(context)),
context.size()),
OSSL_PARAM_construct_end(),
};
if (EVP_KDF_derive(
ctx.get(),
reinterpret_cast<unsigned char*>(secret_output.data()),
secret_output.size(), params.data()) != 1) {
secure_wipe(secret_output);
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::hkdf_sha256: EVP_KDF_derive failed")};
}
return {};
#else
secure_wipe(secret_output);
return std::unexpected{make_crypto_error(
CryptoErrorCode::backend_error,
"Crypto::hkdf_sha256: OpenSSL backend unavailable")};
#endif
}
} // namespace Void::Crypto