//! Functions for generating keys and nonces for use in API calls

use rand::Rng;
use rand::rngs::OsRng;
use trifid_pki::cert::{serialize_x25519_private, serialize_x25519_public};
use trifid_pki::ed25519_dalek::{SigningKey, VerifyingKey};
use trifid_pki::x25519_dalek::{PublicKey, StaticSecret};

/// Generate a new random set of Nebula (Diffie-Hellman) and Ed25519 (API calls) keys for use in your client
pub fn new_keys() -> (Vec<u8>, Vec<u8>, VerifyingKey, SigningKey) {
    let (dh_pub, dh_priv) = new_nebula_keypair();
    let (ed_pub, ed_priv) = new_ed25519_keypair();
    (dh_pub, dh_priv, ed_pub, ed_priv)
}

/// Generate a new PEM-encoded Nebula keypair
pub fn new_nebula_keypair() -> (Vec<u8>, Vec<u8>) {
    let (pub_key, priv_key) = new_x25519_keypair();
    let pub_key_encoded = serialize_x25519_public(&pub_key);
    let priv_key_encoded = serialize_x25519_private(&priv_key);
    (pub_key_encoded, priv_key_encoded)
}

/// Generate a new 32-byte X25519 keypair
pub fn new_x25519_keypair() -> ([u8; 32], [u8; 32]) {
    let priv_key = StaticSecret::new(OsRng);
    let pub_key = PublicKey::from(&priv_key);
    (pub_key.to_bytes(), priv_key.to_bytes())
}

/// Generate a new random Ed25519 signing keypair for signing API calls
pub fn new_ed25519_keypair() -> (VerifyingKey, SigningKey) {
    let secret = SigningKey::generate(&mut OsRng);
    let public = secret.verifying_key();
    (public, secret)
}

/// Generates a 16-byte random nonce for use in API calls
pub fn nonce() -> [u8; 16] {
    rand::thread_rng().gen()
}