pub use sodiumoxide::randombytes::randombytes_into;
pub use sodiumoxide::crypto::box_::*;
pub use sodiumoxide::crypto::hash::{sha256, sha512};
pub use sodiumoxide::crypto::secretbox;
use std::sync::{Once, ONCE_INIT};
use byteorder::{ByteOrder, NativeEndian};
use toxcore::binary_io::*;
static CRYPTO_INIT_ONCE: Once = ONCE_INIT;
static mut CRYPTO_INIT: bool = false;
pub fn crypto_init() -> bool {
CRYPTO_INIT_ONCE.call_once(|| {
let initialized = ::sodiumoxide::init();
unsafe { CRYPTO_INIT = initialized; }
});
unsafe { CRYPTO_INIT }
}
pub fn random_u32() -> u32 {
trace!("Generating random u32");
let mut array = [0; 4];
randombytes_into(&mut array);
NativeEndian::read_u32(&array)
}
pub fn random_u64() -> u64 {
trace!("Generating random u64");
let mut array = [0; 8];
randombytes_into(&mut array);
NativeEndian::read_u64(&array)
}
pub fn public_key_valid(&PublicKey(ref pk): &PublicKey) -> bool {
pk[PUBLICKEYBYTES - 1] <= 127 }
#[inline]
pub fn encrypt_precompute(their_public_key: &PublicKey,
our_secret_key: &SecretKey) -> PrecomputedKey {
precompute(their_public_key, our_secret_key)
}
#[inline]
pub fn encrypt_data_symmetric(precomputed_key: &PrecomputedKey,
nonce: &Nonce,
plain: &[u8]) -> Vec<u8> {
seal_precomputed(plain, nonce, precomputed_key)
}
#[inline]
pub fn decrypt_data_symmetric(precomputed_key: &PrecomputedKey,
nonce: &Nonce,
encrypted: &[u8]) -> Result<Vec<u8>, ()> {
open_precomputed(encrypted, nonce, precomputed_key)
}
#[inline]
pub fn increment_nonce(nonce: &mut Nonce) {
trace!(target: "Nonce", "Incrementing Nonce: {:?}", &nonce);
let Nonce(ref mut bytes) = *nonce;
bytes.reverse(); ::sodiumoxide::utils::increment_le(bytes);
bytes.reverse(); }
pub fn increment_nonce_number(mut nonce: &mut Nonce, num: usize) {
for _ in 0..num {
increment_nonce(&mut nonce);
}
}
pub fn pk_as_digest(pk: PublicKey) -> sha256::Digest {
sha256::Digest::from_slice(pk.as_ref()).unwrap()
}
pub fn digest_as_pk(d: sha256::Digest) -> PublicKey {
PublicKey::from_slice(d.as_ref()).unwrap()
}
impl FromBytes for PublicKey {
named!(from_bytes<PublicKey>, map_opt!(take!(PUBLICKEYBYTES), PublicKey::from_slice));
}
impl FromBytes for SecretKey {
named!(from_bytes<SecretKey>, map_opt!(take!(SECRETKEYBYTES), SecretKey::from_slice));
}
impl FromBytes for Nonce {
named!(from_bytes<Nonce>, map_opt!(take!(NONCEBYTES), Nonce::from_slice));
}
impl FromBytes for secretbox::Nonce {
named!(from_bytes<secretbox::Nonce>, map_opt!(take!(secretbox::NONCEBYTES), secretbox::Nonce::from_slice));
}
impl FromBytes for sha256::Digest {
named!(from_bytes<sha256::Digest>, map_opt!(take!(sha256::DIGESTBYTES), sha256::Digest::from_slice));
}
impl FromBytes for sha512::Digest {
named!(from_bytes<sha512::Digest>, map_opt!(take!(sha512::DIGESTBYTES), sha512::Digest::from_slice));
}