Botan 3.11.0
Crypto and TLS for C&
mem_utils.h
Go to the documentation of this file.
1/*
2* (C) 2025 Jack Lloyd
3*
4* Botan is released under the Simplified BSD License (see license.txt)
5*/
6
7#ifndef BOTAN_MEM_UTILS_H_
8#define BOTAN_MEM_UTILS_H_
9
10#include <botan/types.h>
11#include <concepts>
12#include <cstring>
13#include <span>
14#include <string>
15#include <string_view>
16#include <type_traits>
17
18namespace Botan {
19
20/**
21* Zeroize memory contents in a way that a compiler should not elide,
22* using some system specific technique.
23*
24* Use this function to scrub memory just before deallocating it, or on
25* a stack buffer before returning from the function.
26*
27* @param ptr a pointer to memory to scrub
28* @param n the number of bytes pointed to by ptr
29*/
30BOTAN_TEST_API void secure_zeroize_buffer(void* ptr, size_t n);
31
32/**
33 * @param buf a pointer to the start of the region
34 * @param n the number of elements in buf
35 */
36template <std::unsigned_integral T>
37inline void zeroize_buffer(T buf[], size_t n) {
38 if(n > 0) {
39 std::memset(buf, 0, sizeof(T) * n);
40 }
41}
42
43template <std::unsigned_integral T>
44inline void unchecked_copy_memory(T* out, const T* in, size_t n) {
45 if(in != nullptr && out != nullptr && n > 0) {
46 std::memmove(out, in, sizeof(T) * n);
47 }
48}
49
50/**
51* Return true if any of the provided arguments are null
52*/
53template <typename... Ptrs>
54bool any_null_pointers(Ptrs... ptr) {
55 static_assert((... && std::is_pointer_v<Ptrs>), "All arguments must be pointers");
56 return (... || (ptr == nullptr));
57}
58
59inline std::span<const uint8_t> as_span_of_bytes(const char* s, size_t len) {
60 const uint8_t* b = reinterpret_cast<const uint8_t*>(s);
61 return std::span{b, len};
62}
63
64inline std::span<const uint8_t> as_span_of_bytes(const std::string& s) {
65 return as_span_of_bytes(s.data(), s.size());
66}
67
68inline std::span<const uint8_t> as_span_of_bytes(std::string_view s) {
69 return as_span_of_bytes(s.data(), s.size());
70}
71
72inline std::span<const uint8_t> cstr_as_span_of_bytes(const char* s) {
73 return as_span_of_bytes(s, std::strlen(s));
74}
75
76inline std::string bytes_to_string(std::span<const uint8_t> bytes) {
77 return std::string(reinterpret_cast<const char*>(bytes.data()), bytes.size());
78}
79
80} // namespace Botan
81
82#endif
#define BOTAN_TEST_API
Definition api.h:41
std::span< const uint8_t > as_span_of_bytes(const char *s, size_t len)
Definition mem_utils.h:59
std::string bytes_to_string(std::span< const uint8_t > bytes)
Definition mem_utils.h:76
void zeroize_buffer(T buf[], size_t n)
Definition mem_utils.h:37
std::span< const uint8_t > cstr_as_span_of_bytes(const char *s)
Definition mem_utils.h:72
void unchecked_copy_memory(T *out, const T *in, size_t n)
Definition mem_utils.h:44
void secure_zeroize_buffer(void *ptr, size_t n)
Definition mem_utils.cpp:29
bool any_null_pointers(Ptrs... ptr)
Definition mem_utils.h:54