CsCrypto  1.0.1
sym_init_vector.h
1 /***********************************************************************
2 *
3 * Copyright (c) 2021-2024 Tim van Deurzen
4 * Copyright (c) 2021-2024 Barbara Geller
5 * Copyright (c) 2021-2024 Ansel Sermersheim
6 *
7 * This file is part of CsCrypto.
8 *
9 * CsCrypto is free software, released under the BSD 2-Clause license.
10 * For license details refer to LICENSE provided with this project.
11 *
12 * CsCrypto is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
15 *
16 * https://opensource.org/licenses/BSD-2-Clause
17 *
18 ***********************************************************************/
19 
20 #ifndef CS_CRYPTO_SYM_INIT_VECTOR_H
21 #define CS_CRYPTO_SYM_INIT_VECTOR_H
22 
23 #include <util/conversions/byte.h>
24 #include <util/tools/crypto_traits.h>
25 
26 #include <array>
27 #include <optional>
28 #include <cstddef>
29 #include <algorithm>
30 #include <type_traits>
31 
32 namespace cs_crypto::cipher {
33 
34 template <std::size_t SIZE>
35 class init_vector
36 {
37  public:
38  template <typename T>
39  constexpr explicit init_vector(const T (&iv)[SIZE])
40  {
41  if constexpr (cs_crypto::traits::is_uniquely_represented_byte_v<T>) {
42  std::copy_n(util::to_byte_ptr(iv), SIZE, m_data.begin());
43  } else {
44  static_assert(cs_crypto::traits::always_false<T>{}, "Unable to construct init_vector object from array of type T");
45  }
46  }
47 
48  ~init_vector() = default;
49 
50  constexpr init_vector(const init_vector &other) = delete;
51  constexpr init_vector &operator=(const init_vector &other) & = delete;
52 
53  constexpr init_vector(init_vector &&other) = default;
54  constexpr init_vector &operator=(init_vector &&other) & = default;
55 
56  constexpr static std::optional<init_vector> from_string(const std::string &str)
57  {
58  if (str.size() != SIZE) {
59  return std::nullopt;
60  }
61 
62  std::optional<init_vector> retval = init_vector{};
63  std::copy_n(util::to_byte_ptr(str.data()), SIZE, retval.value().m_data.data());
64 
65  return retval;
66  }
67 
68  constexpr std::size_t size() const
69  {
70  return SIZE;
71  }
72 
73  constexpr auto data() const &
74  {
75  return m_data.data();
76  }
77 
78  private:
79  std::array<std::byte, SIZE> m_data = {};
80 
81  constexpr init_vector()
82  {
83  }
84 };
85 
86 } // namespace cs_crypto::cipher
87 
88 #endif