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
//! This crate implements the NTRUMLS library in Rust. It is an interface to the reference NTRUMLS
//! implementation. NTRUMLS is a modular latice signature based in NTRU, which avoids the security
//! issues of NTRUSign. More on NTRUMLS
//! [here](https://github.com/NTRUOpenSourceProject/NTRUMLS/raw/master/doc/NTRUMLS-preprint.pdf).
//!
//! NTRU is a faster encryption / decryption scheme, that uses latice based encryption to provide
//! quantum proof security. More on NTRUEncrypt [here](https://en.wikipedia.org/wiki/NTRUEncrypt).
//!
//! To use this library, you need to include this in your crate:
//!
//! ```
//! extern crate ntrumls;
//! ```
//!
//! # Examples
//!
//! To generate the keys that will be used during encryption / decryption, you have to use the
//! ```generate_keys()``` function. These keys must not be used in NTRUEncrypt nor in other
//! encryption schemes, since they are specifically generated for this purpose. Example:
//!
//! ```
//! use ntrumls::params::{ParamSet, XXX_20151024_743};
//!
//! let params = XXX_20151024_743;
//! let (private_key, public_key) = ntrumls::generate_keys(&params).unwrap();
//!
//! let mut message = b"Hello from NTRUMLS!";
//!
//! let signature = ntrumls::sign(&private_key, &public_key, message).unwrap();
//! assert!(ntrumls::verify(&signature, &public_key, message));
//! ```

// #![forbid(missing_docs, warnings)]
#![deny(deprecated, drop_with_repr_extern, improper_ctypes,
        non_shorthand_field_patterns, overflowing_literals, plugin_as_library,
        private_no_mangle_fns, private_no_mangle_statics, stable_features, unconditional_recursion,
        unknown_lints, unused, unused_allocation, unused_attributes,
        unused_comparisons, unused_features, unused_parens, while_true)]
#![warn(missing_docs, trivial_casts, trivial_numeric_casts, unused, unused_extern_crates,
        unused_import_braces, unused_qualifications, unused_results, variant_size_differences)]

extern crate libc;

pub mod params;
mod ffi;

use std::ptr;
use params::ParamSet;

/// Generates a public and private key pair
///
/// This function generates a public and private key pair to use when signing and verifying a
/// message. It needs the NTRUMLS parameter to use, and it will return an optional tuple, with the
/// private key in the first position and the public key in the second position. If something goes
/// wrong, ```None``` will be returned. Example:
///
/// ```
/// use ntrumls::params::{ParamSet, XXX_20151024_743};
///
/// let params = XXX_20151024_743;
/// let (private_key, public_key) = ntrumls::generate_keys(&params).unwrap();
///
/// ```
pub fn generate_keys(params: &ParamSet) -> Option<(PrivateKey, PublicKey)> {
    let (mut privkey_blob_len, mut pubkey_blob_len) = (0usize, 0usize);

    let result = unsafe {
        ffi::pq_gen_key(params,
                        &mut privkey_blob_len,
                        ptr::null_mut(),
                        &mut pubkey_blob_len,
                        ptr::null_mut())
    };
    if result != 0 {
        return None;
    }

    let mut privkey_blob = vec![0u8; privkey_blob_len];
    let mut pubkey_blob = vec![0u8; pubkey_blob_len];
    let result = unsafe {
        ffi::pq_gen_key(params,
                        &mut privkey_blob_len,
                        &mut privkey_blob[..][0],
                        &mut pubkey_blob_len,
                        &mut pubkey_blob[..][0])
    };

    if result != 0 {
        None
    } else {
        Some((PrivateKey::import(privkey_blob.as_slice()),
              PublicKey::import(pubkey_blob.as_slice())))
    }
}

/// Signs a message
///
/// This function signs a message using the public and private key pair. It will return an optional
/// boxed byte array, with the signed message. If something goes wrong, ```None``` will be
/// returned. Example:
///
/// ```
/// # use ntrumls::params::{ParamSet, XXX_20151024_743};
///
/// # let params = XXX_20151024_743;
/// # let (private_key, public_key) = ntrumls::generate_keys(&params).unwrap();
/// #
/// let mut message = b"Hello from NTRUMLS!";
/// let signature = ntrumls::sign(&private_key, &public_key, message).unwrap();
/// ```
pub fn sign(private_key: &PrivateKey, public_key: &PublicKey, message: &[u8]) -> Option<Box<[u8]>> {
    let mut sign_len = 0usize;
    let result = unsafe {
        ffi::pq_sign(&mut sign_len,
                     ptr::null_mut(),
                     private_key.get_bytes().len(),
                     &private_key.get_bytes()[0],
                     public_key.get_bytes().len(),
                     &public_key.get_bytes()[0],
                     message.len(),
                     &message[0])
    };
    if result != 0 {
        return None;
    }

    let mut sign = vec![0u8; sign_len];
    let result = unsafe {
        ffi::pq_sign(&mut sign_len,
                     &mut sign[0],
                     private_key.get_bytes().len(),
                     &private_key.get_bytes()[0],
                     public_key.get_bytes().len(),
                     &public_key.get_bytes()[0],
                     message.len(),
                     &message[0])
    };

    if result != 0 {
        None
    } else {
        Some(sign.into_boxed_slice())
    }
}

/// Verifies a signed message
///
/// This function verifies that a signed message has been signed with the given public key's
/// private key. It will return a boolean indicating if it has been verified or not. Example:
///
/// ```
/// # use ntrumls::params::{ParamSet, XXX_20151024_743};
///
/// # let params = XXX_20151024_743;
/// # let (private_key, public_key) = ntrumls::generate_keys(&params).unwrap();
/// #
/// let mut message = b"Hello from NTRUMLS!";
/// let signature = ntrumls::sign(&private_key, &public_key, message).unwrap();
///
/// let signature = ntrumls::sign(&private_key, &public_key, message).unwrap();
/// assert!(ntrumls::verify(&signature, &public_key, message));
pub fn verify(signature: &[u8], public_key: &PublicKey, message: &[u8]) -> bool {
    let result = unsafe {
        ffi::pq_verify(signature.len(),
                       &signature[0],
                       public_key.get_bytes().len(),
                       &public_key.get_bytes()[0],
                       message.len(),
                       &message[0])
    };

    result == 0
}

/// NTRUMLS private key
#[derive(PartialEq, Eq, Debug, Clone)]
pub struct PrivateKey {
    ffi_key: Box<[u8]>,
}

impl PrivateKey {
    /// Import the actual bytes of the key to the struct
    pub fn import(bytes: &[u8]) -> PrivateKey {
        PrivateKey { ffi_key: bytes.to_vec().into_boxed_slice() }
    }

    /// Get the byte slice of the key
    pub fn get_bytes(&self) -> &[u8] {
        &self.ffi_key
    }
}

/// NTRUMLS public key
#[derive(PartialEq, Eq, Debug, Clone)]
pub struct PublicKey {
    ffi_key: Box<[u8]>,
}

impl PublicKey {
    /// Import the actual bytes of the key to the struct
    pub fn import(bytes: &[u8]) -> PublicKey {
        PublicKey { ffi_key: bytes.to_vec().into_boxed_slice() }
    }

    /// Get the byte slice of the key
    pub fn get_bytes(&self) -> &[u8] {
        &self.ffi_key
    }
}