use ed25519_dalek::VerifyingKey;
use crate::errors::{Error, Kind, Result};
use crate::keys::{aid_of, b64url, decode, public_key, y_below_prime, URL_ALPHABET};
use crate::openssh::{b64std_canonical, ssh_public_blob};
pub(crate) const MAX_PUBLIC_CHARS: usize = 1024;
const RAW_LEN: usize = 32;
const AID_LEN: usize = 44;
const RAW_B64URL_LEN: usize = 43;
const ED25519_PUB: [u8; 2] = [0xed, 0x01];
const MAX_MULTIBASE: usize = 48;
const B58: &[u8; 58] = b"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
fn b64url_canonical(text: &str) -> Option<Vec<u8>> {
if !text.bytes().all(|b| URL_ALPHABET.contains(&b)) {
return None;
}
let data = decode(text, URL_ALPHABET)?;
(b64url(&data) == text).then_some(data)
}
pub(crate) fn b58_decode(text: &str) -> Option<Vec<u8>> {
if text.is_empty() {
return None;
}
let zeros = text.bytes().take_while(|b| *b == b'1').count();
let mut number: Vec<u8> = Vec::new();
for ch in text.bytes() {
let mut carry = B58.iter().position(|c| *c == ch)? as u32;
for byte in number.iter_mut().rev() {
carry += *byte as u32 * 58;
*byte = carry as u8;
carry >>= 8;
}
while carry > 0 {
number.insert(0, carry as u8);
carry >>= 8;
}
}
let mut out = vec![0u8; zeros];
out.extend(number);
Some(out)
}
fn multibase_ed25519(value: &str) -> Option<[u8; RAW_LEN]> {
if value.len() > MAX_MULTIBASE {
return None;
}
let decoded = b58_decode(value.strip_prefix('z')?)?;
if decoded.len() != ED25519_PUB.len() + RAW_LEN || decoded[..2] != ED25519_PUB {
return None;
}
decoded[2..].try_into().ok()
}
fn aid_body(text: &str) -> Option<[u8; RAW_LEN]> {
if text.len() != AID_LEN || !b"BDE".contains(&text.as_bytes()[0]) {
return None;
}
let decoded = b64url_canonical(&format!("A{}", &text[1..]))?;
let raw: [u8; RAW_LEN] = decoded[1..].try_into().ok()?;
(aid_of(&raw)[1..] == text[1..]).then_some(raw)
}
fn ssh_line(text: &str) -> Option<[u8; RAW_LEN]> {
let rest = text.strip_prefix("ssh-ed25519 ")?;
let (blob, comment) = match rest.split_once(' ') {
Some((blob, comment)) => (blob, Some(comment)),
None => (rest, None),
};
let blob_ok = !blob.is_empty()
&& blob
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"+/=".contains(&b));
let comment_ok = comment.map_or(true, |c| {
let bytes = c.as_bytes();
!bytes.is_empty()
&& bytes.iter().all(|b| (0x20..=0x7e).contains(b))
&& bytes[0] != b' '
&& bytes[bytes.len() - 1] != b' '
});
if !blob_ok || !comment_ok {
return None;
}
ssh_public_blob(&b64std_canonical(blob)?)
}
fn raw_of(text: &str) -> Option<[u8; RAW_LEN]> {
if text.len() == AID_LEN && text.starts_with('B') {
return aid_body(text);
}
if text.len() == RAW_B64URL_LEN {
return b64url_canonical(text)?.try_into().ok();
}
if let Some(value) = text.strip_prefix("did:key:") {
return multibase_ed25519(value);
}
if let Some(value) = text.strip_prefix("did:peer:0") {
return multibase_ed25519(value);
}
ssh_line(text)
}
fn refuse(message: String) -> Error {
Error::new(Kind::MalformedKey, message)
}
pub fn aid_from(text: &str) -> Result<String> {
if text.chars().nth(MAX_PUBLIC_CHARS).is_some() {
return Err(refuse(format!(
"A public key is at most {MAX_PUBLIC_CHARS} characters in any spelling fiki reads; \
this one is longer."
)));
}
if (text.starts_with('D') || text.starts_with('E')) && aid_body(text).is_some() {
return Err(refuse(
"The text is a transferable or digest AID, whose current key is not recoverable from \
the identifier; resolve it to a key first."
.into(),
));
}
let raw = raw_of(text).ok_or_else(|| {
refuse(format!(
"The text, {} characters, is not an Ed25519 public key in any spelling fiki reads: an \
AID, raw base64url, a base58btc did:key, a did:peer:0, or an ssh-ed25519 line.",
text.chars().count()
))
})?;
if public_key(&raw).is_none() {
let on_curve = y_below_prime(&raw) && VerifyingKey::from_bytes(&raw).is_ok();
return Err(refuse(if on_curve {
"The key given is a point of small order, under which a signature can be forged for \
any message, so no signature is checked against it."
.into()
} else {
"The key given is not the canonical encoding of a point on the Ed25519 curve, so no \
signature could be checked against it."
.into()
}));
}
Ok(aid_of(&raw))
}
#[cfg(test)]
mod tests {
use super::*;
fn b58_encode(raw: &[u8]) -> String {
let zeros = raw.iter().take_while(|b| **b == 0).count();
let mut digits: Vec<u8> = Vec::new(); for byte in &raw[zeros..] {
let mut carry = *byte as u32;
for d in digits.iter_mut() {
carry += *d as u32 * 256;
*d = (carry % 58) as u8;
carry /= 58;
}
while carry > 0 {
digits.push((carry % 58) as u8);
carry /= 58;
}
}
let mut out = "1".repeat(zeros);
out.extend(digits.iter().rev().map(|d| B58[*d as usize] as char));
out
}
#[test]
fn base58_decodes_every_string_to_the_one_byte_string_that_re_encodes_to_it() {
let mut texts: Vec<String> = Vec::new();
for a in B58.iter() {
texts.push((*a as char).to_string());
for b in B58.iter() {
texts.push(format!("{}{}", *a as char, *b as char));
for c in *b"1z" {
texts.push(format!("{}{}{}", c as char, *a as char, *b as char));
}
}
}
texts.push("1111".into());
texts.push("z".repeat(47));
for text in texts {
let raw = b58_decode(&text).unwrap();
assert_eq!(b58_encode(&raw), text);
}
for raw in [
vec![],
vec![0],
vec![0, 0, 1],
vec![255; 34],
(0u8..34).collect(),
] {
assert_eq!(b58_decode(&b58_encode(&raw)).unwrap_or_default(), raw);
}
}
#[test]
fn base58_refuses_what_is_not_in_its_alphabet() {
for text in ["", "0", "O", "I", "l", "+", "z0", "é"] {
assert_eq!(b58_decode(text), None, "{text:?}");
}
}
}