Crypto: add HMAC-SHA1 and PBKDF2-HMAC-SHA256 (#41)

This commit is contained in:
faumaray committed 2026-12-03 15:50:15 +03:00
1 parent b3c566ed4d
commit 74bd01aac5
6 files changed
+826 -46

No files matched your search

+33
View File
@@ -5,6 +5,7 @@
#include <Void/Functional/Result.hpp>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <memory>
#include <span>
@@ -166,6 +167,19 @@ namespace Void::Crypto
const Ed25519PublicKey& public_key,
const ProviderOptions& provider = {});
/// Compute HMAC-SHA-1 (RFC 2104) into a caller-owned 20-byte buffer.
/// Wipes output on backend failure and rejects overlapping buffers.
[[nodiscard]] Void::Result::Result<void>
hmac_sha1_into(std::span<const std::byte> secret_key,
std::span<const std::byte> message,
std::span<std::byte> output,
const ProviderOptions& provider = {});
[[nodiscard]] Void::Result::Result<Digest>
hmac_sha1(std::span<const std::byte> secret_key,
std::span<const std::byte> message,
const ProviderOptions& provider = {});
/// Compute HMAC-SHA-256 into a caller-owned 32-byte buffer.
/// Wipes output on backend failure and rejects overlapping buffers.
[[nodiscard]] Void::Result::Result<void>
@@ -179,6 +193,25 @@ namespace Void::Crypto
std::span<const std::byte> message,
const ProviderOptions& provider = {});
/// Derive key material with RFC 8018 PBKDF2-HMAC-SHA-256 into a
/// caller-owned buffer. iterations must be 1..kMaxPbkdf2Iterations, salt
/// at most kMaxPbkdf2SaltBytes and output 1..kMaxPbkdf2OutputBytes.
/// Rejects overlapping buffers and wipes output on any failure after
/// validation.
[[nodiscard]] Void::Result::Result<void>
pbkdf2_hmac_sha256_into(std::span<const std::byte> password,
std::span<const std::byte> salt,
std::uint32_t iterations,
std::span<std::byte> output,
const ProviderOptions& provider = {});
[[nodiscard]] Void::Result::Result<Digest>
pbkdf2_hmac_sha256(std::span<const std::byte> password,
std::span<const std::byte> salt,
std::uint32_t iterations,
std::size_t output_length,
const ProviderOptions& provider = {});
/// Derive key material with RFC 5869 HKDF-SHA-256 into a caller-owned
/// buffer (1..CryptoLimits::kMaxHkdfOutputBytes). Rejects overlapping
/// buffers and wipes secret_output on any failure after validation.
+6 -1
View File
@@ -16,12 +16,16 @@ namespace Void::Crypto
inline constexpr std::size_t Ed25519PublicKeySize = 32;
inline constexpr std::size_t Ed25519SignatureSize = 64;
inline constexpr std::size_t Ed25519SeedSize = 32;
inline constexpr std::size_t HmacSha1Size = 20;
inline constexpr std::size_t HmacSha256Size = 32;
struct CryptoLimits {
static constexpr std::size_t kMaxOneShotMessageBytes =
16ULL * 1024ULL * 1024ULL;
static constexpr std::size_t kMaxHkdfOutputBytes = 4ULL * 1024ULL;
static constexpr std::uint32_t kMaxPbkdf2Iterations = 10'000'000U;
static constexpr std::size_t kMaxPbkdf2SaltBytes = 64ULL * 1024ULL;
static constexpr std::size_t kMaxPbkdf2OutputBytes = 1024ULL;
static constexpr std::size_t kStreamChunkBytes = 64ULL * 1024ULL;
static constexpr std::size_t kDefaultMaxConcurrentFileHashes = 8;
static constexpr std::size_t kDefaultMaxWaitingFileHashes = 32;
@@ -256,7 +260,8 @@ namespace Void::Crypto
ed25519_sign,
ed25519_verify,
hmac,
hkdf
hkdf,
pbkdf2
};
struct FaultConfig {
+131
View File
@@ -789,6 +789,46 @@ namespace Void::Crypto::Detail
return out;
}
void builtin_hmac_sha1(std::span<const std::byte> secret_key,
std::span<const std::byte> message,
std::span<std::byte> output_20) noexcept
{
std::array<std::byte, 64> key_block{};
if (secret_key.size() > 64) {
Sha1State kh;
kh.update(secret_key);
kh.finalize_into(std::span{key_block}.subspan(0, 20));
} else if (!secret_key.empty()) {
std::memcpy(key_block.data(), secret_key.data(), secret_key.size());
}
std::array<std::byte, 64> ipad{};
std::array<std::byte, 64> opad{};
for (std::size_t i = 0; i < 64; ++i) {
ipad[i] = key_block[i] ^ std::byte{0x36};
opad[i] = key_block[i] ^ std::byte{0x5C};
}
std::array<std::byte, 20> inner_hash{};
{
Sha1State inner;
inner.update(ipad);
inner.update(message);
inner.finalize_into(inner_hash);
}
{
Sha1State outer;
outer.update(opad);
outer.update(inner_hash);
outer.finalize_into(output_20);
}
builtin_secure_wipe(key_block);
builtin_secure_wipe(ipad);
builtin_secure_wipe(opad);
builtin_secure_wipe(inner_hash);
}
void builtin_hmac_sha256(std::span<const std::byte> secret_key,
std::span<const std::byte> message,
std::span<std::byte> output_32) noexcept
@@ -892,4 +932,95 @@ namespace Void::Crypto::Detail
builtin_secure_wipe(t);
}
void builtin_pbkdf2_hmac_sha256(std::span<const std::byte> password,
std::span<const std::byte> salt,
std::uint32_t iterations,
std::span<std::byte> secret_output) noexcept
{
std::array<std::byte, 64> key_block{};
if (password.size() > 64) {
Sha256State kh;
kh.update(password);
kh.finalize_into(std::span{key_block}.subspan(0, 32));
} else if (!password.empty()) {
std::memcpy(key_block.data(), password.data(), password.size());
}
std::array<std::byte, 64> ipad{};
std::array<std::byte, 64> opad{};
for (std::size_t i = 0; i < 64; ++i) {
ipad[i] = key_block[i] ^ std::byte{0x36};
opad[i] = key_block[i] ^ std::byte{0x5C};
}
auto hmac = [&ipad, &opad](std::span<const std::byte> data,
std::span<std::byte> out) noexcept {
std::array<std::byte, 32> inner_hash{};
{
Sha256State inner;
inner.update(ipad);
inner.update(data);
inner.finalize_into(inner_hash);
}
{
Sha256State outer;
outer.update(opad);
outer.update(inner_hash);
outer.finalize_into(out);
}
builtin_secure_wipe(inner_hash);
};
// Callers cap the output length, so this cannot overflow.
const std::size_t blocks = (secret_output.size() + 31) / 32;
std::size_t written = 0;
for (std::size_t block = 1; block <= blocks; ++block) {
std::array<std::byte, 4> counter{};
store_be32(counter.data(), static_cast<std::uint32_t>(block));
std::array<std::byte, 32> u{};
{
std::array<std::byte, 32> inner_hash{};
{
Sha256State inner;
inner.update(ipad);
inner.update(salt);
inner.update(counter);
inner.finalize_into(inner_hash);
}
{
Sha256State outer;
outer.update(opad);
outer.update(inner_hash);
outer.finalize_into(u);
}
builtin_secure_wipe(inner_hash);
}
std::array<std::byte, 32> t = u;
for (std::uint32_t iteration = 1; iteration < iterations;
++iteration) {
std::array<std::byte, 32> next{};
hmac(u, next);
u = next;
for (std::size_t i = 0; i < t.size(); ++i) {
t[i] ^= u[i];
}
builtin_secure_wipe(next);
}
const std::size_t copy_n =
std::min<std::size_t>(32, secret_output.size() - written);
std::memcpy(secret_output.data() + written, t.data(), copy_n);
written += copy_n;
builtin_secure_wipe(u);
builtin_secure_wipe(t);
}
builtin_secure_wipe(key_block);
builtin_secure_wipe(ipad);
builtin_secure_wipe(opad);
}
} // namespace Void::Crypto::Detail
+10
View File
@@ -4,6 +4,7 @@
#include <Void/Crypto/Types.hpp>
#include <cstddef>
#include <cstdint>
#include <span>
namespace Void::Crypto::Detail
@@ -37,10 +38,19 @@ namespace Void::Crypto::Detail
void destroy() noexcept;
};
void builtin_hmac_sha1(std::span<const std::byte> secret_key,
std::span<const std::byte> message,
std::span<std::byte> output_20) noexcept;
void builtin_hmac_sha256(std::span<const std::byte> secret_key,
std::span<const std::byte> message,
std::span<std::byte> output_32) noexcept;
void builtin_pbkdf2_hmac_sha256(std::span<const std::byte> password,
std::span<const std::byte> salt,
std::uint32_t iterations,
std::span<std::byte> secret_output) noexcept;
void builtin_hkdf_sha256(std::span<const std::byte> secret_input,
std::span<const std::byte> salt,
std::span<const std::byte> context,
+251 -45
View File
@@ -220,6 +220,135 @@ namespace Void::Crypto
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::verifyEd25519: built without OpenSSL backend")};
#endif
}
[[maybe_unused]] [[nodiscard]] const char*
hmac_digest_name(HashAlgorithm algorithm) noexcept
{
switch (algorithm) {
case HashAlgorithm::Sha1:
return "SHA1";
case HashAlgorithm::Sha256:
return "SHA256";
default:
return nullptr;
}
}
[[nodiscard]] Void::Result::Result<void>
hmac_into_impl(HashAlgorithm algorithm,
std::span<const std::byte> secret_key,
std::span<const std::byte> message,
std::span<std::byte> output,
const ProviderOptions& provider,
std::string_view operation)
{
const std::size_t expected_size = algorithm == HashAlgorithm::Sha1
? HmacSha1Size
: HmacSha256Size;
if (output.size() != expected_size) {
return std::unexpected{
make_crypto_error(CryptoErrorCode::invalid_argument,
std::format("{}: output must be {} bytes",
operation, expected_size))};
}
if (spans_overlap(secret_key, output) ||
spans_overlap(message, output)) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::overlapping_buffers,
std::format("{}: output buffer overlaps input",
operation))};
}
if (auto fault =
maybe_inject_fault(FaultOperation::hmac, operation);
fault.has_value()) {
secure_wipe(output);
return std::unexpected{std::move(*fault)};
}
if (use_builtin_hash(algorithm, provider)) {
if (!provider.property_query.empty()) {
secure_wipe(output);
return std::unexpected{make_crypto_error(
CryptoErrorCode::provider_error,
std::format("{}: property_query unavailable on "
"built-in backend",
operation))};
}
if (algorithm == HashAlgorithm::Sha1) {
Detail::builtin_hmac_sha1(secret_key, message, output);
} else {
Detail::builtin_hmac_sha256(secret_key, message, output);
}
return {};
}
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
const char* name = hmac_digest_name(algorithm);
if (name == nullptr) {
secure_wipe(output);
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
std::format("{}: unsupported HMAC algorithm", operation))};
}
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,
std::format("{}: EVP_MAC_fetch failed", operation))};
}
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,
std::format("{}: EVP_MAC_CTX_new failed", operation))};
}
std::array<char, 8> digest_name{};
std::strncpy(digest_name.data(), name, digest_name.size() - 1);
std::array<OSSL_PARAM, 2> params = {
OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST,
digest_name.data(), 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,
std::format("{}: EVP_MAC_init failed", operation))};
}
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,
std::format("{}: EVP_MAC_update failed", operation))};
}
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 != expected_size) {
secure_wipe(output);
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
std::format("{}: EVP_MAC_final failed", operation))};
}
return {};
#else
secure_wipe(output);
return std::unexpected{make_crypto_error(
CryptoErrorCode::backend_error,
std::format("{}: OpenSSL backend unavailable", operation))};
#endif
}
} // namespace
@@ -891,26 +1020,98 @@ namespace Void::Crypto
provider);
}
Void::Result::Result<void>
hmac_sha1_into(std::span<const std::byte> secret_key,
std::span<const std::byte>
message,
std::span<std::byte>
output,
const ProviderOptions& provider)
{
return hmac_into_impl(HashAlgorithm::Sha1, secret_key, message, output,
provider, "Crypto::hmac_sha1_into");
}
Void::Result::Result<Digest>
hmac_sha1(std::span<const std::byte> secret_key,
std::span<const std::byte>
message,
const ProviderOptions& provider)
{
Digest out(HmacSha1Size);
if (auto res = hmac_sha1_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>
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 hmac_into_impl(HashAlgorithm::Sha256, secret_key, message,
output, provider, "Crypto::hmac_sha256_into");
}
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>
pbkdf2_hmac_sha256_into(std::span<const std::byte> password,
std::span<const std::byte> salt,
std::uint32_t iterations,
std::span<std::byte> output,
const ProviderOptions& provider)
{
if (iterations == 0 ||
iterations > CryptoLimits::kMaxPbkdf2Iterations) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_argument,
std::format("Crypto::hmac_sha256_into: output must be {} bytes",
HmacSha256Size))};
std::format("Crypto::pbkdf2_hmac_sha256: iterations must be "
"1..{}",
CryptoLimits::kMaxPbkdf2Iterations))};
}
if (spans_overlap(secret_key, output) ||
spans_overlap(message, output)) {
if (salt.size() > CryptoLimits::kMaxPbkdf2SaltBytes) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::message_too_large,
std::format("Crypto::pbkdf2_hmac_sha256: salt exceeds {} byte "
"cap",
CryptoLimits::kMaxPbkdf2SaltBytes))};
}
if (output.empty()) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_argument,
"Crypto::pbkdf2_hmac_sha256: output buffer must be non-empty")};
}
if (output.size() > CryptoLimits::kMaxPbkdf2OutputBytes) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::output_too_large,
std::format(
"Crypto::pbkdf2_hmac_sha256: output size exceeds {} byte "
"cap",
CryptoLimits::kMaxPbkdf2OutputBytes))};
}
if (spans_overlap(password, output) || spans_overlap(salt, output)) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::overlapping_buffers,
"Crypto::hmac_sha256_into: output buffer overlaps input")};
"Crypto::pbkdf2_hmac_sha256: output buffer overlaps input")};
}
if (auto fault = maybe_inject_fault(FaultOperation::hmac,
"Crypto::hmac_sha256_into");
if (auto fault = maybe_inject_fault(FaultOperation::pbkdf2,
"Crypto::pbkdf2_hmac_sha256");
fault.has_value()) {
secure_wipe(output);
return std::unexpected{std::move(*fault)};
@@ -921,78 +1122,83 @@ namespace Void::Crypto
secure_wipe(output);
return std::unexpected{make_crypto_error(
CryptoErrorCode::provider_error,
"Crypto::hmac_sha256_into: property_query unavailable on "
"Crypto::pbkdf2_hmac_sha256: property_query unavailable on "
"built-in backend")};
}
Detail::builtin_hmac_sha256(secret_key, message, output);
Detail::builtin_pbkdf2_hmac_sha256(password, salt, iterations,
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) {
EvpKdfPtr kdf{EVP_KDF_fetch(nullptr, "PBKDF2", propq_or_null(provider)),
&EVP_KDF_free};
if (!kdf) {
secure_wipe(output);
return std::unexpected{make_openssl_error(
CryptoErrorCode::provider_error,
"Crypto::hmac_sha256_into: EVP_MAC_fetch failed")};
"Crypto::pbkdf2_hmac_sha256: EVP_KDF_fetch failed")};
}
EvpMacCtxPtr ctx{EVP_MAC_CTX_new(mac.get()), &EVP_MAC_CTX_free};
EvpKdfCtxPtr ctx{EVP_KDF_CTX_new(kdf.get()), &EVP_KDF_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")};
"Crypto::pbkdf2_hmac_sha256: EVP_KDF_CTX_new failed")};
}
char digest_name[] = "SHA256";
std::array<OSSL_PARAM, 2> params = {
OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST, digest_name,
int iteration_count = static_cast<int>(iterations);
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_PASSWORD,
const_cast<unsigned char*>(non_null_bytes(password)),
password.size()),
OSSL_PARAM_construct_octet_string(
OSSL_KDF_PARAM_SALT,
const_cast<unsigned char*>(non_null_bytes(salt)), salt.size()),
OSSL_PARAM_construct_int(OSSL_KDF_PARAM_ITER, &iteration_count),
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) {
if (EVP_KDF_derive(ctx.get(),
reinterpret_cast<unsigned char*>(output.data()),
output.size(), params.data()) != 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")};
"Crypto::pbkdf2_hmac_sha256: EVP_KDF_derive failed")};
}
return {};
#else
secure_wipe(output);
return std::unexpected{make_crypto_error(
CryptoErrorCode::backend_error,
"Crypto::hmac_sha256_into: OpenSSL backend unavailable")};
"Crypto::pbkdf2_hmac_sha256: 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)
Void::Result::Result<Digest>
pbkdf2_hmac_sha256(std::span<const std::byte> password,
std::span<const std::byte> salt,
std::uint32_t iterations,
std::size_t output_length,
const ProviderOptions& provider)
{
Digest out(HmacSha256Size);
if (auto res = hmac_sha256_into(secret_key, message, out, provider);
if (output_length > CryptoLimits::kMaxPbkdf2OutputBytes) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::output_too_large,
std::format(
"Crypto::pbkdf2_hmac_sha256: output size exceeds {} byte "
"cap",
CryptoLimits::kMaxPbkdf2OutputBytes))};
}
Digest out(output_length);
if (auto res = pbkdf2_hmac_sha256_into(password, salt, iterations, out,
provider);
!res.has_value()) {
secure_wipe(out);
return std::unexpected{std::move(res.error())};
+395
View File
@@ -0,0 +1,395 @@
#include <Void/Crypto/Crypto.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <algorithm>
#include <array>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <span>
#include <string>
#include <string_view>
#include <vector>
namespace
{
int hex_nibble(char c)
{
if (c >= '0' && c <= '9') {
return c - '0';
}
if (c >= 'a' && c <= 'f') {
return c - 'a' + 10;
}
if (c >= 'A' && c <= 'F') {
return c - 'A' + 10;
}
return -1;
}
std::vector<std::byte> from_hex(std::string_view hex)
{
Void::Testing::require(hex.size() % 2 == 0);
std::vector<std::byte> out;
out.reserve(hex.size() / 2);
for (std::size_t i = 0; i < hex.size(); i += 2) {
const int hi = hex_nibble(hex[i]);
const int lo = hex_nibble(hex[i + 1]);
Void::Testing::require(hi >= 0 && lo >= 0);
out.push_back(static_cast<std::byte>((hi << 4) | lo));
}
return out;
}
std::string to_hex(std::span<const std::byte> data)
{
static constexpr char kHex[] = "0123456789abcdef";
std::string out;
out.reserve(data.size() * 2);
for (const std::byte b : data) {
const auto v = static_cast<unsigned char>(b);
out.push_back(kHex[v >> 4]);
out.push_back(kHex[v & 0x0F]);
}
return out;
}
std::span<const std::byte> as_bytes(std::string_view text)
{
return std::as_bytes(std::span{text.data(), text.size()});
}
std::string hotp(std::span<const std::byte> secret, std::uint64_t counter,
int digits)
{
std::array<std::byte, 8> message{};
for (std::size_t i = 0; i < message.size(); ++i) {
message[message.size() - 1 - i] =
static_cast<std::byte>((counter >> (8 * i)) & 0xFFU);
}
auto mac = Void::Crypto::hmac_sha1(secret, message);
Void::Testing::require(mac.has_value());
const auto offset = static_cast<std::size_t>(
std::to_integer<unsigned>(mac->back()) & 0x0FU);
const std::uint32_t binary =
((std::to_integer<std::uint32_t>((*mac)[offset]) & 0x7FU) << 24U) |
((std::to_integer<std::uint32_t>((*mac)[offset + 1]) & 0xFFU)
<< 16U) |
((std::to_integer<std::uint32_t>((*mac)[offset + 2]) & 0xFFU)
<< 8U) |
(std::to_integer<std::uint32_t>((*mac)[offset + 3]) & 0xFFU);
std::uint32_t modulus = 1;
for (int i = 0; i < digits; ++i) {
modulus *= 10U;
}
std::string code = std::to_string(binary % modulus);
while (code.size() < static_cast<std::size_t>(digits)) {
code.insert(code.begin(), '0');
}
return code;
}
std::string totp(std::span<const std::byte> secret, std::uint64_t unix_time,
int digits)
{
return hotp(secret, unix_time / 30U, digits);
}
} // namespace
Void::Testing::Test crypto_hmac_sha1_rfc2202_vectors()
{
using namespace Void::Crypto;
const std::array<std::string_view, 6> macs = {
"b617318655057264e28bc0b6fb378c8ef146be00",
"effcdf6ae5eb2fa2d27416d5f184df9c259a7c79",
"125d7342b9ac11cd91a39af48aa17b4f63f175d3",
"4c9007f4026250c6bc8414f9bf50c86c2d7235da",
"aa4ae5e15272d00e95705637ce8a3b55ed402112",
"e8e99d0f45237d786d6bbaa7965c7808bbff1a91"};
const std::vector<std::byte> twenty_0b(20, std::byte{0x0b});
const std::vector<std::byte> twenty_aa(20, std::byte{0xaa});
const std::vector<std::byte> eighty_aa(80, std::byte{0xaa});
const std::vector<std::byte> fifty_dd(50, std::byte{0xdd});
const std::vector<std::byte> fifty_cd(50, std::byte{0xcd});
const auto key4 =
from_hex("0102030405060708090a0b0c0d0e0f10111213141516171819");
// Keys/messages that are not pure hex are supplied directly.
struct RawVector {
std::span<const std::byte> key;
std::span<const std::byte> data;
std::string_view mac_hex;
};
const std::array<RawVector, 6> raw = {{
{twenty_0b, as_bytes("Hi There"), macs[0]},
{as_bytes("Jefe"), as_bytes("what do ya want for nothing?"),
macs[1]},
{twenty_aa, fifty_dd, macs[2]},
{key4, fifty_cd, macs[3]},
{eighty_aa,
as_bytes("Test Using Larger Than Block-Size Key - Hash Key First"),
macs[4]},
{eighty_aa,
as_bytes("Test Using Larger Than Block-Size Key and Larger Than One "
"Block-Size Data"),
macs[5]},
}};
const ProviderOptions builtin{.prefer_builtin = true};
for (const auto& vec : raw) {
for (const auto& opts : {ProviderOptions{}, builtin}) {
if (opts.prefer_builtin == false && !has_openssl_backend()) {
continue;
}
auto mac = hmac_sha1(vec.key, vec.data, opts);
Void::Testing::require(mac.has_value());
Void::Testing::expect_eq(to_hex(*mac), std::string{vec.mac_hex});
}
}
}
Void::Testing::Test crypto_hmac_sha1_boundaries_and_guards()
{
using namespace Void::Crypto;
// Empty key and message are valid.
auto empty = hmac_sha1({}, {});
Void::Testing::require(empty.has_value());
Void::Testing::expect_eq(empty->size(), HmacSha1Size);
// Wrong output size is rejected before touching the buffer.
std::array<std::byte, HmacSha1Size + 1> wrong_size{};
auto bad_size =
hmac_sha1_into(as_bytes("key"), as_bytes("msg"), wrong_size);
Void::Testing::require(!bad_size.has_value());
Void::Testing::expect_eq(
bad_size.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::invalid_argument));
// Overlapping input/output is rejected.
std::array<std::byte, 64> shared{};
shared.fill(std::byte{0x5A});
auto overlap = hmac_sha1_into(std::span{shared}.subspan(0, 20),
std::span{shared}.subspan(20, 20),
std::span{shared}.subspan(0, 20));
Void::Testing::require(!overlap.has_value());
Void::Testing::expect_eq(
overlap.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::overlapping_buffers));
// Injected backend fault wipes the destination.
std::array<std::byte, HmacSha1Size> wiped{};
wiped.fill(std::byte{0xCC});
{
ScopedFaultGuard fault{FaultConfig{FaultOperation::hmac,
CryptoErrorCode::provider_error, 0}};
auto failed = hmac_sha1_into(as_bytes("key"), as_bytes("msg"), wiped);
Void::Testing::require(!failed.has_value());
}
Void::Testing::expect(
std::all_of(wiped.begin(), wiped.end(),
[](std::byte b) { return b == std::byte{0}; }));
// property_query is unavailable on the built-in backend.
ProviderOptions bad_provider{.property_query = "provider=none",
.prefer_builtin = true};
auto unavailable =
hmac_sha1(as_bytes("key"), as_bytes("msg"), bad_provider);
Void::Testing::require(!unavailable.has_value());
Void::Testing::expect_eq(
unavailable.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::provider_error));
}
Void::Testing::Test crypto_hotp_totp_rfc4226_6238_vectors()
{
const auto secret = as_bytes("12345678901234567890");
// RFC 4226 Appendix D.
const std::array<std::string_view, 10> hotp_expected = {
"755224", "287082", "359152", "969429", "338314",
"254676", "287922", "162583", "399871", "520489"};
for (std::uint64_t counter = 0; counter < hotp_expected.size(); ++counter) {
Void::Testing::expect_eq(hotp(secret, counter, 6),
std::string{hotp_expected[counter]});
}
// RFC 6238 Appendix B (SHA-1 rows, 8 digits).
struct TotpVector {
std::uint64_t time;
std::string_view code;
};
const std::array<TotpVector, 6> totp_vectors = {{
{59, "94287082"},
{1111111109, "07081804"},
{1111111111, "14050471"},
{1234567890, "89005924"},
{2000000000, "69279037"},
{20000000000, "65353130"},
}};
for (const auto& vec : totp_vectors) {
Void::Testing::expect_eq(totp(secret, vec.time, 8),
std::string{vec.code});
}
}
Void::Testing::Test crypto_pbkdf2_hmac_sha256_rfc7914_vectors()
{
using namespace Void::Crypto;
const ProviderOptions builtin{.prefer_builtin = true};
// RFC 7914 section 11, first vector (c = 1, 64-byte output).
{
const auto expected = std::string{
"55ac046e56e3089fec1691c22544b605f94185216dde0465e68b9d57c20dacbc"
"49ca9cccf179b645991664b39d77ef317c71b845b1e30bd509112041d3a19783"};
for (const auto& opts : {ProviderOptions{}, builtin}) {
if (!opts.prefer_builtin && !has_openssl_backend()) {
continue;
}
auto derived = pbkdf2_hmac_sha256(as_bytes("passwd"),
as_bytes("salt"), 1, 64, opts);
Void::Testing::require(derived.has_value());
Void::Testing::expect_eq(to_hex(*derived), expected);
}
}
// RFC 7914 section 11, second vector (c = 80000, 64-byte output).
{
auto derived = pbkdf2_hmac_sha256(as_bytes("Password"),
as_bytes("NaCl"), 80000, 64);
Void::Testing::require(derived.has_value());
Void::Testing::expect_eq(
to_hex(*derived),
std::string{
"4ddcd8f60b98be21830cee5ef22701f9641a4418d04c0414aeff"
"08876b34ab56a1d425a1225833549adb841b51c9b3176a272bdebba1d0"
"78478f62b397f33c8d"});
}
}
Void::Testing::Test crypto_pbkdf2_hmac_sha256_boundaries_and_guards()
{
using namespace Void::Crypto;
const auto password = as_bytes("password");
const auto salt = as_bytes("salt");
// Zero and oversized iteration counts are rejected.
for (const std::uint32_t iterations :
{0U, CryptoLimits::kMaxPbkdf2Iterations + 1U}) {
std::array<std::byte, 32> out{};
auto r = pbkdf2_hmac_sha256_into(password, salt, iterations, out);
Void::Testing::require(!r.has_value());
Void::Testing::expect_eq(
r.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::invalid_argument));
}
// Oversized salt and output are rejected without mutating the output.
{
std::vector<std::byte> big_salt(CryptoLimits::kMaxPbkdf2SaltBytes + 1U,
std::byte{0x11});
std::array<std::byte, 32> out{};
auto r = pbkdf2_hmac_sha256_into(password, big_salt, 1, out);
Void::Testing::require(!r.has_value());
Void::Testing::expect_eq(
r.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::message_too_large));
std::vector<std::byte> big_out(CryptoLimits::kMaxPbkdf2OutputBytes + 1U,
std::byte{0x7A});
auto r_big = pbkdf2_hmac_sha256_into(password, salt, 1, big_out);
Void::Testing::require(!r_big.has_value());
Void::Testing::expect_eq(
r_big.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::output_too_large));
Void::Testing::expect(
std::all_of(big_out.begin(), big_out.end(),
[](std::byte b) { return b == std::byte{0x7A}; }));
std::span<std::byte> empty_out;
auto r_empty = pbkdf2_hmac_sha256_into(password, salt, 1, empty_out);
Void::Testing::require(!r_empty.has_value());
Void::Testing::expect_eq(
r_empty.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::invalid_argument));
// The Digest overload rejects an overflowing length before allocating.
auto r_overflow = pbkdf2_hmac_sha256(
password, salt, 1, std::numeric_limits<std::size_t>::max());
Void::Testing::require(!r_overflow.has_value());
Void::Testing::expect_eq(
r_overflow.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::output_too_large));
}
// Overlapping output is rejected.
{
std::array<std::byte, 64> shared{};
auto r = pbkdf2_hmac_sha256_into(std::span{shared}.subspan(0, 16), {},
1, std::span{shared}.subspan(8, 32));
Void::Testing::require(!r.has_value());
Void::Testing::expect_eq(
r.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::overlapping_buffers));
}
// Injected fault wipes the destination.
{
std::array<std::byte, 32> wiped{};
wiped.fill(std::byte{0xCC});
{
ScopedFaultGuard fault{FaultConfig{
FaultOperation::pbkdf2, CryptoErrorCode::provider_error, 0}};
auto r = pbkdf2_hmac_sha256_into(password, salt, 1, wiped);
Void::Testing::require(!r.has_value());
}
Void::Testing::expect(
std::all_of(wiped.begin(), wiped.end(),
[](std::byte b) { return b == std::byte{0}; }));
}
// Empty password and salt are valid; match hashlib reference values.
{
const auto expected = std::string{
"f7ce0b653d2d72a4108cf5abe912ffdd777616dbbb27a70e8204f3ae2d0f6fad"};
for (const auto& opts :
{ProviderOptions{}, ProviderOptions{.prefer_builtin = true}}) {
if (!opts.prefer_builtin && !has_openssl_backend()) {
continue;
}
auto derived = pbkdf2_hmac_sha256({}, {}, 1, 32, opts);
Void::Testing::require(derived.has_value());
Void::Testing::expect_eq(to_hex(*derived), expected);
}
}
// Partial final block and built-in/backend parity.
{
auto odd = pbkdf2_hmac_sha256(password, salt, 2, 33);
Void::Testing::require(odd.has_value());
Void::Testing::expect_eq(odd->size(), 33U);
auto prefix = pbkdf2_hmac_sha256(password, salt, 2, 32);
Void::Testing::require(prefix.has_value());
Void::Testing::expect(
std::equal(prefix->begin(), prefix->end(), odd->begin()));
auto builtin = pbkdf2_hmac_sha256(
password, salt, 2, 33, ProviderOptions{.prefer_builtin = true});
Void::Testing::require(builtin.has_value());
Void::Testing::expect_eq(*builtin, *odd);
auto gitea = pbkdf2_hmac_sha256(as_bytes("password"),
as_bytes("somesalt"), 10000, 32);
Void::Testing::require(gitea.has_value());
Void::Testing::expect_eq(
to_hex(*gitea),
std::string{"f47eaaf9fcacaf867696eaa1d205356d2d029bff08828a05d0dab"
"60b6e0c2de2"});
}
}