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
use ffi;
use std::mem;
pub fn shared(secret_key: [u8; 32], their_public_key: [u8; 32]) -> Result<[u8; 32], String> {
unsafe {
let mut shared_key: [u8; 32] = mem::uninitialized();
if ffi::crypto_key_exchange(
shared_key.as_mut_ptr(),
secret_key.as_ptr(),
their_public_key.as_ptr(),
) == 0
{
return Ok(shared_key);
}
Err("Their public key is malicious!".to_owned())
}
}
pub fn public(secret_key: [u8; 32]) -> [u8; 32] {
unsafe {
let mut public_key: [u8; 32] = mem::uninitialized();
ffi::crypto_x25519_public_key(public_key.as_mut_ptr(), secret_key.as_ptr());
public_key
}
}
#[cfg(test)]
mod test {
#[test]
fn shared() {
let pubkey = [1u8; 32];
let shared_key = ::key_exchange::shared([31u8; 32], pubkey);
assert_eq!(shared_key.is_ok(), true);
assert_eq!(shared_key.unwrap(),
[221, 154, 19, 66, 124, 44, 238, 44, 9, 242, 98, 231, 40,23, 150, 119, 121, 116,
47, 199, 173, 61, 70, 53, 155, 235, 80, 11, 107, 75, 87, 110])
}
#[test]
fn public() {
let secret_key = [2u8; 32];
let public_key = ::key_exchange::public(secret_key);
assert_eq!(public_key,
[206, 141, 58, 209, 204, 182, 51, 236, 123, 112, 193, 120, 20, 165, 199, 110,
205, 2, 150, 133, 5, 13, 52, 71, 69, 186, 5, 135, 14, 88, 125, 89])
}
}