//! P-256 keys (`spec/SPACES.md`, "P-256 did:keys"): a public key as a //! `did:key`, an account's KEM key, and the shared secret a syncer's key //! share and the KEM key make ("The shared secret"): HPKE's secret export //! (RFC 9180 §5.3) in base mode, DHKEM(P-256, HKDF-SHA256), HKDF-SHA256 and //! the Export-only AEAD, the key share its `enc`. use crate::Error; use hmac::{Hmac, Mac}; use p256::elliptic_curve::Generate; use p256::elliptic_curve::sec1::ToSec1Point; use sha2::Sha256; /// The multicodec `p256-pub`, as a varint. const P256_PUB: [u8; 2] = [0x80, 0x24]; /// A point on P-256. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct PublicKey(p256::PublicKey); impl PublicKey { /// The key a P-256 `did:key` names: `did:key:z`, then base58btc of /// `0x80 0x24` and the 33-byte compressed point. Anything else is no /// P-256 key: another curve, an uncompressed point, an `x` with no point. pub fn from_did_key(s: &str) -> Result { let b58 = s .strip_prefix("did:key:z") .ok_or_else(|| Error::new("not a did:key"))?; let bytes = bs58::decode(b58) .into_vec() .map_err(|_| Error::new("a did:key that does not parse"))?; let point = bytes .strip_prefix(&P256_PUB[..]) .ok_or_else(|| Error::new("a did:key that is not P-256"))?; if point.len() != 33 || !matches!(point[0], 2 | 3) { return Err(Error::new( "a P-256 did:key that is not 33 bytes of compressed point", )); } p256::PublicKey::from_sec1_bytes(point) .map(PublicKey) .map_err(|_| Error::new("a P-256 did:key with no point on the curve")) } /// The key as a `did:key`; every one starts `did:key:zDn`. pub fn did_key(&self) -> String { let mut bytes = P256_PUB.to_vec(); bytes.extend_from_slice(self.0.to_sec1_point(true).as_bytes()); format!("did:key:z{}", bs58::encode(bytes).into_string()) } /// The uncompressed point: `0x04`, `x`, `y`, each 32 bytes big-endian. pub fn uncompressed(&self) -> [u8; 65] { self.0 .to_sec1_point(false) .as_bytes() .try_into() .expect("an uncompressed P-256 point is 65 bytes") } pub(crate) fn verifying_key(&self) -> p256::ecdsa::VerifyingKey { p256::ecdsa::VerifyingKey::from(self.0) } } /// An account's KEM key: a P-256 private key, which signs nothing. #[derive(Clone)] pub struct KemKey(p256::SecretKey); impl std::fmt::Debug for KemKey { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "KemKey({})", self.public().did_key()) } } impl KemKey { /// A new key, from the operating system's random source. pub fn generate() -> KemKey { KemKey(p256::SecretKey::generate()) } /// The key whose scalar is these 32 bytes, big-endian. pub fn from_bytes(bytes: &[u8]) -> Result { if bytes.len() != 32 { return Err(Error::new("a P-256 private key is 32 bytes")); } p256::SecretKey::from_slice(bytes) .map(KemKey) .map_err(|_| Error::new("not a P-256 private key")) } /// The scalar, 32 bytes big-endian, as `from_bytes` takes it. pub fn to_bytes(&self) -> [u8; 32] { self.0.to_bytes().into() } pub fn public(&self) -> PublicKey { PublicKey(self.0.public_key()) } /// ECDH with another key: the 32-byte big-endian `x` of `d·P`. pub fn dh(&self, other: &PublicKey) -> [u8; 32] { let shared = p256::ecdh::diffie_hellman(self.0.to_nonzero_scalar(), other.0.as_affine()); (*shared.raw_secret_bytes()).into() } /// DHKEM's shared secret (RFC 9180 §4.1) of a syncer's key share and /// this key, the step before the key schedule. pub fn kem_secret(&self, key_share: &PublicKey) -> [u8; 32] { kem_secret(&self.dh(key_share), key_share, &self.public()) } /// The secret HPKE exports, in base mode with an empty exporter context /// and a length of 32, to this key from a syncer's key share, under /// `info`: `MAC_INFO` for every MAC. pub fn decapsulate(&self, key_share: &PublicKey, info: &[u8]) -> SharedSecret { export(&self.kem_secret(key_share), info) } /// The shared secret of a syncer's key share and this key, the key of /// their MACs: `decapsulate` with `MAC_INFO`. pub fn shared_secret(&self, key_share: &PublicKey) -> SharedSecret { self.decapsulate(key_share, MAC_INFO) } /// The same secret as a syncer makes it: this key the fresh one whose /// public key is the key share, `author` the author's KEM key. pub fn encapsulate(&self, author: &PublicKey) -> SharedSecret { export( &kem_secret(&self.dh(author), &self.public(), author), MAC_INFO, ) } } /// The `info` of the shared secret: the ASCII bytes `atproto-mac`. pub const MAC_INFO: &[u8] = b"atproto-mac"; /// `"KEM" ‖ u16(0x0010)`: DHKEM(P-256, HKDF-SHA256). const KEM_ID: &[u8] = b"KEM\x00\x10"; /// `"HPKE" ‖ u16(0x0010) ‖ u16(0x0001) ‖ u16(0xFFFF)`: the ciphersuite, its /// AEAD Export-only. const SUITE_ID: &[u8] = b"HPKE\x00\x10\x00\x01\xff\xff"; fn labeled_extract(id: &[u8], salt: &[u8], label: &[u8], ikm: &[u8]) -> [u8; 32] { hmac(salt, &[b"HPKE-v1", id, label, ikm]) } /// HKDF's expand to 32 bytes, its one block. fn labeled_expand(id: &[u8], prk: &[u8], label: &[u8], info: &[u8]) -> [u8; 32] { hmac(prk, &[&[0, 32], b"HPKE-v1", id, label, info, &[1]]) } /// DHKEM's shared secret of `dh`, `enc` and the recipient `author`. fn kem_secret(dh: &[u8; 32], enc: &PublicKey, author: &PublicKey) -> [u8; 32] { let prk = labeled_extract(KEM_ID, b"", b"eae_prk", dh); let kem_context = [enc.uncompressed(), author.uncompressed()].concat(); labeled_expand(KEM_ID, &prk, b"shared_secret", &kem_context) } /// The key schedule in base mode, with no pre-shared key, then the export /// with an empty exporter context. fn export(kem_secret: &[u8; 32], info: &[u8]) -> SharedSecret { let psk_id_hash = labeled_extract(SUITE_ID, b"", b"psk_id_hash", b""); let info_hash = labeled_extract(SUITE_ID, b"", b"info_hash", info); let context = [&[0][..], &psk_id_hash, &info_hash].concat(); let secret = labeled_extract(SUITE_ID, kem_secret, b"secret", b""); let exporter_secret = labeled_expand(SUITE_ID, &secret, b"exp", &context); SharedSecret(labeled_expand(SUITE_ID, &exporter_secret, b"sec", b"")) } /// HMAC-SHA256 of the parts, in order, keyed with `key`. pub(crate) fn hmac(key: &[u8], parts: &[&[u8]]) -> [u8; 32] { let mut m = Hmac::::new_from_slice(key).expect("HMAC takes a key of any length"); for p in parts { m.update(p); } m.finalize().into_bytes().into() } /// Whether `mac` is the HMAC-SHA256 of `message` keyed with `key`, compared /// in constant time. pub(crate) fn verify_hmac(key: &[u8], message: &[u8], mac: &[u8]) -> bool { let mut m = Hmac::::new_from_slice(key).expect("HMAC takes a key of any length"); m.update(message); m.verify_slice(mac).is_ok() } /// The secret a syncer and a repo host agree, the key of their MACs. #[derive(Clone, PartialEq, Eq)] pub struct SharedSecret(pub [u8; 32]); impl std::fmt::Debug for SharedSecret { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("SharedSecret(..)") } }