docs

#Cryptography and TLS

On this page

Nabi ships its own cryptography. core::crypto has the algorithms (hashes, HMAC and HKDF, authenticated encryption, key exchange, signatures), std::random reads the operating system's secure random source, and std::net::tls is a TLS 1.3 client and server built on the two. No OpenSSL or other system library is involved, so the same code behaves the same on every target.

Warning

This code is experimental and has not been audited. It is tested against the published test vectors and written to run in constant time on secret data, but it has not had the independent review that cryptography needs before you trust it with real secrets. Use it to learn and to experiment, and keep an audited library for anything that matters for now.

#Hashes and MACs

The common items are at core::crypto (HashAlgorithm, Digest, Hmac, Aead, Secret, ...). Keys and HKDF are reached through their algorithm's module, since several of them have a PublicKey: crypto::ed25519::SigningKey, crypto::x25519::PrivateKey, crypto::hkdf::extract. The modules are sha2, sha3, hmac, hkdf, aead, x25519, ed25519, ecdsa, rsa and mlkem. Every function that takes bytes accepts any AsBytes value: List<u8>, Slice<u8>, a byte array, a str (its UTF-8 bytes) or a Secret, so byte strings and text can be passed directly. Your own functions that pass bytes on take <B: AsBytes> the same way, and a type of your own that implements AsBytes can be passed too. Results are List<u8>, except key material, which comes back as a Secret (below). To show bytes as text, encoding::hex::encode and encoding::base64::encode turn them into hex or base64 (base64::encode(x, base64::URL_SAFE_NO_PAD) picks another alphabet and padding), and decode turns the text back.

nabi
use core::crypto::{HashAlgorithm, Digest, Hmac};
use core::encoding::hex;

println(hex::encode(HashAlgorithm::Sha256.digest("abc")));

// The same hash, fed in pieces.
let d = Digest::new(HashAlgorithm::Sha256);
d.update("a");
d.update(b"bc");
println(f"{d.finish() == HashAlgorithm::Sha256.digest("abc")}");

let tag = Hmac::mac(HashAlgorithm::Sha256, "secret key", "message");
println(f"{tag.len()} {Hmac::verify(HashAlgorithm::Sha256, "secret key", "message", tag)}");
println(f"{Hmac::verify(HashAlgorithm::Sha256, "secret key", "massage", tag)}");
ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
true
32 true
false

Hmac::verify compares in constant time. To compare two secrets yourself, use crypto::constant_time_eq rather than ==, which stops at the first difference and so leaks how much matched. hkdf::extract / expand derive keys from a shared secret. HashAlgorithm has the SHA-3 functions too, Sha3_256 and Sha3_512, so HMAC, HKDF and signatures take them like any other: Hmac::mac(HashAlgorithm::Sha3_256, key, data). sha3 also has the SHA-3 and SHAKE states as their own types. Later releases may add algorithms, so a match on a HashAlgorithm needs a _ arm.

#Encryption and signatures

Aead encrypts and authenticates in one step (AES-128-GCM, AES-256-GCM or ChaCha20-Poly1305). seal returns the ciphertext with a 16-byte tag; open returns none when anything, the ciphertext, the tag or the associated data, was changed. Keys and nonces come from random: the algorithms take randomness as an argument and never fetch it themselves.

nabi
use core::crypto::{Aead, AeadAlgorithm};
use core::crypto::ed25519::SigningKey;
use std::random;

let key = random::secret(32);
let nonce = random::bytes(12);           // never reuse a nonce with the same key
let aead = try! Aead::new(AeadAlgorithm::ChaCha20Poly1305, key);
let sealed = try! aead.seal(nonce, "v1", "meet at noon");
println(f"{sealed.len()} bytes sealed");  // 12 bytes of text + a 16-byte tag

if let plain = try! aead.open(nonce, "v1", sealed) {
    println(try! str::from_utf8(plain));
}
sealed[0] = sealed[0] ^ 1;              // tamper with one bit
println(f"tampered: {(try! aead.open(nonce, "v1", sealed)) is none}");

let signer = try! SigningKey::from_seed(random::secret(32));   // the private key
let public = signer.verifying_key();
let sig = signer.sign("release 1.0");
println(f"{public.verify("release 1.0", sig)} {public.verify("release 1.1", sig)}");
28 bytes sealed
meet at noon
tampered: true
true false

x25519 and mlkem (ML-KEM-768) agree on shared keys (the classic and the post-quantum way), and ecdsa (P-256 / P-384) and rsa sign and verify for the certificates the web uses. A private key is a typed value (ed25519::SigningKey, x25519::PrivateKey, ecdsa::SigningKey, rsa::PrivateKey, mlkem::DecapsulationKey768) that is checked once when it is made and keeps its bytes in secret storage (below); its public half (VerifyingKey, PublicKey, EncapsulationKey768) is a plain value.

#Key material: Secret

A Secret holds bytes in secret storage: a buffer the collector never moves or copies and overwrites with zeros before it frees it. hkdf::extract / expand, x25519::PrivateKey::diffie_hellman and ML-KEM's encapsulate / decapsulate return one, and random::secret(n) draws random bytes straight into one. It prints as Secret { len: n, .. }, never its contents, and has no ==: compare with constant_time_eq. wipe() zeroes it now, and a using binding wipes it at the end of the block. Aead and the private key types keep their key in secret storage too, and their wipe clears it.

nabi
use core::crypto::{Aead, AeadAlgorithm, HashAlgorithm, Secret, constant_time_eq};
use core::crypto::{hkdf, x25519};
use std::random;

let a = try! x25519::PrivateKey::from_bytes(random::secret(32));
let b = try! x25519::PrivateKey::from_bytes(random::secret(32));
let ab = a.diffie_hellman(b.public_key()) ?? panic("bad key");
let ba = b.diffie_hellman(a.public_key()) ?? panic("bad key");
println(f"{ab:?} {constant_time_eq(ab, ba)}");

let key = try! hkdf::expand(HashAlgorithm::Sha256, hkdf::extract(HashAlgorithm::Sha256, "salt", ab), "key", 32);
let aead = try! Aead::new(AeadAlgorithm::ChaCha20Poly1305, key);
key.wipe();                               // zero it now, not at some later collection
println(f"{key[0]}");
aead.wipe();                              // the cipher is done too

using s = Secret::new("temporary") {
    println(f"{s.len()} bytes");
}                                         // wiped here
Secret { len: 32, .. } true
0
9 bytes

Copying a secret's bytes into an ordinary object (as_bytes().to_list(), a str, a formatted string) makes a copy the collector does not wipe. Secret storage is not locked in RAM either, so it can still reach swap or a core dump.

#TLS: net::tls

tls::Client::new(stream, server_name) runs a TLS 1.3 handshake over an open TcpStream, checks the server's certificate chain against the OS trust store and its name, and returns a connection with the same read / write_all / read_to_end methods as the socket. With the default config the handshake offers the X25519MLKEM768 post-quantum hybrid. TLS 1.2 and older are refused.

nabi
use std::net::{tcp_connect, tls};

let conn = try tls::Client::new(try tcp_connect("example.com:443"), "example.com");
try conn.write_all(b"GET / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n");
let resp = try conn.read_to_end();
try conn.close();                                           // close_notify, then the socket
println((try str::from_utf8(resp)).lines().next() ?? "");   // HTTP/1.1 200 OK

For real HTTP, use the http package, which does this for you, with redirects, pooling and HTTP/2.

A server needs a certificate chain and its private key, usually read from PEM files. The program below runs both sides on the loopback interface: a server task with a self-signed certificate, and a client that trusts exactly that certificate through ClientConfig.root_certs. ClientConfig and ServerConfig are records whose fields have defaults, so a literal names only what differs: ClientConfig { root_certs: chain }, or ClientConfig { alpn_protocols: [b"h2"], ..try tls::ClientConfig::new() } to start from the OS trust store. Every call has an _async form for tasks (chapter 12).

tls::system_roots() reads the OS trust store (SSL_CERT_FILE overrides it), ClientConfig.alpn_protocols negotiates protocols such as h2, and negotiated_alpn() / peer_certificates() tell you what was agreed. Client certificates, session resumption with 0-RTT data and OCSP stapling are supported; CRLs and OCSP queries over the network are not used.

#Summary

  • core::crypto has SHA-2 / SHA-3, HMAC, HKDF, AEAD, X25519, ML-KEM, Ed25519, ECDSA and RSA. Byte arguments take any AsBytes value; private keys are typed values in secret storage.
  • Randomness comes only from std::random (bytes(n), fill(buf), secret(n)) and is passed in.
  • Keys come back as Secret, which is wiped by wipe(), by using, or when it is collected.
  • Compare secrets with constant_time_eq or Hmac::verify, never ==.
  • tls::Client / tls::Server wrap a TcpStream in TLS 1.3 and then read and write like it; close() sends close_notify and closes the socket.
  • ClientConfig / ServerConfig literals name only the fields that differ from the defaults.
  • The implementation is new and unaudited.

#Further reading

Found a mistake? Edit this page on GitHub. Last updated