1#[cfg(feature = "alloc")]
2use alloc::vec::Vec;
3use zeroize::{Zeroize, ZeroizeOnDrop};
4
5use crate::CryptoError;
6
7#[derive(Zeroize, ZeroizeOnDrop)]
27pub struct SecretKey<const N: usize> {
28 bytes: [u8; N],
29}
30
31impl<const N: usize> SecretKey<N> {
32 #[must_use]
34 pub fn new(bytes: [u8; N]) -> Self {
35 Self { bytes }
36 }
37
38 #[must_use = "result must be checked"]
42 pub fn from_slice(slice: &[u8]) -> Result<Self, CryptoError> {
43 let bytes: [u8; N] = slice.try_into().map_err(|_| CryptoError::InvalidKey)?;
44 Ok(Self { bytes })
45 }
46
47 #[must_use]
51 pub fn as_bytes(&self) -> &[u8; N] {
52 &self.bytes
53 }
54}
55
56impl<const N: usize> core::fmt::Debug for SecretKey<N> {
57 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
58 write!(f, "SecretKey<{N}>(***)")
59 }
60}
61
62impl<const N: usize> Clone for SecretKey<N> {
63 fn clone(&self) -> Self {
64 Self { bytes: self.bytes }
65 }
66}
67
68#[cfg(feature = "alloc")]
78#[derive(Zeroize, ZeroizeOnDrop)]
79pub struct SecretVec {
80 bytes: Vec<u8>,
81}
82
83#[cfg(feature = "alloc")]
84impl SecretVec {
85 #[must_use]
87 pub fn new(bytes: Vec<u8>) -> Self {
88 Self { bytes }
89 }
90
91 #[must_use]
93 pub fn from_slice(slice: &[u8]) -> Self {
94 Self {
95 bytes: slice.to_vec(),
96 }
97 }
98
99 #[must_use]
101 pub fn as_bytes(&self) -> &[u8] {
102 &self.bytes
103 }
104
105 #[must_use]
107 pub fn len(&self) -> usize {
108 self.bytes.len()
109 }
110
111 #[must_use]
113 pub fn is_empty(&self) -> bool {
114 self.bytes.is_empty()
115 }
116}
117
118#[cfg(feature = "alloc")]
119impl core::fmt::Debug for SecretVec {
120 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
121 write!(f, "SecretVec(len={}, ***)", self.bytes.len())
122 }
123}
124
125#[cfg(feature = "alloc")]
126impl Clone for SecretVec {
127 fn clone(&self) -> Self {
128 Self {
129 bytes: self.bytes.clone(),
130 }
131 }
132}
133
134pub struct KeyPair<SK: Zeroize, PK> {
143 secret: SK,
144 public: PK,
145}
146
147impl<SK: Zeroize, PK> KeyPair<SK, PK> {
148 #[must_use]
150 pub fn new(secret: SK, public: PK) -> Self {
151 Self { secret, public }
152 }
153
154 #[must_use]
156 pub fn secret(&self) -> &SK {
157 &self.secret
158 }
159
160 #[must_use]
162 pub fn public(&self) -> &PK {
163 &self.public
164 }
165}
166
167impl<SK: Zeroize, PK> Drop for KeyPair<SK, PK> {
168 fn drop(&mut self) {
169 self.secret.zeroize();
170 }
171}
172
173impl<SK: Zeroize + core::fmt::Debug, PK: core::fmt::Debug> core::fmt::Debug for KeyPair<SK, PK> {
174 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
175 f.debug_struct("KeyPair")
176 .field("secret", &"***")
177 .field("public", &self.public)
178 .finish()
179 }
180}