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
//! Memory safe keypair implementation.
use crypto::asymmetrickey::authenc::{
BEFORENMBYTES,
PUBLICKEYBYTES,
SECRETKEYBYTES,
SEEDBYTES
};
use libc::{c_int, c_uchar};
use SSError::{self, KEYGEN};
use crypto::utils::secmem;
/// The key structure contains information necessary to create slices from raw
/// parts.
pub struct KeyPair {
s_key_ptr: *mut u8,
s_size: usize,
p_key_ptr: *mut u8,
p_size: usize,
}
extern "C" {
fn crypto_box_seed_keypair(pk: *mut c_uchar,
sk: *mut c_uchar,
seed: *const c_uchar) -> c_int;
fn crypto_box_keypair(pk: *mut c_uchar, sk: *mut c_uchar) -> c_int;
fn crypto_scalarmult_base(q: *mut c_uchar, n: *const c_uchar) -> c_int;
fn crypto_box_beforenm(k: *mut c_uchar,
pk: *const c_uchar,
sk: *const c_uchar) -> c_int;
}
impl KeyPair {
/// Create a new keypair with the given sizes. The keys are generated with
/// the *crypto_box_keypair()* function to ensure safety and then set to no
/// access via *mprotect_noaccess()* to ensure the data is not inadvertently
/// (or maliciously) altered. Note in order to use the keypair, the caller
/// must use *activate_sk()* and *activate_pk()*.
///
/// # Examples
///
/// ```
/// use sodium_sys::crypto::utils::init;
/// use sodium_sys::crypto::asymmetrickey::{authenc,auth_keypair};
///
/// // Initialize the sodium-sys library.
/// init::init();
///
/// // Create a keypair for the box_ module.
/// let keypair = auth_keypair::KeyPair::new().unwrap();
///
/// // Activate the keys for use (they are created as no access).
/// keypair.activate_sk();
/// keypair.activate_pk();
///
/// // Validate.
/// assert!(keypair.sk_bytes().len() == authenc::SECRETKEYBYTES);
/// assert!(keypair.sk_bytes() != [0; authenc::SECRETKEYBYTES]);
/// assert!(keypair.pk_bytes().len() == authenc::PUBLICKEYBYTES);
/// assert!(keypair.pk_bytes() != [0; authenc::PUBLICKEYBYTES]);
/// ```
pub fn new() -> Result<KeyPair, SSError> {
let mut sk = secmem::malloc(SECRETKEYBYTES);
let mut pk = secmem::malloc(PUBLICKEYBYTES);
let res: i32;
unsafe {
res = crypto_box_keypair(pk.as_mut_ptr(), sk.as_mut_ptr());
}
if res == 0 {
secmem::mprotect_noaccess(sk);
secmem::mprotect_noaccess(pk);
Ok(KeyPair {
s_key_ptr: sk.as_mut_ptr(),
s_size: SECRETKEYBYTES,
p_key_ptr: pk.as_mut_ptr(),
p_size: PUBLICKEYBYTES,
})
} else {
Err(KEYGEN("Unable to generate keypair"))
}
}
/// Create a new keypair with the given sizes and the given seed key. The
/// keys are generated with the *crypto_box_seed_keypair()* function to
/// ensure safety and then set to no access via *mprotect_noaccess()* to
/// ensure the data is not inadvertently (or maliciously) altered. Note in
/// order to use the keypair, the caller must use *activate_sk()* and
/// *activate_pk()*.
///
/// # Examples
///
/// ```
/// use sodium_sys::crypto::utils::init;
/// use sodium_sys::crypto::asymmetrickey::{authenc,auth_keypair};
///
/// // Initialize the sodium-sys library.
/// init::init();
///
/// // Test seed key (don't use all zeros, it's a bad idea).
/// const TEST_SEED_KEY: [u8; authenc::SEEDBYTES] = [0; authenc::SEEDBYTES];
///
/// // Create a keypair for the box_ module.
/// let keypair = auth_keypair::KeyPair::new_with_seed(&TEST_SEED_KEY).unwrap();
///
/// // Activate the keys for use (they are created as no access).
/// keypair.activate_sk();
/// keypair.activate_pk();
///
/// // Validate.
/// assert!(keypair.sk_bytes().len() == authenc::SECRETKEYBYTES);
/// assert!(keypair.sk_bytes() != [0; authenc::SECRETKEYBYTES]);
/// assert!(keypair.pk_bytes().len() == authenc::PUBLICKEYBYTES);
/// assert!(keypair.pk_bytes() != [0; authenc::PUBLICKEYBYTES]);
/// ```
pub fn new_with_seed(seed: &[u8]) -> Result<KeyPair, SSError> {
assert!(seed.len() == SEEDBYTES);
let mut sk = secmem::malloc(SECRETKEYBYTES);
let mut pk = secmem::malloc(PUBLICKEYBYTES);
let res: i32;
unsafe {
res = crypto_box_seed_keypair(pk.as_mut_ptr(),
sk.as_mut_ptr(),
seed.as_ptr());
}
if res == 0 {
secmem::mprotect_noaccess(sk);
secmem::mprotect_noaccess(pk);
Ok(KeyPair {
s_key_ptr: sk.as_mut_ptr(),
s_size: SECRETKEYBYTES,
p_key_ptr: pk.as_mut_ptr(),
p_size: PUBLICKEYBYTES,
})
} else {
Err(KEYGEN("Unable to generate keypair"))
}
}
/// In addition, *derivepk()* can be used to compute the public key given a
/// secret key previously generated by *KeyPair::new()* or
/// *KeyPair::seed()*.
pub fn derivepk(sk: &[u8]) -> Result<KeyPair, SSError> {
let mut nsk = secmem::malloc(SECRETKEYBYTES);
let mut pk = secmem::malloc(PUBLICKEYBYTES);
// Copy the old secret into this KeyPair to avoid any drop issues.
for (i,b) in (0..).zip(sk.iter()) {
nsk[i] = *b;
}
let res: i32;
unsafe {
res = crypto_scalarmult_base(pk.as_mut_ptr(), nsk.as_ptr());
}
if res == 0 {
secmem::mprotect_noaccess(nsk);
secmem::mprotect_noaccess(pk);
Ok(KeyPair {
s_key_ptr: nsk.as_mut_ptr(),
s_size: SECRETKEYBYTES,
p_key_ptr: pk.as_mut_ptr(),
p_size: PUBLICKEYBYTES,
})
} else {
Err(KEYGEN("Unable to derive public key"))
}
}
/// Convert the secret key to a byte sequence.
pub fn sk_bytes(&self) -> &[u8] {
use std::slice;
unsafe {
slice::from_raw_parts(self.s_key_ptr, self.s_size)
}
}
/// Convert the secret key to a mutable byte sequence.
pub fn sk_bytes_mut(&self) -> &mut [u8] {
use std::slice;
unsafe {
slice::from_raw_parts_mut(self.s_key_ptr, self.s_size)
}
}
/// Activate the secret key for use via *mprotect_readonly()*. Note that
/// once a secret key is created it cannot be modified in memory, only read.
pub fn activate_sk(&self) {
secmem::mprotect_readonly(self.sk_bytes());
}
/// De-activate the secret key via *mprotect_noaccess()*. Use this when the
/// key isn't currently being used, but may be at a later time.
pub fn deactivate_sk(&self) {
secmem::mprotect_noaccess(self.sk_bytes());
}
/// Convert the public key to a byte sequence.
pub fn pk_bytes(&self) -> &[u8] {
use std::slice;
unsafe {
slice::from_raw_parts(self.p_key_ptr, self.p_size)
}
}
/// Convert the public key to a mutable byte sequence.
pub fn pk_bytes_mut(&self) -> &mut [u8] {
use std::slice;
unsafe {
slice::from_raw_parts_mut(self.p_key_ptr, self.p_size)
}
}
/// Activate the public key for use via *mprotect_readonly()*. Note that
/// once a public key is created it cannot be modified in memory, only read.
pub fn activate_pk(&self) {
secmem::mprotect_readonly(self.pk_bytes());
}
/// De-activate the public key via *mprotect_noaccess()*. Use this when the
/// key isn't currently being used, but may be at a later time.
pub fn deactivate_pk(&self) {
secmem::mprotect_noaccess(self.pk_bytes());
}
/// Applications that send several messages to the same receiver or receive
/// several messages from the same sender can gain speed by calculating the
/// shared key only once, and reusing it in subsequent operations.
///
/// The *shared_secret()* function computes a shared secret key given a
/// public key and returns the shared secret key result.
pub fn shared_secret<'a>(&self,
pk: &[u8]) -> Result<&'a mut [u8], SSError> {
let mut ssk = secmem::malloc(BEFORENMBYTES);
let res: i32;
unsafe {
res = crypto_box_beforenm(ssk.as_mut_ptr(),
pk.as_ptr(),
self.s_key_ptr);
}
if res == 0 {
secmem::mprotect_readonly(ssk);
Ok(ssk)
} else {
Err(KEYGEN("Unable to generate shared secret key!"))
}
}
}
impl Drop for KeyPair {
/// Free the keypair memory if the pointer is not null. libsodium *free()*
/// is used here.
fn drop(&mut self) {
// Guard against the ref having already been dropped
if !self.s_key_ptr.is_null() { secmem::free(self.sk_bytes()); }
if !self.p_key_ptr.is_null() { secmem::free(self.pk_bytes()); }
}
}