dnapi_rs/
crypto.rs

1//! Functions for generating keys and nonces for use in API calls
2
3use rand::rngs::OsRng;
4use rand::Rng;
5use trifid_pki::cert::{serialize_x25519_private, serialize_x25519_public};
6use trifid_pki::ed25519_dalek::{SigningKey, VerifyingKey};
7use trifid_pki::x25519_dalek::{PublicKey, StaticSecret};
8
9/// Generate a new random set of Nebula (Diffie-Hellman) and Ed25519 (API calls) keys for use in your client
10pub fn new_keys() -> (Vec<u8>, Vec<u8>, VerifyingKey, SigningKey) {
11    let (dh_pub, dh_priv) = new_nebula_keypair();
12    let (ed_pub, ed_priv) = new_ed25519_keypair();
13    (dh_pub, dh_priv, ed_pub, ed_priv)
14}
15
16/// Generate a new PEM-encoded Nebula keypair
17pub fn new_nebula_keypair() -> (Vec<u8>, Vec<u8>) {
18    let (pub_key, priv_key) = new_x25519_keypair();
19    let pub_key_encoded = serialize_x25519_public(&pub_key);
20    let priv_key_encoded = serialize_x25519_private(&priv_key);
21    (pub_key_encoded, priv_key_encoded)
22}
23
24/// Generate a new 32-byte X25519 keypair
25pub fn new_x25519_keypair() -> ([u8; 32], [u8; 32]) {
26    let priv_key = StaticSecret::random_from_rng(OsRng);
27    let pub_key = PublicKey::from(&priv_key);
28    (pub_key.to_bytes(), priv_key.to_bytes())
29}
30
31/// Generate a new random Ed25519 signing keypair for signing API calls
32pub fn new_ed25519_keypair() -> (VerifyingKey, SigningKey) {
33    let secret = SigningKey::generate(&mut OsRng);
34    let public = secret.verifying_key();
35    (public, secret)
36}
37
38/// Generates a 16-byte random nonce for use in API calls
39pub fn nonce() -> [u8; 16] {
40    rand::thread_rng().gen()
41}