-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.rs
1673 lines (1548 loc) · 59.1 KB
/
mod.rs
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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! A rust translation of the TweetNaCl library. It is mostly a
//! direct translation, but in places I tried to make the API more
//! rustic. It has three major features, of which you are likely
//! to use only one.
//!
//! 1. **Authenticated symmetric-key encryption** This is not so
//! very often useful, but on the off chance you have a shared
//! secret you could use it.
//!
//! 2. **SHA512 hasing** This again could be handy, but is not
//! necesarily what you want most of the time. And to be
//! honest, you probably don't want my crude translation to
//! rust of the pure C TweetNaCl implementation.
//!
//! 3. **Public-key encryption with authentication** This is what
//! you want. It allows you to send messages to a remote
//! party, and ensure they aren't modified in transit. The
//! remote party can verify that you sent the message (or
//! someone else did who had access to either your private key
//! or *their* private key), but they can't prove that you sent
//! the message. It's a nice set of functionality, implemented
//! in the functions `box_up` (which encrypts) and `box_open`
//! (which decrypts and authenticates).
//!
//! # Examples
//!
//! Here is a simple example of encrypting a message and
//! decrypting it. The one thing that it doesn't demonstrate is
//! that the ciphertext is padded with 16 zero bytes, which you
//! probably don't want to bother sending over the network.
//!
//! ```
//! # use std::vec;
//! # use onionsalt::crypto;
//! #
//! // of course, in practice, don't use unwrap: handle the error!
//! let mykey = crypto::box_keypair();
//! let thykey = crypto::box_keypair();
//!
//! let plaintext = b"Friendly message.";
//!
//! let mut padded_plaintext: vec::Vec<u8> = vec::Vec::with_capacity(32+plaintext.len());
//! for _ in 0..32 { padded_plaintext.push(0); }
//! for i in 0..plaintext.len() { padded_plaintext.push(plaintext[i]); }
//!
//! let mut ciphertext: vec::Vec<u8> = vec::Vec::with_capacity(padded_plaintext.len());
//! for _ in 0..padded_plaintext.len() { ciphertext.push(0); }
//!
//! let nonce = crypto::random_nonce();
//!
//! // Here we encreypt the message. Keep in mind when sending it
//! // that you should strip the 16 zeros off the beginning!
//!
//! crypto::box_up(&mut ciphertext, &padded_plaintext,
//! &nonce, &thykey.public, &mykey.secret);
//!
//! let mut decrypted: vec::Vec<u8> = vec::Vec::with_capacity(padded_plaintext.len());
//! for _ in 0..ciphertext.len() { decrypted.push(0); }
//!
//! // Use box_open to decrypt the message. You REALLY don't want
//! // to unwrap (or ignore) the output of box_open, since this is
//! // how you know that the message was authenticated.
//!
//! crypto::box_open(&mut decrypted, &ciphertext,
//! &nonce, &mykey.public, &thykey.secret).unwrap();
//!
//! // Note that decrypted (like padded_plaintext) has 32 bytes of
//! // zeros padded at the beginning.
//! for i in 0..plaintext.len() {
//! assert!(plaintext[i] == decrypted[i+32]);
//! }
//! ```
// #![deny(warnings)]
#[cfg(test)]
extern crate quickcheck;
extern crate serde;
use std::num::Wrapping;
use std::fmt::{Formatter, Error, Display};
fn unwrap<T>(x: Wrapping<T>) -> T {
let Wrapping(x) = x;
x
}
static _0: [u8; 16] = [0; 16];
static _9: [u8; 32] = [9; 32];
type GF = [i64; 16];
static GF0: GF = [0; 16];
// static GF1: GF = [1; 16];
static _121665: GF = [0xDB41,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
// static D: GF = [0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070,
// 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203];
// static D2: GF = [0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0,
// 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406];
// static X: GF = [0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c,
// 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169];
// static Y: GF = [0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666,
// 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666];
// static I: GF = [0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43,
// 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83];
fn l32(x: Wrapping<u32>, c: usize) -> Wrapping<u32> {
(x << c) | ((x&Wrapping(0xffffffff)) >> (32 - c))
}
fn ld32(x: &[u8; 4]) -> Wrapping<u32> {
let mut u= Wrapping(x[3] as u32);
u = (u<<8)|Wrapping(x[2] as u32);
u = (u<<8)|Wrapping(x[1] as u32);
(u<<8)|Wrapping(x[0] as u32)
}
fn st32(x: &mut[u8; 4], mut u: Wrapping<u32>) {
for i in 0..4 {
x[i] = unwrap(u) as u8;
u = u >> 8;
}
}
fn verify_16(x: &[u8; 16], y: &[u8; 16]) -> Result<(), NaClError> {
let mut d: Wrapping<u32> = Wrapping(0);
for i in 0..16 {
d = d | Wrapping((x[i]^y[i]) as u32);
}
if unwrap(Wrapping(1) & ((d - Wrapping(1)) >> 8)) as i32 - 1 != 0 {
Err(NaClError::AuthFailed)
} else {
Ok(())
}
}
fn core(inp: &[u8; 16], k: &[u8; 32], c: &[u8; 16])
-> ([Wrapping<u32>; 16], [Wrapping<u32>; 16]) {
let mut x: [Wrapping<u32>; 16] = [Wrapping(0); 16];
for i in 0..4 {
x[5*i] = ld32(array_ref![c, 4*i, 4]);
x[1+i] = ld32(array_ref![k, 4*i, 4]);
x[6+i] = ld32(array_ref![inp, 4*i, 4]);
x[11+i] = ld32(array_ref![k, 16+4*i, 4]);
}
let mut y: [Wrapping<u32>; 16] = [Wrapping(0); 16];
for i in 0..16 {
y[i] = x[i];
}
let mut w: [Wrapping<u32>; 16] = [Wrapping(0); 16];
let mut t: [Wrapping<u32>; 4] = [Wrapping(0); 4];
for _ in 0..20 {
for j in 0..4 {
for m in 0..4 {
t[m] = x[(5*j+4*m)%16];
}
t[1] = t[1] ^ l32(t[0]+t[3], 7);
t[2] = t[2] ^ l32(t[1]+t[0], 9);
t[3] = t[3] ^ l32(t[2]+t[1],13);
t[0] = t[0] ^ l32(t[3]+t[2],18);
for m in 0..4 {
w[4*j+(j+m)%4] = t[m];
}
}
for m in 0..16 {
x[m] = w[m];
}
}
(x,y)
}
fn core_salsa20(inp: &[u8; 16], k: &[u8; 32], c: &[u8; 16]) -> [u8; 64] {
let (x,y) = core(inp,k,c);
let mut out: [u8; 64] = [0; 64];
for i in 0..16 {
st32(array_mut_ref!(out, 4*i, 4),x[i] + y[i]);
}
out
}
fn core_hsalsa20(n: &[u8; 16], k: &[u8; 32], c: &[u8; 16]) -> [u8; 32] {
let (mut x,y) = core(n,k,c);
let mut out: [u8; 32] = [0; 32];
for i in 0..16 {
x[i] = x[i] + y[i];
}
for i in 0..4 {
x[5*i] = x[5*i] - ld32(array_ref![c, 4*i, 4]);
x[6+i] = x[6+i] - ld32(array_ref!(n, 4*i, 4));
}
for i in 0..4 {
st32(array_mut_ref!(out, 4*i, 4),x[5*i]);
st32(array_mut_ref!(out, 16+4*i, 4),x[6+i]);
}
out
}
static SIGMA: &'static [u8; 16] = b"expand 32-byte k";
/// Securely creates a byte.
pub fn random_byte() -> u8 {
RANDOM.with(|r| { r.borrow_mut().byte() })
}
/// Securely creates a u32.
pub fn random_u32() -> u32 {
RANDOM.with(|r| { r.borrow_mut().u32() })
}
/// Securely creates a u64.
pub fn random_u64() -> u64 {
RANDOM.with(|r| { r.borrow_mut().u64() })
}
/// Securely creates 32 random bytes.
pub fn random_24() -> [u8;24] {
RANDOM.with(|r| { r.borrow_mut().random_24() })
}
/// Securely creates 32 random bytes.
pub fn random_32() -> [u8;32] {
RANDOM.with(|r| { r.borrow_mut().random_32() })
}
thread_local!(static RANDOM: std::cell::RefCell<Salsa20Random>
= std::cell::RefCell::new(Salsa20Random::new()));
struct Salsa20Random {
z: [u8;16],
k: [u8;32],
bytes: [u8;64],
bytes_left: usize,
}
impl Salsa20Random {
fn refill(&mut self) {
self.bytes = core_salsa20(&self.z,&self.k,SIGMA);
self.bytes_left = 64;
// now we increment the counter, which is in the last 8 bytes
// of z.
let mut u: u64 = 1;
for i in 8..16 {
u += self.z[i] as u64;
self.z[i] = u as u8;
u >>= 8;
}
}
fn byte(&mut self) -> u8 {
if self.bytes_left == 0 { self.refill(); }
self.bytes_left -= 1;
self.bytes[63 - self.bytes_left]
}
fn u32(&mut self) -> u32 {
self.byte() as u32 + ((self.byte() as u32) << 8) + ((self.byte() as u32) << 16) + ((self.byte() as u32) << 24)
}
fn u64(&mut self) -> u64 {
self.byte() as u64 + ((self.byte() as u64) << 8) + ((self.byte() as u64) << 16) + ((self.byte() as u64) << 24)
+ ((self.byte() as u64) << 32) + ((self.byte() as u64) << 40) + ((self.byte() as u64) << 48) + ((self.byte() as u64) << 56)
}
fn random_32(&mut self) -> [u8;32] {
// the following is potentially wasteful, but probably not
// much of a problem.
if self.bytes_left < 32 { self.refill(); }
self.bytes_left -= 32;
*array_ref![self.bytes, self.bytes_left, 32]
}
fn random_24(&mut self) -> [u8;24] {
// the following is potentially wasteful, but probably not
// much of a problem.
if self.bytes_left < 24 { self.refill(); }
self.bytes_left -= 24;
*array_ref![self.bytes, self.bytes_left, 24]
}
fn new() -> Self {
let mut rng = OsRng::new().unwrap();
let mut k = [0; 32];
rng.fill_bytes(&mut k);
let mut z = [0; 16];
rng.fill_bytes(&mut z);
Salsa20Random {
z: z,
k: k,
bytes_left: 0,
bytes: [0;64],
}
}
#[cfg(test)]
fn from_nonce_and_key(n: &[u8;8], k: &[u8;32]) -> Self {
let mut z: [u8; 16] = [0; 16];
for i in 0..8 {
z[i] = n[i];
}
Salsa20Random {
z: z,
k: *k,
bytes_left: 0,
bytes: [0;64],
}
}
}
#[cfg(test)]
const RANDOM_TEST_NUM: usize = 64;
#[test]
fn random_matches_stream() {
let k = random_32();
let a = random_32();
let n = *array_ref![&a, 0, 8];
println!("Initializing random");
let mut r = Salsa20Random::from_nonce_and_key(&n, &k);
let zeros = [0u8;RANDOM_TEST_NUM];
let mut bytes = [0u8;RANDOM_TEST_NUM];
println!("Salsa stream");
stream_salsa20_xor(&mut bytes, &zeros, RANDOM_TEST_NUM as u64, &n, &k);
let mut random_bytes = [0u8;RANDOM_TEST_NUM];
for i in 0 .. RANDOM_TEST_NUM {
random_bytes[i] = r.byte();
}
for i in 0 .. RANDOM_TEST_NUM {
println!("{} vs {}", random_bytes[i], bytes[i]);
}
for i in 0 .. RANDOM_TEST_NUM {
println!("Checking byte {}", i);
assert_eq!(bytes[i], random_bytes[i]);
}
}
fn stream_salsa20_xor(c: &mut[u8], mut m: &[u8], mut b: u64,
n: &[u8; 8], k: &[u8; 32]) {
assert!(b != 0);
let mut z = [0u8; 16];
for i in 0..8 {
z[i] = n[i];
}
let mut c_offset: usize = 0;
while b >= 64 {
let x = core_salsa20(&z,k,SIGMA);
for i in 0..64 {
c[c_offset + i] = if i < m.len() { m[i] ^ x[i] } else { x[i] };
}
let mut u: u64 = 1;
for i in 8..16 {
u += z[i] as u64;
z[i] = u as u8;
u >>= 8;
}
b -= 64;
c_offset += 64;
m = &m[64..];
}
if b != 0 {
let x = core_salsa20(&z,k,SIGMA);
for i in 0..b as usize {
c[c_offset + i] = if i < m.len() { m[i] ^ x[i] } else { x[i] };
}
}
}
fn stream_salsa20(c: &mut[u8], d: u64, n: &[u8; 8], k: &[u8; 32]) {
stream_salsa20_xor(c,&[],d,n,k)
}
// stream_32 is a modified version of crypto_stream, which
// always has a fixed length of 32, and returns its output. We
// don't need an actual crypto_stream, since it is only used once
// in tweetnacl.
fn stream_32(n: &Nonce, k: &[u8; 32]) -> [u8;32] {
let s = core_hsalsa20(array_ref![n.0, 0, 16], k, SIGMA);
let mut c: [u8; 32] = [0; 32];
stream_salsa20(&mut c,32,array_ref![n.0, 16, 8],&s);
c
}
fn stream_xor(c: &mut[u8], m: &[u8], d: u64, n: &Nonce, k: &[u8; 32]) {
let s = core_hsalsa20(array_ref![n.0, 0, 16], k, SIGMA);
stream_salsa20_xor(c,m,d,array_ref![n.0, 16, 8],&s)
}
fn add1305(h: &mut[u32], c: &[u32]) {
let mut u: u32 = 0;
for j in 0..17 {
u += h[j] + c[j];
h[j] = u & 255;
u >>= 8;
}
}
static MINUSP: &'static [u32; 17] = &[5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 252];
use std;
/// The error return type. You can get errors for only one of three reasons:
///
/// 1. You passed in slices that were the wrong sizes. This is
/// your bug, and we would be justified in panicking for this.
///
/// 2. You called an "open" function, and the message failed to
/// authenticate. This is only a bug if you thought the
/// message should be valid. But you need to handle this,
/// since presumable some bad person could try to corrupt your
/// data.
///
/// 3. If you are generating random data (either generating keys
/// or a nonce), you could in principle encounter an IO error.
/// This should be unusual, but could happen.
// We derive `Debug` because all types should probably derive
// `Debug`. This gives us a reasonable human readable description
// of the `NaClError` values.
#[derive(Debug)]
pub enum NaClError {
AuthFailed,
WrongKey,
IOError(std::io::Error),
RecvError(std::sync::mpsc::RecvError),
}
impl std::convert::From<std::io::Error> for NaClError {
fn from(e: std::io::Error) -> NaClError {
NaClError::IOError(e)
}
}
impl std::convert::From<std::sync::mpsc::RecvError> for NaClError {
fn from(e: std::sync::mpsc::RecvError) -> NaClError {
NaClError::RecvError(e)
}
}
impl<'a> std::convert::From<&'a str> for NaClError {
fn from(e: &str) -> NaClError {
NaClError::IOError(std::io::Error::new(std::io::ErrorKind::Other, e))
}
}
/// A public key.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PublicKey(pub [u8; 32]);
impl Display for PublicKey {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
let mut s = String::new();
s = s + &format!("{:02x}{:02x}{:02x}{:02x}", self.0[0], self.0[1], self.0[2], self.0[3]);
s = s + &format!("{:02x}{:02x}{:02x}{:02x}", self.0[4], self.0[5], self.0[6], self.0[7]);
s = s + &format!("{:02x}{:02x}{:02x}{:02x}", self.0[8], self.0[9], self.0[10], self.0[11]);
s = s + &format!("{:02x}{:02x}{:02x}{:02x}", self.0[12], self.0[13], self.0[14], self.0[15]);
s = s + &format!("{:02x}{:02x}{:02x}{:02x}", self.0[16], self.0[17], self.0[18], self.0[19]);
s = s + &format!("{:02x}{:02x}{:02x}{:02x}", self.0[20], self.0[21], self.0[22], self.0[23]);
s = s + &format!("{:02x}{:02x}{:02x}{:02x}", self.0[24], self.0[25], self.0[26], self.0[27]);
s = s + &format!("{:02x}{:02x}{:02x}{:02x}", self.0[28], self.0[29], self.0[30], self.0[31]);
f.write_str(&s)
}
}
mod hex;
impl serde::de::Deserialize for PublicKey {
fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
where D: serde::de::Deserializer {
use serde::de::{Deserialize,Error};
match String::deserialize(deserializer) {
Err(e) => Err(e),
Ok(ref bb) => {
let bb = bb.as_bytes();
if bb.len() == 64 {
match hex::bytes_32(array_ref![bb,0,64]) {
Some(b32) => Ok(PublicKey(b32)),
None => Err(D::Error::syntax("invalid hex for PublicKey")),
}
} else {
Err(D::Error::syntax("wrong size for PublicKey"))
}
},
}
}
}
impl serde::ser::Serialize for PublicKey {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: serde::Serializer {
serializer.visit_str(&format!("{}", self))
}
}
#[cfg(test)]
mod test {
use std;
use serde_json;
use tempfile;
use std::io::Seek;
#[test]
fn serialize_publickey() {
let k = super::box_keypair().public;
let mut f = tempfile::TempFile::new().unwrap();
serde_json::to_writer(&mut f, &k).unwrap();
f.seek(std::io::SeekFrom::Start(0)).unwrap();
let kk: super::PublicKey = serde_json::from_reader(&mut f).unwrap();
println!("found key {}", kk);
assert_eq!(kk, k);
}
#[test]
fn serialize_secretkey() {
let k = super::box_keypair().secret;
let mut f = tempfile::TempFile::new().unwrap();
serde_json::to_writer(&mut f, &k).unwrap();
f.seek(std::io::SeekFrom::Start(0)).unwrap();
let kk: super::SecretKey = serde_json::from_reader(&mut f).unwrap();
println!("found key {}", kk);
assert_eq!(kk, k);
}
#[test]
fn serialize_nonce() {
let k = super::random_nonce();
let mut f = tempfile::TempFile::new().unwrap();
serde_json::to_writer(&mut f, &k).unwrap();
f.seek(std::io::SeekFrom::Start(0)).unwrap();
let kk: super::Nonce = serde_json::from_reader(&mut f).unwrap();
println!("found key {}", kk);
assert_eq!(kk, k);
}
}
/// A secret key.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SecretKey(pub [u8; 32]);
impl Display for SecretKey {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
PublicKey(self.0).fmt(f)
}
}
impl serde::de::Deserialize for SecretKey {
fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
where D: serde::de::Deserializer {
use serde::de::{Deserialize,Error};
match String::deserialize(deserializer) {
Err(e) => Err(e),
Ok(ref bb) => {
let bb = bb.as_bytes();
if bb.len() == 64 {
match hex::bytes_32(array_ref![bb,0,64]) {
Some(b32) => Ok(SecretKey(b32)),
None => Err(D::Error::syntax("invalid hex for SecretKey")),
}
} else {
Err(D::Error::syntax("wrong size for SecretKey"))
}
},
}
}
}
impl serde::ser::Serialize for SecretKey {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: serde::Serializer {
serializer.visit_str(&format!("{}", self))
}
}
/// A nonce. You should never reuse a nonce for two different
/// messages between the same set of keys.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Nonce(pub [u8; 24]);
impl Display for Nonce {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
let mut s = String::new();
s = s + &format!("{:02x}{:02x}{:02x}{:02x}", self.0[0], self.0[1], self.0[2], self.0[3]);
s = s + &format!("{:02x}{:02x}{:02x}{:02x}", self.0[4], self.0[5], self.0[6], self.0[7]);
s = s + &format!("{:02x}{:02x}{:02x}{:02x}", self.0[8], self.0[9], self.0[10], self.0[11]);
s = s + &format!("{:02x}{:02x}{:02x}{:02x}", self.0[12], self.0[13], self.0[14], self.0[15]);
s = s + &format!("{:02x}{:02x}{:02x}{:02x}", self.0[16], self.0[17], self.0[18], self.0[19]);
s = s + &format!("{:02x}{:02x}{:02x}{:02x}", self.0[20], self.0[21], self.0[22], self.0[23]);
f.write_str(&s)
}
}
impl serde::de::Deserialize for Nonce {
fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
where D: serde::de::Deserializer {
use serde::de::{Deserialize,Error};
match String::deserialize(deserializer) {
Err(e) => Err(e),
Ok(ref bb) => {
let bb = bb.as_bytes();
if bb.len() == 48 {
match hex::bytes_24(array_ref![bb,0,48]) {
Some(b) => Ok(Nonce(b)),
None => Err(D::Error::syntax("invalid hex for Nonce")),
}
} else {
Err(D::Error::syntax("wrong size for Nonce"))
}
},
}
}
}
impl serde::ser::Serialize for Nonce {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: serde::Serializer {
serializer.visit_str(&format!("{}", self))
}
}
fn onetimeauth(mut m: &[u8], k: &[u8;32]) -> [u8; 16] {
let mut n = m.len();
let x: &mut[u32; 17] = &mut [0; 17];
let r: &mut[u32; 17] = &mut [0; 17];
let h: &mut[u32; 17] = &mut [0; 17];
for j in 0..16 {
r[j]=k[j] as u32;
}
r[3]&=15;
r[4]&=252;
r[7]&=15;
r[8]&=252;
r[11]&=15;
r[12]&=252;
r[15]&=15;
let mut c: &mut[u32; 17] = &mut [0; 17];
let mut g: &mut[u32; 17] = &mut [0; 17];
while n > 0 {
for j in 0..17 {
c[j] = 0;
}
let nor16 = if n < 16 { n } else { 16 } as usize;
for j in 0..nor16 {
c[j] = m[j] as u32;
}
c[nor16] = 1;
m = &m[nor16..];
n -= nor16;
add1305(h,c);
for i in 0..17 {
x[i] = 0;
for j in 0..17 {
x[i] += h[j] * (if j <= i { r[i - j] } else { 320 * r[i + 17 - j]});
}
}
for i in 0..17 {
h[i] = x[i];
}
let mut u: u32 = 0;
for j in 0..16 {
u += h[j];
h[j] = u & 255;
u >>= 8;
}
u += h[16];
h[16] = u & 3;
u = 5 * (u >> 2);
for j in 0..16 {
u += h[j];
h[j] = u & 255;
u >>= 8;
}
u += h[16];
h[16] = u;
}
for j in 0..17 {
g[j] = h[j];
}
add1305(h,MINUSP);
let s: u32 = (-((h[16] >> 7) as i32)) as u32;
for j in 0..17 {
h[j] ^= s & (g[j] ^ h[j]);
}
for j in 0..16 {
c[j] = k[j + 16] as u32;
}
c[16] = 0;
add1305(h,c);
let mut out: [u8; 16] = [0; 16];
for j in 0..16 {
out[j] = h[j] as u8;
}
out
}
fn onetimeauth_verify(h: &[u8; 16], m: &[u8], k: &[u8;32])
-> Result<(), NaClError> {
let x = onetimeauth(m, k);
verify_16(h,&x)
}
/// Use symmetric encryption to encrypt a message.
pub fn secretbox(c: &mut[u8], m: &[u8], n: &Nonce, k: &[u8; 32]) {
let d = c.len() as u64;
assert_eq!(d, m.len() as u64);
assert!(d >= 32);
stream_xor(c,m,d,n,k);
let h = onetimeauth(&c[32..], array_ref![c,0,32]);
for i in 0..16 {
c[i] = 0;
}
// The following loop is additional overhead beyond what the C
// version of the code does, which results from my choice to
// use a return array rather than a mut slice argument for
// "core" above.
for i in 0..16 {
c[16+i] = h[i];
}
}
/// Decrypt a message encrypted with `secretbox`.
pub fn secretbox_open(m: &mut[u8], c: &[u8], n: &Nonce, k: &[u8; 32])
-> Result<(), NaClError> {
let d = c.len() as u64;
assert_eq!(m.len() as u64, d);
assert!(d >= 32);
let x = stream_32(n,k);
try!(onetimeauth_verify(array_ref!(c, 16, 16), &c[32..], &x));
stream_xor(m,c,d,n,k);
for i in 0..32 {
m[i] = 0;
}
Ok(())
}
#[test]
fn secretbox_works() {
use std::vec;
let plaintext: &[u8] = b"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0This is only a test.";
let secretkey: &[u8; 32] = b"This is my secret key. It is me.";
let mut ciphertext: vec::Vec<u8> = vec![];
for _ in 0..plaintext.len() {
ciphertext.push(0);
}
let nonce = Nonce([0; 24]);
secretbox(&mut ciphertext, plaintext, &nonce, secretkey);
// There has got to be a better way to allocate an array of
// zeros with dynamically determined type.
let mut decrypted: vec::Vec<u8> = vec::Vec::with_capacity(plaintext.len());
for _ in 0..plaintext.len() {
decrypted.push(0);
}
secretbox_open(&mut decrypted, &ciphertext, &nonce, secretkey).unwrap();
for i in 0..decrypted.len() {
assert!(decrypted[i] == plaintext[i])
}
}
/// Use symmetric encryption to encrypt a message, with only the first
/// `nauth` bytes plaintext authenticated.
fn funnybox(c: &mut[u8], m: &[u8], nauth: usize, n: &Nonce, k: &[u8; 32]) {
let d = c.len() as u64;
assert_eq!(d, m.len() as u64);
assert!(nauth <= d as usize-32);
assert!(d >= 32);
stream_xor(c,m,d,n,k);
let h = onetimeauth(&c[32..32+nauth], array_ref![c,0,32]);
for i in 0..16 {
c[i] = 0;
}
// The following loop is additional overhead beyond what the C
// version of the code does, which results from my choice to
// use a return array rather than a mut slice argument for
// "core" above.
for i in 0..16 {
c[16+i] = h[i];
}
}
/// Decrypt a message encrypted with `funnybox`, only authenticating
/// the first `nauth` bytes.
pub fn funnybox_open(m: &mut[u8], c: &[u8], nauth: usize, n: &Nonce, k: &[u8; 32])
-> Result<(), NaClError> {
let d = c.len() as u64;
assert_eq!(m.len() as u64, d);
assert!(nauth <= d as usize - 32);
assert!(d >= 32);
let x = stream_32(n,k);
try!(onetimeauth_verify(array_ref!(c, 16, 16), &c[32..32+nauth], &x));
stream_xor(m,c,d,n,k);
for i in 0..32 {
m[i] = 0;
}
Ok(())
}
#[test]
fn funnybox_works() {
use std::vec;
let plaintext: &[u8] = b"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0This is only a test.";
let nauth = "This is only".len();
let secretkey: &[u8; 32] = b"This is my secret key. It is me.";
let mut ciphertext: vec::Vec<u8> = vec![];
for _ in 0..plaintext.len() {
ciphertext.push(0);
}
let nonce = Nonce([0; 24]);
funnybox(&mut ciphertext, plaintext, nauth, &nonce, secretkey);
// There has got to be a better way to allocate an array of
// zeros with dynamically determined type.
let mut decrypted: vec::Vec<u8> = vec::Vec::with_capacity(plaintext.len());
for _ in 0..plaintext.len() {
decrypted.push(0);
}
funnybox_open(&mut decrypted, &ciphertext, nauth, &nonce, secretkey).unwrap();
for i in 0..decrypted.len() {
assert!(decrypted[i] == plaintext[i])
}
}
fn car25519(o: &mut GF) {
for i in 0..16 {
o[i] += 1<<16;
let c: i64 = o[i]>>16;
let iis15 = if i == 15 {1} else {0};
let ilt15 = if i < 15 {1} else {0};
o[(i+1)*ilt15] += c-1+37*(c-1)*iis15;
o[i] -= c<<16;
}
}
fn sel25519(p: &mut GF, q: &mut GF, b: i64) {
let c = !(b-1);
for i in 0..16 {
let t= c&(p[i]^q[i]);
p[i]^=t;
q[i]^=t;
}
}
fn pack25519(o: &mut[u8], n: &GF) {
let mut t = *n;
car25519(&mut t);
car25519(&mut t);
car25519(&mut t);
let mut m = [0; 16];
for _ in 0..1 {
m[0]=t[0]-0xffed;
for i in 1..15 {
m[i]=t[i]-0xffff-((m[i-1]>>16)&1);
m[i-1]&=0xffff;
}
m[15]=t[15]-0x7fff-((m[14]>>16)&1);
let b=(m[15]>>16)&1;
m[14]&=0xffff;
sel25519(&mut t,&mut m,1-b);
}
for i in 0..16 {
o[2*i]= (t[i]&0xff) as u8;
o[2*i+1]= (t[i]>>8) as u8;
}
}
// fn neq25519(a: &GF, b: &GF) -> Result<(), NaClError> {
// let mut c: [u8; 32] = [0; 32];
// let mut d: [u8; 32] = [0; 32];
// pack25519(&mut c,a);
// pack25519(&mut d,b);
// verify_32(&c,&d)
// }
// fn par25519(a: &GF) -> u8 {
// let mut d: [u8; 32] = [0; 32];
// pack25519(&mut d,a);
// d[0]&1
// }
fn unpack25519(n: &[u8]) -> GF {
let mut o = GF0;
for i in 0..16 {
o[i]=n[2*i] as i64 + ((n[2*i+1] as i64) << 8);
}
o[15]&=0x7fff;
o
}
#[allow(non_snake_case)]
fn A(a: &GF, b: &GF) -> GF {
let mut out: GF = *a;
for i in 0..16 {
out[i] += b[i];
}
out
}
#[allow(non_snake_case)]
fn Z(a: &GF, b: &GF) -> GF {
let mut out: GF = *a;
for i in 0..16 {
out[i] -= b[i];
}
out
}
#[allow(non_snake_case)]
fn M(a: &GF, b: &GF) -> GF {
let mut o: GF = *a;
let mut t: [i64; 31] = [0; 31];
for i in 0..16 {
for j in 0..16 {
t[i+j] += a[i]*b[j];
}
}
for i in 0..15 {
t[i]+=38*t[i+16];
}
for i in 0..16 {
o[i]=t[i];
}
car25519(&mut o);
car25519(&mut o);
o
}
#[allow(non_snake_case)]
fn S(a: &GF) -> GF {
M(a,a)
}
fn inv25519(i: &GF) -> GF {
let mut c = *i;
for a in (0..254).rev() {
c = S(&c);
if a!=2 && a!=4 {
c = M(&c,i)
}
}
c
}
// fn pow2523(i: &GF) -> GF {
// let mut c = *i;
// for a in (0..251).rev() {
// c = S(&c);
// if a != 1 {
// c = M(&c, i);
// }
// }
// c
// }
fn scalarmult(q: &mut[u8], n: &[u8], p: &[u8]) {
let mut z: [u8; 32] = [0; 32];
for i in 0..31 {
z[i] = n[i];
}
z[31]=(n[31]&127)|64;
z[0]&=248;
let mut x: [GF; 5] = [unpack25519(p), [0;16], [0;16], [0;16], [0;16]];
let mut b = x[0];
let mut d = GF0;
let mut a = GF0;
let mut c = GF0;
a[0]=1;
d[0]=1;
for i in (0..255).rev() {
let r: i64 = ((z[i>>3]>>(i&7))&1) as i64;
sel25519(&mut a, &mut b,r);
sel25519(&mut c, &mut d,r);
let mut e = A(&a,&c);
a = Z(&a,&c);
c = A(&b,&d);
b = Z(&b,&d);
d = S(&e);
let f = S(&a);
a = M(&c,&a);
c = M(&b,&e);
e = A(&a,&c);
a = Z(&a,&c);
b = S(&a);
c = Z(&d,&f);
a = M(&c,&_121665);
a = A(&a,&d);
c = M(&c,&a);
a = M(&d,&f);
d = M(&b,&x[0]);
b = S(&e);
sel25519(&mut a, &mut b,r);
sel25519(&mut c, &mut d,r);
}
x[1] = a;
x[2] = c;
x[3] = b;
x[4] = d;
x[2] = inv25519(&x[2]);
x[1] = M(&x[1],&x[2]);
pack25519(q,&x[1]);
}
fn scalarmult_base(q: &mut[u8], n: &[u8]) {
scalarmult(q,n,&_9)
}
use rand::{OsRng,Rng};
/// A pair with public and secret keys.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct KeyPair {
pub public: PublicKey,
pub secret: SecretKey,
}
/// Generate a random public/secret key pair. This is the *only* way
/// you should generate keys. Although of course you can store keys
/// to disk and then read them back again. But they always start with