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
//! Poly1305 is a one-time message authentication code.
//!
//! [Official documentation](https://monocypher.org/manual/advanced/poly1305)

use ffi;
use std::mem;

/// Produces a message authentication code for the given message and authentication key.
///
/// # Example
///
/// ```
/// use monocypher::poly1305;
///
/// let key = [1u8; 32];
/// let mac = poly1305::auth("test".as_bytes(), key);
///
/// ```
pub fn auth(message: &[u8], key: [u8; 32]) -> [u8; 16] {
    unsafe {
        let mut mac: [u8; 16] = mem::uninitialized();
        ffi::crypto_poly1305(
            mac.as_mut_ptr(),
            message.as_ptr(),
            message.len(),
            key.as_ptr(),
        );
        mac
    }
}

pub struct Context(ffi::crypto_poly1305_ctx);

impl Context {

    /// Initializes a new context with the given key.
    #[inline]
    pub fn new(key: [u8; 32]) -> Context {
        unsafe {
            let mut ctx = mem::uninitialized();
            ffi::crypto_poly1305_init(&mut ctx, key.as_ptr());
            Context(ctx)
        }
    }

    /// Authenticates the message chunk by chunk.
    #[inline]
    pub fn update(&mut self, message: &[u8]) {
        unsafe {
            ffi::crypto_poly1305_update(&mut self.0, message.as_ptr(), message.len());
        }
    }

    /// Produces the message authentication code.
    #[inline]
    pub fn finalize(&mut self) -> [u8; 16] {
        unsafe {
            let mut mac: [u8; 16] = mem::uninitialized();
            ffi::crypto_poly1305_final(&mut self.0, mac.as_mut_ptr());
            mac
        }
    }
}

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


    #[test]
    fn auth() {
        let key = [1u8; 32];
        let mac = ::poly1305::auth("test".as_bytes(), key);
        assert_eq!(mac, [20, 62, 33, 196, 79, 94, 80, 79, 78, 94, 80, 79, 78, 94, 80, 79])
    }

    #[test]
    fn ctx() {
        let key = [2u8; 32];
        let mut ctx = Context::new(key);
        ctx.update("test".as_bytes());
        let mac = ctx.finalize();

        assert_eq!(mac,
                   [40, 124, 66, 136, 159, 188, 160, 158, 156, 188, 160, 158, 156, 188, 160, 158])
    }
}