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
//! `ed25519`, a signature scheme specified in
//! [Ed25519](http://ed25519.cr.yp.to/). This function is conjectured to meet the
//! standard notion of unforgeability for a public-key signature scheme under
//! chosen-message attacks.

use ffi;
use libc::c_ulonglong;
#[cfg(not(feature = "std"))]
use prelude::*;
use std::fmt;
use std::mem;

/// Number of bytes in a `Seed`.
pub const SEEDBYTES: usize = ffi::crypto_sign_ed25519_SEEDBYTES as usize;

/// Number of bytes in a `SecretKey`.
pub const SECRETKEYBYTES: usize = ffi::crypto_sign_ed25519_SECRETKEYBYTES as usize;

/// Number of bytes in a `PublicKey`.
pub const PUBLICKEYBYTES: usize = ffi::crypto_sign_ed25519_PUBLICKEYBYTES as usize;

/// Number of bytes in a `Signature`.
pub const SIGNATUREBYTES: usize = ffi::crypto_sign_ed25519_BYTES as usize;

new_type! {
    /// `Seed` that can be used for keypair generation
    ///
    /// The `Seed` is used by `keypair_from_seed()` to generate
    /// a secret and public signature key.
    ///
    /// When a `Seed` goes out of scope its contents
    /// will be zeroed out
    secret Seed(SEEDBYTES);
}

new_type! {
    /// `SecretKey` for signatures
    ///
    /// When a `SecretKey` goes out of scope its contents
    /// will be zeroed out
    secret SecretKey(SECRETKEYBYTES);
}

impl SecretKey {
    /// `public_key()` computes the corresponding public key for a given secret key
    pub fn public_key(&self) -> PublicKey {
        let mut pk = PublicKey([0u8; PUBLICKEYBYTES]);
        unsafe {
            ffi::crypto_sign_ed25519_sk_to_pk(pk.0.as_mut_ptr(), self.0.as_ptr());
        }
        pk
    }
}

new_type! {
    /// `PublicKey` for signatures
    public PublicKey(PUBLICKEYBYTES);
}

new_type! {
    /// Detached signature
    public Signature(SIGNATUREBYTES);
}

/// `gen_keypair()` randomly generates a secret key and a corresponding public
/// key.
///
/// THREAD SAFETY: `gen_keypair()` is thread-safe provided that you have
/// called `sodiumoxide::init()` once before using any other function
/// from sodiumoxide.
pub fn gen_keypair() -> (PublicKey, SecretKey) {
    let mut pk = PublicKey([0u8; PUBLICKEYBYTES]);
    let mut sk = SecretKey([0u8; SECRETKEYBYTES]);
    unsafe {
        ffi::crypto_sign_ed25519_keypair(pk.0.as_mut_ptr(), sk.0.as_mut_ptr());
    }
    (pk, sk)
}

/// `keypair_from_seed()` computes a secret key and a corresponding public key
/// from a `Seed`.
pub fn keypair_from_seed(seed: &Seed) -> (PublicKey, SecretKey) {
    let mut pk = PublicKey([0u8; PUBLICKEYBYTES]);
    let mut sk = SecretKey([0u8; SECRETKEYBYTES]);
    unsafe {
        ffi::crypto_sign_ed25519_seed_keypair(
            pk.0.as_mut_ptr(),
            sk.0.as_mut_ptr(),
            seed.0.as_ptr(),
        );
    }
    (pk, sk)
}

/// `sign()` signs a message `m` using the signer's secret key `sk`.
/// `sign()` returns the resulting signed message `sm`.
pub fn sign(m: &[u8], sk: &SecretKey) -> Vec<u8> {
    let mut sm = vec![0u8; m.len() + SIGNATUREBYTES];
    let mut smlen = 0;
    unsafe {
        ffi::crypto_sign_ed25519(
            sm.as_mut_ptr(),
            &mut smlen,
            m.as_ptr(),
            m.len() as c_ulonglong,
            sk.0.as_ptr(),
        );
    }
    sm.truncate(smlen as usize);
    sm
}

/// `verify()` verifies the signature in `sm` using the signer's public key `pk`.
/// `verify()` returns the message `Ok(m)`.
/// If the signature fails verification, `verify()` returns `Err(())`.
pub fn verify(sm: &[u8], pk: &PublicKey) -> Result<Vec<u8>, ()> {
    let mut m = vec![0u8; sm.len()];
    let mut mlen = 0;
    let ret = unsafe {
        ffi::crypto_sign_ed25519_open(
            m.as_mut_ptr(),
            &mut mlen,
            sm.as_ptr(),
            sm.len() as c_ulonglong,
            pk.0.as_ptr(),
        )
    };
    if ret == 0 {
        m.truncate(mlen as usize);
        Ok(m)
    } else {
        Err(())
    }
}

/// `sign_detached()` signs a message `m` using the signer's secret key `sk`.
/// `sign_detached()` returns the resulting signature `sig`.
pub fn sign_detached(m: &[u8], sk: &SecretKey) -> Signature {
    let mut sig = Signature([0u8; SIGNATUREBYTES]);
    let mut siglen: c_ulonglong = 0;
    unsafe {
        ffi::crypto_sign_ed25519_detached(
            sig.0.as_mut_ptr(),
            &mut siglen,
            m.as_ptr(),
            m.len() as c_ulonglong,
            sk.0.as_ptr(),
        );
    }
    assert_eq!(siglen, SIGNATUREBYTES as c_ulonglong);
    sig
}

/// `verify_detached()` verifies the signature in `sig` against the message `m`
/// and the signer's public key `pk`.
/// `verify_detached()` returns true if the signature is valid, false otherwise.
pub fn verify_detached(sig: &Signature, m: &[u8], pk: &PublicKey) -> bool {
    let ret = unsafe {
        ffi::crypto_sign_ed25519_verify_detached(
            sig.0.as_ptr(),
            m.as_ptr(),
            m.len() as c_ulonglong,
            pk.0.as_ptr(),
        )
    };
    ret == 0
}

/// State for multi-part (streaming) computation of signature.
#[derive(Copy, Clone)]
pub struct State(ffi::crypto_sign_ed25519ph_state);

impl State {
    /// `init()` initialize a streaming signing state.
    pub fn init() -> State {
        let mut s = mem::MaybeUninit::uninit();
        let state = unsafe {
            ffi::crypto_sign_ed25519ph_init(s.as_mut_ptr());
            s.assume_init() // s is definitely initialized
        };
        State(state)
    }

    /// `update()` can be called more than once in order to compute the digest
    /// from sequential chunks of the message.
    pub fn update(&mut self, m: &[u8]) {
        unsafe {
            ffi::crypto_sign_ed25519ph_update(&mut self.0, m.as_ptr(), m.len() as c_ulonglong);
        }
    }

    /// `finalize()` finalizes the hashing computation and returns a `Signature`.
    // Moves self becuase libsodium says the state should not be used
    // anymore after final().
    pub fn finalize(mut self, &SecretKey(ref sk): &SecretKey) -> Signature {
        let mut sig = [0u8; SIGNATUREBYTES];
        let mut siglen: c_ulonglong = 0;
        unsafe {
            ffi::crypto_sign_ed25519ph_final_create(
                &mut self.0,
                sig.as_mut_ptr(),
                &mut siglen,
                sk.as_ptr(),
            );
        }
        assert_eq!(siglen, SIGNATUREBYTES as c_ulonglong);
        Signature(sig)
    }

    /// `veriry` verifies the signature in `sm` using the signer's public key `pk`.
    pub fn verify(
        &mut self,
        &Signature(ref sig): &Signature,
        &PublicKey(ref pk): &PublicKey,
    ) -> bool {
        let mut sig = *sig;
        let ret = unsafe {
            ffi::crypto_sign_ed25519ph_final_verify(&mut self.0, sig.as_mut_ptr(), pk.as_ptr())
        };
        ret == 0
    }
}

impl fmt::Debug for State {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "ed25519 state")
    }
}

// Impl Default becuase `State` does have a sensible default: State::init()
impl Default for State {
    fn default() -> State {
        State::init()
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use hex;

    #[test]
    fn test_sk_to_pk() {
        let (pk, sk) = gen_keypair();
        assert_eq!(sk.public_key(), pk);
    }

    #[test]
    fn test_sign_verify() {
        use randombytes::randombytes;
        for i in 0..256usize {
            let (pk, sk) = gen_keypair();
            let m = randombytes(i);
            let sm = sign(&m, &sk);
            let m2 = verify(&sm, &pk);
            assert!(Ok(m) == m2);
        }
    }

    #[test]
    fn test_sign_verify_tamper() {
        use randombytes::randombytes;
        for i in 0..32usize {
            let (pk, sk) = gen_keypair();
            let m = randombytes(i);
            let mut sm = sign(&m, &sk);
            for j in 0..sm.len() {
                sm[j] ^= 0x20;
                assert!(Err(()) == verify(&sm, &pk));
                sm[j] ^= 0x20;
            }
        }
    }

    #[test]
    fn test_sign_verify_detached() {
        use randombytes::randombytes;
        for i in 0..256usize {
            let (pk, sk) = gen_keypair();
            let m = randombytes(i);
            let sig = sign_detached(&m, &sk);
            assert!(verify_detached(&sig, &m, &pk));
        }
    }

    #[test]
    fn test_sign_verify_detached_tamper() {
        use randombytes::randombytes;
        for i in 0..32usize {
            let (pk, sk) = gen_keypair();
            let m = randombytes(i);
            let Signature(mut sig) = sign_detached(&m, &sk);
            for j in 0..SIGNATUREBYTES {
                sig[j] ^= 0x20;
                assert!(!verify_detached(&Signature(sig), &m, &pk));
                sig[j] ^= 0x20;
            }
        }
    }

    #[test]
    fn test_sign_verify_seed() {
        use randombytes::{randombytes, randombytes_into};
        for i in 0..256usize {
            let mut seedbuf = [0; 32];
            randombytes_into(&mut seedbuf);
            let seed = Seed(seedbuf);
            let (pk, sk) = keypair_from_seed(&seed);
            let m = randombytes(i);
            let sm = sign(&m, &sk);
            let m2 = verify(&sm, &pk);
            assert!(Ok(m) == m2);
        }
    }

    #[test]
    fn test_sign_verify_tamper_seed() {
        use randombytes::{randombytes, randombytes_into};
        for i in 0..32usize {
            let mut seedbuf = [0; 32];
            randombytes_into(&mut seedbuf);
            let seed = Seed(seedbuf);
            let (pk, sk) = keypair_from_seed(&seed);
            let m = randombytes(i);
            let mut sm = sign(&m, &sk);
            for j in 0..sm.len() {
                sm[j] ^= 0x20;
                assert!(Err(()) == verify(&sm, &pk));
                sm[j] ^= 0x20;
            }
        }
    }

    #[test]
    fn test_vectors() {
        // test vectors from the Python implementation
        // from the [Ed25519 Homepage](http://ed25519.cr.yp.to/software.html)
        use std::fs::File;
        use std::io::{BufRead, BufReader};

        let r = BufReader::new(File::open("testvectors/ed25519.input").unwrap());
        for mline in r.lines() {
            let line = mline.unwrap();
            let mut x = line.split(':');
            let x0 = x.next().unwrap();
            let x1 = x.next().unwrap();
            let x2 = x.next().unwrap();
            let x3 = x.next().unwrap();
            let seed_bytes = hex::decode(&x0[..64]).unwrap();
            let mut seed = Seed([0u8; SEEDBYTES]);
            seed.0.copy_from_slice(&seed_bytes);
            let (pk, sk) = keypair_from_seed(&seed);
            let m = hex::decode(x2).unwrap();
            let sm = sign(&m, &sk);
            verify(&sm, &pk).unwrap();
            assert!(x1 == hex::encode(pk));
            assert!(x3 == hex::encode(sm));
        }
    }

    #[test]
    fn test_vectors_detached() {
        // test vectors from the Python implementation
        // from the [Ed25519 Homepage](http://ed25519.cr.yp.to/software.html)
        use std::fs::File;
        use std::io::{BufRead, BufReader};

        let r = BufReader::new(File::open("testvectors/ed25519.input").unwrap());
        for mline in r.lines() {
            let line = mline.unwrap();
            let mut x = line.split(':');
            let x0 = x.next().unwrap();
            let x1 = x.next().unwrap();
            let x2 = x.next().unwrap();
            let x3 = x.next().unwrap();
            let seed_bytes = hex::decode(&x0[..64]).unwrap();
            assert!(seed_bytes.len() == SEEDBYTES);
            let mut seed = Seed([0u8; SEEDBYTES]);
            for (s, b) in seed.0.iter_mut().zip(seed_bytes.iter()) {
                *s = *b
            }
            let (pk, sk) = keypair_from_seed(&seed);
            let m = hex::decode(x2).unwrap();
            let sig = sign_detached(&m, &sk);
            assert!(verify_detached(&sig, &m, &pk));
            assert!(x1 == hex::encode(pk));
            let sm = hex::encode(sig) + x2; // x2 is m hex encoded
            assert!(x3 == sm);
        }
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_serialisation() {
        use randombytes::randombytes;
        use test_utils::round_trip;
        for i in 0..256usize {
            let (pk, sk) = gen_keypair();
            let m = randombytes(i);
            let sig = sign_detached(&m, &sk);
            round_trip(pk);
            round_trip(sk);
            round_trip(sig);
        }
    }

    #[test]
    fn test_streaming_sign() {
        use randombytes::randombytes;
        for i in 0..256usize {
            let (pk, sk) = gen_keypair();
            let m = randombytes(i);
            let mut creation_state = State::init();
            creation_state.update(&m);
            let sig = creation_state.finalize(&sk);
            let mut validator_state = State::init();
            validator_state.update(&m);
            assert!(validator_state.verify(&sig, &pk));
        }
    }

    #[test]
    fn test_streaming_empty_sign() {
        let (pk, sk) = gen_keypair();
        let creation_state = State::init();
        let sig = creation_state.finalize(&sk);
        let mut validator_state = State::init();
        assert!(validator_state.verify(&sig, &pk));
    }

    #[test]
    fn test_streaming_vectors() {
        // test vectors from the Python implementation
        // from the [Ed25519 Homepage](http://ed25519.cr.yp.to/software.html)
        use std::fs::File;
        use std::io::{BufRead, BufReader};

        let r = BufReader::new(File::open("testvectors/ed25519.input").unwrap());
        for mline in r.lines() {
            let line = mline.unwrap();
            let mut x = line.split(':');
            let x0 = x.next().unwrap();
            let x1 = x.next().unwrap();
            let x2 = x.next().unwrap();
            let seed_bytes = hex::decode(&x0[..64]).unwrap();
            assert!(seed_bytes.len() == SEEDBYTES);
            let mut seed = Seed([0u8; SEEDBYTES]);
            for (s, b) in seed.0.iter_mut().zip(seed_bytes.iter()) {
                *s = *b
            }
            let (pk, sk) = keypair_from_seed(&seed);

            let m = hex::decode(x2).unwrap();

            let mut creation_state = State::init();
            creation_state.update(&m);
            let sig = creation_state.finalize(&sk);

            let mut validator_state = State::init();
            validator_state.update(&m);

            assert!(validator_state.verify(&sig, &pk));

            assert_eq!(x1, hex::encode(pk));
        }
    }

    #[test]
    fn test_streaming_copy() {
        use randombytes::randombytes;
        let i = 256;
        let (pk, sk) = gen_keypair();
        let m = randombytes(i);
        let mut creation_state = State::init();
        creation_state.update(&m);

        let creation_state_copy = creation_state;
        let sig = creation_state_copy.finalize(&sk);
        let mut validator_state = State::init();
        validator_state.update(&m);
        assert!(validator_state.verify(&sig, &pk));
    }

    #[test]
    fn test_streaming_default() {
        use randombytes::randombytes;
        let i = 256;
        let (pk, sk) = gen_keypair();
        let m = randombytes(i);
        let mut creation_state = State::default();
        creation_state.update(&m);

        let sig = creation_state.finalize(&sk);
        let mut validator_state = State::init();
        validator_state.update(&m);
        assert!(validator_state.verify(&sig, &pk));
    }

    #[test]
    fn test_streaming_format() {
        let creation_state = State::init();
        let creation_state_fmt = format!("{:?}", creation_state);
        assert_eq!(creation_state_fmt, "ed25519 state");
    }

    #[test]
    fn test_chunks_sign() {
        use randombytes::randombytes;
        let (pk, sk) = gen_keypair();
        let mut creation_state = State::init();
        let mut validator_state = State::init();
        for i in 0..64usize {
            let chunk = randombytes(i);
            creation_state.update(&chunk);
            validator_state.update(&chunk);
        }
        let sig = creation_state.finalize(&sk);
        assert!(validator_state.verify(&sig, &pk));
    }
}

#[cfg(feature = "benchmarks")]
#[cfg(test)]
mod bench {
    extern crate test;
    use super::*;
    use randombytes::randombytes;

    const BENCH_SIZES: [usize; 14] = [0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096];

    #[bench]
    fn bench_sign(b: &mut test::Bencher) {
        let (_, sk) = gen_keypair();
        let ms: Vec<Vec<u8>> = BENCH_SIZES.iter().map(|s| randombytes(*s)).collect();
        b.iter(|| {
            for m in ms.iter() {
                sign(m, &sk);
            }
        });
    }

    #[bench]
    fn bench_verify(b: &mut test::Bencher) {
        let (pk, sk) = gen_keypair();
        let sms: Vec<Vec<u8>> = BENCH_SIZES
            .iter()
            .map(|s| {
                let m = randombytes(*s);
                sign(&m, &sk)
            })
            .collect();
        b.iter(|| {
            for sm in sms.iter() {
                verify(sm, &pk);
            }
        });
    }
}