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
pub use sodiumoxide::crypto::hash;
pub use sodiumoxide::crypto::scalarmult;
pub use sodiumoxide::crypto::sign;
pub mod sign_ext {
use libsodium_sys::crypto_sign_ed25519_pk_to_curve25519;
use sodiumoxide::crypto::sign::ed25519;
pub const SIGN_KEY_SIZE: usize = 32;
pub fn sign_ed25519_pk_to_curve25519(public_key: ed25519::PublicKey) -> Result<[u8; SIGN_KEY_SIZE], ()> {
let mut res = [0_u8; SIGN_KEY_SIZE];
let err_code = unsafe {
crypto_sign_ed25519_pk_to_curve25519(res.as_mut_ptr(), public_key.0.as_ptr())
};
if err_code == 0 {
Ok(res)
} else {
Err(())
}
}
}
pub mod random {
use parking_lot::Once;
pub trait Random {
fn random_bytes(&self, dest: &mut [u8]);
}
pub struct DefaultRandom(());
impl DefaultRandom {
pub fn new() -> Result<Self, ()> {
if Self::init_sodiumoxide() {
Ok(DefaultRandom(()))
} else {
Err(())
}
}
fn init_sodiumoxide() -> bool {
static INIT_SODIUMOXIDE: Once = Once::new();
static mut INITIALIZED: bool = false;
INIT_SODIUMOXIDE.call_once(|| {
let success = sodiumoxide::init().is_ok();
unsafe {
INITIALIZED = success;
}
});
unsafe { INITIALIZED }
}
}
impl Random for DefaultRandom {
#[inline(always)]
fn random_bytes(&self, dest: &mut [u8]) {
sodiumoxide::randombytes::randombytes_into(dest);
}
}
}