trifid/dnapi-rs/src/crypto.rs

42 lines
1.5 KiB
Rust
Raw Normal View History

2023-03-29 17:13:50 +00:00
//! Functions for generating keys and nonces for use in API calls
use rand::rngs::OsRng;
2023-05-14 17:47:49 +00:00
use rand::Rng;
2023-03-29 17:13:50 +00:00
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]) {
2023-04-07 00:23:05 +00:00
let priv_key = StaticSecret::random_from_rng(OsRng);
2023-03-29 17:13:50 +00:00
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()
2023-05-14 17:47:49 +00:00
}