[keys] Key pairs and API keys: custos-keys (Ed25519, ECDSA P-256, RSA), secret_key, api_key; threat model; v0.4.0

This commit is contained in:
2026-11-02 15:49:07 +01:00
parent 12783c9b92
commit 3f3cd26590
8 changed files with 914 additions and 48 deletions
+80
View File
@@ -514,3 +514,83 @@ pub fn pin(length: u8) -> Generated {
let value: String = (0..len).map(|_| digit()).collect();
Generated { value: SecretString::new(value), entropy_bits: len as f64 * 10f64.log2() }
}
// ---------- keys and API keys (docs/KEYS.md) ----------
/// How a secret key is written out.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum KeyEncoding {
/// Lowercase hex.
Hex,
/// Base64url without padding.
Base64Url,
/// Standard base64 with padding.
Base64,
}
/// `bytes` random bytes (16..=128), encoded: symmetric keys, HMAC and JWT secrets.
pub fn secret_key(bytes: usize, encoding: KeyEncoding) -> Result<Generated, GenError> {
if !(16..=128).contains(&bytes) {
return Err(GenError("a secret key is 16 to 128 bytes".into()));
}
let mut raw = zeroize::Zeroizing::new(vec![0u8; bytes]);
rand::Rng::fill_bytes(&mut rng(), &mut raw);
let value = match encoding {
KeyEncoding::Hex => data_encoding::HEXLOWER.encode(&raw),
KeyEncoding::Base64Url => data_encoding::BASE64URL_NOPAD.encode(&raw),
KeyEncoding::Base64 => data_encoding::BASE64.encode(&raw),
};
Ok(Generated { value: SecretString::new(value), entropy_bits: 8.0 * bytes as f64 })
}
const BASE62: &[u8; 62] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
const API_KEY_RANDOM: usize = 32;
/// CRC-32 (IEEE 802.3, reflected, as zlib computes it): the API key checksum. Not a security feature.
fn crc32(data: &[u8]) -> u32 {
let mut crc = !0u32;
for &b in data {
crc ^= b as u32;
for _ in 0..8 {
crc = if crc & 1 != 0 { (crc >> 1) ^ 0xEDB8_8320 } else { crc >> 1 };
}
}
!crc
}
fn checksum6(body: &str) -> String {
let mut n = crc32(body.as_bytes()) as u64;
let mut out = [b'0'; 6];
for c in out.iter_mut().rev() {
*c = BASE62[(n % 62) as usize];
n /= 62;
}
String::from_utf8(out.to_vec()).expect("base62 is ASCII")
}
/// `<prefix>_` + 32 uniform base62 characters (190.5 bits) + a 6-character CRC-32 checksum.
/// The prefix is empty, or a lowercase letter and up to 15 lowercase letters or digits.
pub fn api_key(prefix: &str) -> Result<Generated, GenError> {
let ok = prefix.is_empty()
|| (prefix.len() <= 16
&& prefix.starts_with(|c: char| c.is_ascii_lowercase())
&& prefix.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit()));
if !ok {
return Err(GenError("the prefix is a lowercase letter and up to 15 lowercase letters or digits".into()));
}
let mut body = if prefix.is_empty() { String::new() } else { format!("{prefix}_") };
for _ in 0..API_KEY_RANDOM {
body.push(BASE62[rng().random_range(0..62)] as char);
}
let sum = checksum6(&body);
body.push_str(&sum);
Ok(Generated { value: SecretString::new(body), entropy_bits: API_KEY_RANDOM as f64 * 62f64.log2() })
}
/// Whether an API key's last 6 characters are the checksum of the rest (a typo, or not one of ours).
pub fn api_key_checksum_ok(key: &str) -> bool {
key.len() > 6 && key.is_char_boundary(key.len() - 6) && {
let (body, sum) = key.split_at(key.len() - 6);
checksum6(body) == sum
}
}