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
use crate::{error::Error, scalar::Scalar};
use core::convert::{TryFrom, TryInto};
use generic_array::{ArrayLength, GenericArray};
#[cfg(feature = "getrandom")]
use getrandom::getrandom;
pub struct SecretKey<ScalarSize>
where
ScalarSize: ArrayLength<u8>,
{
scalar: Scalar<ScalarSize>,
}
impl<ScalarSize> SecretKey<ScalarSize>
where
ScalarSize: ArrayLength<u8>,
{
pub fn new(bytes: GenericArray<u8, ScalarSize>) -> Self {
Self {
scalar: Scalar::new(bytes),
}
}
pub fn from_bytes(bytes: impl AsRef<[u8]>) -> Result<Self, Error> {
bytes.as_ref().try_into()
}
#[cfg(feature = "getrandom")]
pub fn generate() -> Self {
let mut bytes = GenericArray::default();
getrandom(bytes.as_mut_slice()).expect("RNG failure!");
Self::new(bytes)
}
pub fn secret_scalar(&self) -> &Scalar<ScalarSize> {
&self.scalar
}
}
#[cfg(feature = "zeroize")]
impl<ScalarSize> Drop for SecretKey<ScalarSize>
where
ScalarSize: ArrayLength<u8>,
{
fn drop(&mut self) {
use zeroize::Zeroize;
self.scalar.zeroize();
}
}
impl<ScalarSize> TryFrom<&[u8]> for SecretKey<ScalarSize>
where
ScalarSize: ArrayLength<u8>,
{
type Error = Error;
fn try_from(slice: &[u8]) -> Result<Self, Error> {
if slice.len() == ScalarSize::to_usize() {
Ok(Self::new(GenericArray::clone_from_slice(slice)))
} else {
Err(Error)
}
}
}