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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
use super::Error;
use core::iter::FromIterator;
use curve25519_dalek::constants;
use curve25519_dalek::edwards::{CompressedEdwardsY, EdwardsPoint};
use curve25519_dalek::scalar::Scalar;
use hex::{FromHex, ToHex};
use rand::{CryptoRng, RngCore};
use zeroize::Zeroize;
pub const SECRET_KEY_LENGTH: usize = 32;
pub const PUBLIC_KEY_LENGTH: usize = 32;
#[derive(Debug)]
pub struct SecretKey(pub(crate) [u8; SECRET_KEY_LENGTH]);
impl Drop for SecretKey {
fn drop(&mut self) {
self.0.zeroize();
}
}
impl ToHex for SecretKey {
fn encode_hex<T: FromIterator<char>>(&self) -> T {
self.0.encode_hex()
}
fn encode_hex_upper<T: FromIterator<char>>(&self) -> T {
self.0.encode_hex_upper()
}
}
impl FromHex for SecretKey {
type Error = Error;
fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Error> {
let mut bytes = Vec::<u8>::from_hex(hex).map_err(|_| Error::InvalidSecretKeyBytes)?;
let sk = Self::from_bytes(&bytes)?;
bytes.zeroize();
Ok(sk)
}
}
impl SecretKey {
#[inline]
pub fn to_bytes(&self) -> [u8; SECRET_KEY_LENGTH] {
self.0
}
#[inline]
pub fn as_bytes<'a>(&'a self) -> &'a [u8; SECRET_KEY_LENGTH] {
&self.0
}
#[inline]
pub fn from_bytes(bytes: &[u8]) -> Result<SecretKey, Error> {
if bytes.len() != SECRET_KEY_LENGTH {
return Err(Error::InvalidSecretKeyBytes);
}
let mut bits: [u8; 32] = [0u8; 32];
bits.copy_from_slice(&bytes[..32]);
Ok(SecretKey(bits))
}
pub fn generate<T>(csprng: &mut T) -> SecretKey
where
T: CryptoRng + RngCore,
{
let mut sk: SecretKey = SecretKey([0u8; 32]);
csprng.fill_bytes(&mut sk.0);
sk
}
}
#[derive(Copy, Clone, Default, Eq, PartialEq)]
pub struct PublicKey(pub(crate) CompressedEdwardsY);
impl PublicKey {
#[inline]
pub fn to_bytes(&self) -> [u8; PUBLIC_KEY_LENGTH] {
self.0.to_bytes()
}
#[inline]
pub fn as_bytes<'a>(&'a self) -> &'a [u8; PUBLIC_KEY_LENGTH] {
self.0.as_bytes()
}
#[inline]
pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
if bytes.len() != PUBLIC_KEY_LENGTH {
return Err(Error::InvalidPublicKeyBytes);
}
let point = CompressedEdwardsY::from_slice(bytes);
if point.decompress().is_none() {
return Err(Error::InvalidPublicKeyBytes);
}
Ok(PublicKey(point))
}
pub fn from_secret(sk: &SecretKey) -> Self {
let point = &Scalar::from_bits(sk.to_bytes()) * &constants::ED25519_BASEPOINT_TABLE;
PublicKey(point.compress())
}
pub fn to_point(&self) -> EdwardsPoint {
CompressedEdwardsY::from_slice(self.0.as_bytes())
.decompress()
.expect("ecies-ed25519: unexpect error decompressing public key")
}
}
impl FromHex for PublicKey {
type Error = Error;
fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Error> {
let mut bytes = Vec::<u8>::from_hex(hex).map_err(|_| Error::InvalidPublicKeyBytes)?;
let sk = Self::from_bytes(&bytes)?;
bytes.zeroize();
Ok(sk)
}
}
impl AsRef<[u8]> for PublicKey {
fn as_ref(&self) -> &[u8] {
self.as_bytes()
}
}
#[cfg(feature = "serde")]
use serde::{
de::Error as SerdeError, de::Unexpected, de::Visitor, Deserialize, Deserializer, Serialize,
Serializer,
};
#[cfg(feature = "serde")]
impl Serialize for SecretKey {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
if serializer.is_human_readable() {
let encoded: Vec<char> = self.encode_hex();
let mut encoded: String = encoded.into_iter().collect();
let result = serializer.serialize_str(&encoded);
encoded.zeroize();
result
} else {
serializer.serialize_bytes(self.as_bytes())
}
}
}
#[cfg(feature = "serde")]
impl<'d> Deserialize<'d> for SecretKey {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'d>,
{
struct SecretKeyVisitor;
impl<'d> Visitor<'d> for SecretKeyVisitor {
type Value = SecretKey;
fn expecting(&self, formatter: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
formatter.write_str("An ecies-ed25519 secret key as 32 bytes.")
}
fn visit_str<E>(self, input: &str) -> Result<SecretKey, E>
where
E: SerdeError,
{
let mut bytes = hex::decode(input).or(Err(SerdeError::invalid_value(
Unexpected::Other("invalid hex"),
&self,
)))?;
let sk = SecretKey::from_bytes(&bytes)
.or(Err(SerdeError::invalid_length(bytes.len(), &self)))?;
bytes.zeroize();
Ok(sk)
}
fn visit_bytes<E>(self, bytes: &[u8]) -> Result<SecretKey, E>
where
E: SerdeError,
{
SecretKey::from_bytes(bytes).or(Err(SerdeError::invalid_length(bytes.len(), &self)))
}
}
if deserializer.is_human_readable() {
deserializer.deserialize_str(SecretKeyVisitor)
} else {
deserializer.deserialize_bytes(SecretKeyVisitor)
}
}
}
#[cfg(feature = "serde")]
impl Serialize for PublicKey {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
if serializer.is_human_readable() {
let encoded: Vec<char> = self.encode_hex();
let mut encoded: String = encoded.into_iter().collect();
let result = serializer.serialize_str(&encoded);
encoded.zeroize();
result
} else {
serializer.serialize_bytes(self.as_bytes())
}
}
}
#[cfg(feature = "serde")]
impl<'d> Deserialize<'d> for PublicKey {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'d>,
{
struct PublicKeyVisitor;
impl<'d> Visitor<'d> for PublicKeyVisitor {
type Value = PublicKey;
fn expecting(&self, formatter: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
formatter.write_str("An ecies-ed25519 public key as 32 bytes.")
}
fn visit_str<E>(self, input: &str) -> Result<PublicKey, E>
where
E: SerdeError,
{
if input.len() != PUBLIC_KEY_LENGTH * 2 {
return Err(SerdeError::invalid_length(input.len(), &self));
}
let mut bytes = hex::decode(input).or(Err(SerdeError::invalid_value(
Unexpected::Other("invalid hex"),
&self,
)))?;
let pk = PublicKey::from_bytes(&bytes).map_err(|e| SerdeError::custom(e))?;
bytes.zeroize();
Ok(pk)
}
fn visit_bytes<E>(self, bytes: &[u8]) -> Result<PublicKey, E>
where
E: SerdeError,
{
if bytes.len() != PUBLIC_KEY_LENGTH {
return Err(SerdeError::invalid_length(bytes.len(), &self));
}
PublicKey::from_bytes(bytes).map_err(|e| SerdeError::custom(e))
}
}
if deserializer.is_human_readable() {
deserializer.deserialize_str(PublicKeyVisitor)
} else {
deserializer.deserialize_bytes(PublicKeyVisitor)
}
}
}