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
use crate::{error::Error, Curve, ElementBytes};
use core::{
convert::{TryFrom, TryInto},
fmt::{self, Debug},
};
use generic_array::{typenum::Unsigned, GenericArray};
#[cfg(feature = "rand")]
use {
crate::{Arithmetic, Generate},
rand_core::{CryptoRng, RngCore},
};
#[derive(Clone)]
pub struct SecretKey<C: Curve> {
scalar: ElementBytes<C>,
}
impl<C: Curve> SecretKey<C> {
pub fn new(bytes: ElementBytes<C>) -> Self {
Self { scalar: bytes }
}
pub fn from_bytes(bytes: impl AsRef<[u8]>) -> Result<Self, Error> {
bytes.as_ref().try_into()
}
pub fn as_bytes(&self) -> &ElementBytes<C> {
&self.scalar
}
}
impl<C: Curve> TryFrom<&[u8]> for SecretKey<C> {
type Error = Error;
fn try_from(slice: &[u8]) -> Result<Self, Error> {
if slice.len() == C::ElementSize::to_usize() {
Ok(SecretKey {
scalar: GenericArray::clone_from_slice(slice),
})
} else {
Err(Error)
}
}
}
impl<C: Curve> Debug for SecretKey<C> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "SecretKey<{:?}>{{ ... }}", C::default())
}
}
#[cfg(feature = "rand")]
#[cfg_attr(docsrs, doc(cfg(feature = "rand")))]
impl<C> Generate for SecretKey<C>
where
C: Curve + Arithmetic,
C::Scalar: Generate + Into<ElementBytes<C>>,
{
fn generate(rng: impl CryptoRng + RngCore) -> Self {
Self {
scalar: C::Scalar::generate(rng).into(),
}
}
}
#[cfg(feature = "zeroize")]
impl<C: Curve> Drop for SecretKey<C> {
fn drop(&mut self) {
use zeroize::Zeroize;
self.scalar.zeroize();
}
}