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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
use core::{
    fmt::{self, Debug, Formatter},
    marker::{PhantomData, PhantomPinned},
    ops::Deref,
};

use crate::generic_array::{ArrayLength, GenericArray};
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
use subtle::{Choice, ConstantTimeEq};
use zeroize::Zeroize;

use super::HexRepr;
use crate::{
    error::Error,
    kdf::{FromKeyDerivation, KeyDerivation},
    random::fill_random,
};

/// A secure representation for fixed-length keys
#[derive(Clone, Hash)]
#[repr(transparent)]
pub struct ArrayKey<L: ArrayLength<u8>>(
    GenericArray<u8, L>,
    // ensure that the type does not implement Unpin
    PhantomPinned,
);

impl<L: ArrayLength<u8>> ArrayKey<L> {
    /// The array length in bytes
    pub const SIZE: usize = L::USIZE;

    /// Create a new buffer using an initializer for the data
    pub fn new_with(f: impl FnOnce(&mut [u8])) -> Self {
        let mut slf = Self::default();
        f(slf.0.as_mut());
        slf
    }

    /// Create a new buffer using a fallible initializer for the data
    pub fn try_new_with<E>(f: impl FnOnce(&mut [u8]) -> Result<(), E>) -> Result<Self, E> {
        let mut slf = Self::default();
        f(slf.0.as_mut())?;
        Ok(slf)
    }

    /// Temporarily allocate and use a key
    pub fn temp<R>(f: impl FnOnce(&mut [u8]) -> R) -> R {
        let mut slf = Self::default();
        f(slf.0.as_mut())
    }

    /// Convert this array to a non-zeroing GenericArray instance
    #[inline]
    pub fn extract(self) -> GenericArray<u8, L> {
        self.0.clone()
    }

    /// Create a new array instance from a slice of bytes.
    /// Like <&GenericArray>::from_slice, panics if the length of the slice
    /// is incorrect.
    #[inline]
    pub fn from_slice(data: &[u8]) -> Self {
        Self::from(GenericArray::from_slice(data))
    }

    /// Get the length of the array
    #[inline]
    pub fn len() -> usize {
        Self::SIZE
    }

    /// Create a new array of random bytes
    #[inline]
    pub fn random() -> Self {
        Self::new_with(fill_random)
    }

    /// Get a hex formatter for the key data
    pub fn as_hex(&self) -> HexRepr<&[u8]> {
        HexRepr(self.0.as_ref())
    }
}

impl<L: ArrayLength<u8>> AsRef<GenericArray<u8, L>> for ArrayKey<L> {
    #[inline(always)]
    fn as_ref(&self) -> &GenericArray<u8, L> {
        &self.0
    }
}

impl<L: ArrayLength<u8>> Deref for ArrayKey<L> {
    type Target = [u8];

    #[inline(always)]
    fn deref(&self) -> &[u8] {
        self.0.as_ref()
    }
}

impl<L: ArrayLength<u8>> Default for ArrayKey<L> {
    #[inline(always)]
    fn default() -> Self {
        Self(GenericArray::default(), PhantomPinned)
    }
}

impl<L: ArrayLength<u8>> From<&GenericArray<u8, L>> for ArrayKey<L> {
    #[inline(always)]
    fn from(key: &GenericArray<u8, L>) -> Self {
        Self(key.clone(), PhantomPinned)
    }
}

impl<L: ArrayLength<u8>> From<GenericArray<u8, L>> for ArrayKey<L> {
    #[inline(always)]
    fn from(key: GenericArray<u8, L>) -> Self {
        Self(key, PhantomPinned)
    }
}

impl<L: ArrayLength<u8>> Debug for ArrayKey<L> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        if cfg!(test) {
            f.debug_tuple("ArrayKey").field(&*self).finish()
        } else {
            f.debug_tuple("ArrayKey").field(&"<secret>").finish()
        }
    }
}

impl<L: ArrayLength<u8>> ConstantTimeEq for ArrayKey<L> {
    fn ct_eq(&self, other: &Self) -> Choice {
        ConstantTimeEq::ct_eq(self.0.as_ref(), other.0.as_ref())
    }
}

impl<L: ArrayLength<u8>> PartialEq for ArrayKey<L> {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.ct_eq(other).into()
    }
}
impl<L: ArrayLength<u8>> Eq for ArrayKey<L> {}

impl<L: ArrayLength<u8>> Serialize for ArrayKey<L> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_bytes(self.as_ref())
    }
}

impl<'de, L: ArrayLength<u8>> Deserialize<'de> for ArrayKey<L> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_bytes(KeyVisitor { _pd: PhantomData })
    }
}

impl<L: ArrayLength<u8>> Zeroize for ArrayKey<L> {
    fn zeroize(&mut self) {
        self.0.zeroize();
    }
}

impl<L: ArrayLength<u8>> Drop for ArrayKey<L> {
    fn drop(&mut self) {
        self.zeroize();
    }
}

struct KeyVisitor<L: ArrayLength<u8>> {
    _pd: PhantomData<L>,
}

impl<'de, L: ArrayLength<u8>> de::Visitor<'de> for KeyVisitor<L> {
    type Value = ArrayKey<L>;

    fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        formatter.write_str("ArrayKey")
    }

    fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E>
    where
        E: de::Error,
    {
        if value.len() != L::USIZE {
            return Err(E::invalid_length(value.len(), &self));
        }
        Ok(ArrayKey::from_slice(value))
    }
}

impl<L: ArrayLength<u8>> FromKeyDerivation for ArrayKey<L> {
    fn from_key_derivation<D: KeyDerivation>(mut derive: D) -> Result<Self, Error>
    where
        Self: Sized,
    {
        Self::try_new_with(|buf| derive.derive_key_bytes(buf))
    }
}