CsCrypto  1.0.1
sym_secret_key.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_SECRET_KEY_H
21 #define CS_CRYPTO_SYM_SECRET_KEY_H
22 
23 #include <util/conversions/byte.h>
24 #include <util/tools/crypto_traits.h>
25 
26 #include <algorithm>
27 #include <array>
28 #include <cstddef>
29 #include <optional>
30 #include <string>
31 #include <type_traits>
32 
33 namespace cs_crypto::cipher {
34 
35 template <std::size_t SIZE>
36 class secret_key
37 {
38  public:
39  template <typename T>
40  constexpr explicit secret_key(const T (&key)[SIZE])
41  {
42  if constexpr (cs_crypto::traits::is_uniquely_represented_byte_v<T>) {
43  std::copy_n(util::to_byte_ptr(key), SIZE, m_key_data.begin());
44  } else {
45  static_assert(cs_crypto::traits::always_false<T>{}, "Unable to construct secret key from array of type T");
46  }
47  }
48 
49  ~secret_key() = default;
50 
51  constexpr secret_key(const secret_key &other) = delete;
52  constexpr secret_key &operator=(const secret_key &other) & = delete;
53 
54  constexpr secret_key(secret_key &&other) = default;
55  constexpr secret_key &operator=(secret_key &&other) & = default;
56 
57 
58  constexpr static std::optional<secret_key> from_string(const std::string &key_data)
59  {
60  if (key_data.size() < SIZE) {
61  return std::nullopt;
62  }
63 
64  secret_key retval = {};
65  std::copy_n(util::to_byte_ptr(key_data.data()), SIZE, retval.m_key_data.data());
66 
67  return std::optional<secret_key>(std::move(retval));
68  }
69 
70  constexpr std::size_t size() const
71  {
72  return SIZE;
73  }
74 
75  constexpr auto data() const &
76  {
77  return m_key_data.data();
78  }
79 
80  private:
81  std::array<std::byte, SIZE> m_key_data = {};
82 
83  constexpr secret_key()
84  {
85  }
86 };
87 
88 } // namespace cs_crypto::cipher
89 
90 #endif