1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
use derive_more::{Display, Error};
use rand::{rngs::OsRng, RngCore};
use std::{fmt, str::FromStr};
#[derive(Debug, Display, Error)]
pub struct SecretKeyError;
pub type SecretKey32 = SecretKey<32>;
#[derive(Clone, PartialEq, Eq)]
pub struct SecretKey<const N: usize>([u8; N]);
impl<const N: usize> fmt::Debug for SecretKey<N> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("SecretKey")
            .field(&"**OMITTED**".to_string())
            .finish()
    }
}
impl<const N: usize> Default for SecretKey<N> {
    
    
    
    
    
    fn default() -> Self {
        Self::generate().unwrap()
    }
}
impl<const N: usize> SecretKey<N> {
    
    pub fn unprotected_as_bytes(&self) -> &[u8] {
        &self.0
    }
    
    pub fn unprotected_as_byte_array(&self) -> &[u8; N] {
        &self.0
    }
    
    #[allow(clippy::len_without_is_empty)]
    pub fn len(&self) -> usize {
        N
    }
    
    
    pub fn generate() -> Result<Self, SecretKeyError> {
        
        if N < 1 || N > (isize::MAX as usize) {
            return Err(SecretKeyError);
        }
        let mut key = [0; N];
        OsRng.fill_bytes(&mut key);
        Ok(Self(key))
    }
    
    
    pub fn from_slice(slice: &[u8]) -> Result<Self, SecretKeyError> {
        if slice.len() != N {
            return Err(SecretKeyError);
        }
        let mut value = [0u8; N];
        value[..N].copy_from_slice(slice);
        Ok(Self(value))
    }
}
impl<const N: usize> From<[u8; N]> for SecretKey<N> {
    fn from(arr: [u8; N]) -> Self {
        Self(arr)
    }
}
impl<const N: usize> FromStr for SecretKey<N> {
    type Err = SecretKeyError;
    
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let bytes = hex::decode(s).map_err(|_| SecretKeyError)?;
        Self::from_slice(&bytes)
    }
}
impl<const N: usize> fmt::Display for SecretKey<N> {
    
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", hex::encode(self.unprotected_as_bytes()))
    }
}