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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
use sodiumoxide::crypto::sign::ed25519::{PublicKey as PublicKeySodium,
SecretKey as SecretKeySodium, Seed as SeedSodium,
Signature as SignatureSodium, State as SignState,
sign_detached, verify_detached, keypair_from_seed,
gen_keypair as gen_keypair_sodium};
use sodiumoxide::crypto::hash::sha256::{Digest, State as HashState, hash as hash_sodium};
use sodiumoxide;
use serde::{Serialize, Serializer};
use serde::de::{self, Visitor, Deserialize, Deserializer};
use hex::{ToHex, FromHex};
use std::default::Default;
use std::ops::{Index, Range, RangeFrom, RangeTo, RangeFull};
use std::fmt;
pub use sodiumoxide::crypto::sign::ed25519::{PUBLICKEYBYTES as PUBLIC_KEY_LENGTH,
SECRETKEYBYTES as SECRET_KEY_LENGTH,
SIGNATUREBYTES as SIGNATURE_LENGTH,
SEEDBYTES as SEED_LENGTH};
pub use sodiumoxide::crypto::hash::sha256::DIGESTBYTES as HASH_SIZE;
pub use encoding::serialize::{FromHexError, HexValue};
const BYTES_IN_DEBUG: usize = 4;
pub fn sign(data: &[u8], secret_key: &SecretKey) -> Signature {
let sodium_signature = sign_detached(data, &secret_key.0);
Signature(sodium_signature)
}
pub fn gen_keypair_from_seed(seed: &Seed) -> (PublicKey, SecretKey) {
let (sod_pub_key, sod_secr_key) = keypair_from_seed(&seed.0);
(PublicKey(sod_pub_key), SecretKey(sod_secr_key))
}
pub fn gen_keypair() -> (PublicKey, SecretKey) {
let (pubkey, secrkey) = gen_keypair_sodium();
(PublicKey(pubkey), SecretKey(secrkey))
}
pub fn verify(sig: &Signature, data: &[u8], pubkey: &PublicKey) -> bool {
verify_detached(&sig.0, data, &pubkey.0)
}
pub fn hash(data: &[u8]) -> Hash {
let dig = hash_sodium(data);
Hash(dig)
}
pub fn init() {
if !sodiumoxide::init() {
panic!("Cryptographic library hasn't initialized.");
}
}
#[derive(Debug, Default)]
pub struct HashStream(HashState);
impl HashStream {
pub fn new() -> Self {
HashStream(HashState::init())
}
pub fn update(mut self, chunk: &[u8]) -> Self {
self.0.update(chunk);
self
}
pub fn hash(self) -> Hash {
let dig = self.0.finalize();
Hash(dig)
}
}
#[derive(Debug, Default)]
pub struct SignStream(SignState);
impl SignStream {
pub fn new() -> Self {
SignStream(SignState::init())
}
pub fn update(mut self, chunk: &[u8]) -> Self {
self.0.update(chunk);
self
}
pub fn sign(&mut self, secret_key: &SecretKey) -> Signature {
Signature(self.0.finalize(&secret_key.0))
}
pub fn verify(&mut self, sig: &Signature, public_key: &PublicKey) -> bool {
self.0.verify(&sig.0, &public_key.0)
}
}
macro_rules! implement_public_sodium_wrapper {
($(#[$attr:meta])* struct $name:ident, $name_from:ident, $size:expr) => (
#[derive(PartialEq, Eq, Clone, Copy, PartialOrd, Ord, Hash)]
$(#[$attr])*
pub struct $name($name_from);
impl $name {
pub fn zero() -> Self {
$name::new([0; $size])
}
}
impl $name {
pub fn new(ba: [u8; $size]) -> Self {
$name($name_from(ba))
}
pub fn from_slice(bs: &[u8]) -> Option<Self> {
$name_from::from_slice(bs).map($name)
}
}
impl AsRef<[u8]> for $name {
fn as_ref(&self) -> &[u8] {
self.0.as_ref()
}
}
impl ::std::str::FromStr for $name {
type Err = ::encoding::serialize::FromHexError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
$name::from_hex(s)
}
}
impl ToString for $name {
fn to_string(&self) -> String {
::crypto::HexValue::to_hex(self)
}
}
impl fmt::Debug for $name {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, stringify!($name))?;
write!(f, "(")?;
for i in &self[0..BYTES_IN_DEBUG] {
write!(f, "{:02X}", i)?
}
write!(f, ")")
}
}
)
}
macro_rules! implement_private_sodium_wrapper {
($(#[$attr:meta])* struct $name:ident, $name_from:ident, $size:expr) => (
#[derive(Clone, PartialEq, Eq)]
$(#[$attr])*
pub struct $name($name_from);
impl $name {
pub fn zero() -> Self {
$name::new([0; $size])
}
}
impl $name {
pub fn new(ba: [u8; $size]) -> Self {
$name($name_from(ba))
}
pub fn from_slice(bs: &[u8]) -> Option<Self> {
$name_from::from_slice(bs).map($name)
}
}
impl fmt::Debug for $name {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, stringify!($name))?;
write!(f, "(")?;
for i in &self[0..BYTES_IN_DEBUG] {
write!(f, "{:02X}", i)?
}
write!(f, "...)")
}
}
)
}
implement_public_sodium_wrapper! {
struct PublicKey, PublicKeySodium, PUBLIC_KEY_LENGTH
}
implement_private_sodium_wrapper! {
struct SecretKey, SecretKeySodium, SECRET_KEY_LENGTH
}
implement_public_sodium_wrapper! {
struct Hash, Digest, HASH_SIZE
}
implement_public_sodium_wrapper! {
struct Signature, SignatureSodium, SIGNATURE_LENGTH
}
implement_private_sodium_wrapper! {
struct Seed, SeedSodium, SEED_LENGTH
}
macro_rules! implement_serde {
($name:ident) => (
impl HexValue for $name {
fn to_hex(&self) -> String {
let inner = &self.0;
inner.0.as_ref().to_hex()
}
fn from_hex<T: AsRef<str>>(v: T) -> Result<Self, FromHexError> {
let bytes: Vec<u8> = FromHex::from_hex(v.as_ref())?;
if let Some(self_value) = Self::from_slice(bytes.as_ref()) {
Ok(self_value)
} else {
Err(FromHexError::InvalidHexLength)
}
}
}
impl Serialize for $name
{
fn serialize<S>(&self, ser:S) -> Result<S::Ok, S::Error>
where S: Serializer
{
ser.serialize_str(&HexValue::to_hex(self))
}
}
impl<'de> Deserialize<'de> for $name
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>
{
struct HexVisitor;
impl<'v> Visitor<'v> for HexVisitor
{
type Value = $name;
fn expecting (&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(fmt, "expecting str.")
}
fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
where E: de::Error
{
$name::from_hex(s).map_err(|_| de::Error::custom("Invalid hex"))
}
}
deserializer.deserialize_str(HexVisitor)
}
}
)
}
implement_serde! {Hash}
implement_serde! {PublicKey}
implement_serde! {SecretKey}
implement_serde! {Seed}
implement_serde! {Signature}
impl HexValue for Vec<u8> {
fn to_hex(&self) -> String {
ToHex::to_hex(self)
}
fn from_hex<T: AsRef<str>>(v: T) -> Result<Self, FromHexError> {
FromHex::from_hex(v.as_ref())
}
}
macro_rules! implement_index_traits {
($newtype:ident) => (
impl Index<Range<usize>> for $newtype {
type Output = [u8];
fn index(&self, _index: Range<usize>) -> &[u8] {
let inner = &self.0;
inner.0.index(_index)
}
}
impl Index<RangeTo<usize>> for $newtype {
type Output = [u8];
fn index(&self, _index: RangeTo<usize>) -> &[u8] {
let inner = &self.0;
inner.0.index(_index)
}
}
impl Index<RangeFrom<usize>> for $newtype {
type Output = [u8];
fn index(&self, _index: RangeFrom<usize>) -> &[u8] {
let inner = &self.0;
inner.0.index(_index)
}
}
impl Index<RangeFull> for $newtype {
type Output = [u8];
fn index(&self, _index: RangeFull) -> &[u8] {
let inner = &self.0;
inner.0.index(_index)
}
})
}
implement_index_traits! {Hash}
implement_index_traits! {PublicKey}
implement_index_traits! {SecretKey}
implement_index_traits! {Seed}
implement_index_traits! {Signature}
impl Default for Hash {
fn default() -> Hash {
Hash::zero()
}
}
#[cfg(test)]
mod tests {
use super::{hash, gen_keypair, Hash, PublicKey, SecretKey, Seed, Signature, HashStream,
SignStream};
use super::HexValue;
use serde_json;
#[test]
fn test_hash() {
let h = hash(&[]);
let h1 = Hash::from_hex(h.to_hex()).unwrap();
assert_eq!(h1, h);
let h = Hash::zero();
assert_eq!(*h.as_ref(), [0; 32]);
}
#[test]
fn test_keys() {
let (p, s) = gen_keypair();
let p1 = PublicKey::from_hex(p.to_hex()).unwrap();
let s1 = SecretKey::from_hex(s.to_hex()).unwrap();
assert_eq!(p1, p);
assert_eq!(s1, s);
}
#[test]
fn test_ser_deser() {
let h = Hash::new([207; 32]);
let json_h = serde_json::to_string(&h).unwrap();
let h1 = serde_json::from_str(&json_h).unwrap();
assert_eq!(h, h1);
let h = PublicKey::new([208; 32]);
let json_h = serde_json::to_string(&h).unwrap();
let h1 = serde_json::from_str(&json_h).unwrap();
assert_eq!(h, h1);
let h = Signature::new([209; 64]);
let json_h = serde_json::to_string(&h).unwrap();
let h1 = serde_json::from_str(&json_h).unwrap();
assert_eq!(h, h1);
let h = Seed::new([210; 32]);
let json_h = serde_json::to_string(&h).unwrap();
let h1 = serde_json::from_str(&json_h).unwrap();
assert_eq!(h, h1);
let h = SecretKey::new([211; 64]);
let json_h = serde_json::to_string(&h).unwrap();
let h1 = serde_json::from_str(&json_h).unwrap();
assert_eq!(h, h1);
}
#[test]
fn test_debug_format() {
let hash = Hash::new([1; 32]);
assert_eq!(format!("{:?}", &hash), "Hash(01010101)");
let pk = PublicKey::new([15; 32]);
assert_eq!(format!("{:?}", &pk), "PublicKey(0F0F0F0F)");
let sk = SecretKey::new([8; 64]);
assert_eq!(format!("{:?}", &sk), "SecretKey(08080808...)");
let signature = Signature::new([10; 64]);
assert_eq!(format!("{:?}", &signature), "Signature(0A0A0A0A)");
let seed = Seed::new([4; 32]);
assert_eq!(format!("{:?}", &seed), "Seed(04040404...)");
let hash = Hash::new([128; 32]);
assert_eq!(format!("{:?}", &hash), "Hash(80808080)");
let sk = SecretKey::new([255; 64]);
assert_eq!(format!("{:?}", &sk), "SecretKey(FFFFFFFF...)");
}
#[test]
fn test_range_sodium() {
let h = hash(&[]);
let sub_range = &h[10..20];
assert_eq!(
&[244u8, 200, 153, 111, 185, 36, 39, 174, 65, 228],
sub_range
);
}
#[test]
fn test_hash_streaming_zero() {
let h1 = hash(&[]);
let state = HashStream::new();
let h2 = state.update(&[]).hash();
assert_eq!(h1, h2);
}
#[test]
fn test_hash_streaming_chunks() {
let data: [u8; 10] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
let h1 = hash(&data);
let state = HashStream::new();
let h2 = state.update(&data[..5]).update(&data[5..]).hash();
assert_eq!(h1, h2);
}
#[test]
fn test_sign_streaming_zero() {
let (pk, sk) = gen_keypair();
let mut creation_stream = SignStream::new().update(&[]);
let sig = creation_stream.sign(&sk);
let mut verified_stream = SignStream::new().update(&[]);
assert!(verified_stream.verify(&sig, &pk));
}
#[test]
fn test_sign_streaming_chunks() {
let data: [u8; 10] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
let (pk, sk) = gen_keypair();
let mut creation_stream = SignStream::new().update(&data[..5]).update(&data[5..]);
let sig = creation_stream.sign(&sk);
let mut verified_stream = SignStream::new().update(&data[..5]).update(&data[5..]);
assert!(verified_stream.verify(&sig, &pk));
}
}