purify
C++ Purify implementation with native circuit and BPP support
Loading...
Searching...
No Matches
secure_cleanup.hpp
Go to the documentation of this file.
1// Copyright (c) 2026 Judica, Inc.
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or https://opensource.org/license/mit/.
4
5#pragma once
6
7#include <cstddef>
8#include <memory>
9#include <ranges>
10#include <type_traits>
11
12#include "purify/secret.hpp"
13
14namespace purify::detail {
15
16template <typename T>
18 std::ranges::contiguous_range<T> && std::ranges::sized_range<T> &&
19 !std::is_const_v<std::remove_reference_t<
20 std::ranges::range_reference_t<T>>> &&
21 std::is_trivially_destructible_v<
22 std::remove_cv_t<std::ranges::range_value_t<T>>>;
23
25template <MutableContiguousRange T>
26void secure_erase(T& value) noexcept {
27 using Element = std::remove_cv_t<std::ranges::range_value_t<T>>;
28 const auto count = static_cast<std::size_t>(std::ranges::size(value));
29 secure_clear_bytes(std::ranges::data(value), count * sizeof(Element));
30}
31
33template <typename T>
34 requires (!std::ranges::range<T> && !std::is_const_v<T> &&
35 std::is_trivially_destructible_v<T>)
36void secure_erase(T& value) noexcept {
37 secure_clear_bytes(std::addressof(value), sizeof(T));
38}
39
40template <typename T>
41concept SecureErasable = requires(T& value) {
42 secure_erase(value);
43};
44
45template <typename T>
47 std::is_trivially_destructible_v<T> &&
48 !std::ranges::view<T>;
49
51template <SecretValue T>
52class Secret {
53public:
54 Secret() = default;
55 Secret(const Secret&) = delete;
56 Secret& operator=(const Secret&) = delete;
57 Secret(Secret&&) = delete;
58 Secret& operator=(Secret&&) = delete;
59
62 }
63
64 T value{};
65};
66
68template <SecureErasable T>
70public:
71 explicit WipeOnDestruction(T& value) noexcept
72 : value_(std::addressof(value)) {}
73
78
80 secure_erase(*value_);
81 }
82
83private:
84 T* value_;
85};
86
87} // namespace purify::detail
Secret & operator=(const Secret &)=delete
Secret(Secret &&)=delete
Secret & operator=(Secret &&)=delete
Secret(const Secret &)=delete
WipeOnDestruction(WipeOnDestruction &&)=delete
WipeOnDestruction & operator=(WipeOnDestruction &&)=delete
WipeOnDestruction(const WipeOnDestruction &)=delete
WipeOnDestruction & operator=(const WipeOnDestruction &)=delete
void secure_clear_bytes(void *data, std::size_t size) noexcept
Definition secret.hpp:22
void secure_erase(T &value) noexcept
Secret-owning Purify key material wrappers.