use ed25519_dalek::{Signer, SigningKey, VerifyingKey};
use crate::errors::{Error, Kind, Result};
const CODE: u8 = b'B';
const RAW_LEN: usize = 32;
const QB64_LEN: usize = 44;
pub(crate) const URL_ALPHABET: &[u8; 64] =
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
const STD_ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
pub(crate) fn encode(raw: &[u8], alphabet: &[u8; 64], pad: bool) -> String {
let mut out = String::with_capacity(raw.len().div_ceil(3) * 4);
for chunk in raw.chunks(3) {
let b = [
chunk[0],
*chunk.get(1).unwrap_or(&0),
*chunk.get(2).unwrap_or(&0),
];
let n = (b[0] as u32) << 16 | (b[1] as u32) << 8 | b[2] as u32;
out.push(alphabet[(n >> 18) as usize & 63] as char);
out.push(alphabet[(n >> 12) as usize & 63] as char);
if chunk.len() > 1 {
out.push(alphabet[(n >> 6) as usize & 63] as char);
} else if pad {
out.push('=');
}
if chunk.len() > 2 {
out.push(alphabet[n as usize & 63] as char);
} else if pad {
out.push('=');
}
}
out
}
pub(crate) fn decode(text: &str, alphabet: &[u8; 64]) -> Option<Vec<u8>> {
let mut lookup = [255u8; 256];
for (i, ch) in alphabet.iter().enumerate() {
lookup[*ch as usize] = i as u8;
}
let trimmed = text.trim_end_matches('=');
if text.len() - trimmed.len() > 2 || trimmed.len() % 4 == 1 {
return None;
}
let mut out = Vec::with_capacity(trimmed.len() / 4 * 3);
for chunk in trimmed.as_bytes().chunks(4) {
let mut n: u32 = 0;
for (i, ch) in chunk.iter().enumerate() {
let v = lookup[*ch as usize];
if v == 255 {
return None;
}
n |= (v as u32) << (18 - 6 * i);
}
out.push((n >> 16) as u8);
if chunk.len() > 2 {
out.push((n >> 8) as u8);
}
if chunk.len() > 3 {
out.push(n as u8);
}
}
Some(out)
}
pub(crate) fn b64url(raw: &[u8]) -> String {
encode(raw, URL_ALPHABET, false)
}
pub(crate) fn b64std(raw: &[u8]) -> String {
encode(raw, STD_ALPHABET, true)
}
pub(crate) fn b64std_decode(text: &str) -> Option<Vec<u8>> {
decode(text, STD_ALPHABET)
}
pub fn to_aid(raw: &[u8]) -> Result<String> {
let raw: &[u8; RAW_LEN] = raw.try_into().map_err(|_| {
Error::new(
Kind::InvalidArgument,
format!(
"An Ed25519 public key is {RAW_LEN} bytes; this one is {}, so it has no AID.",
raw.len()
),
)
})?;
Ok(aid_of(raw))
}
pub(crate) fn aid_of(raw: &[u8; RAW_LEN]) -> String {
let mut padded = [0u8; RAW_LEN + 1];
padded[1..].copy_from_slice(raw);
let mut aid = b64url(&padded);
aid.replace_range(0..1, "B");
aid
}
pub fn verifying_key(aid: &str) -> Result<VerifyingKey> {
if aid.len() != QB64_LEN || aid.as_bytes()[0] != CODE {
return Err(Error::detailed(
Kind::MalformedKey,
"A non-transferable AID is 44 characters beginning with \"B\"; this one is not.",
aid,
));
}
if !aid.bytes().all(|b| URL_ALPHABET.contains(&b)) {
return Err(Error::detailed(
Kind::MalformedKey,
format!("The AID {aid} is not valid base64url."),
aid,
));
}
let decoded = decode(&format!("A{}", &aid[1..]), URL_ALPHABET).ok_or_else(|| {
Error::detailed(
Kind::MalformedKey,
format!("The AID {aid} is not valid base64url."),
aid,
)
})?;
let bytes: [u8; RAW_LEN] = decoded[1..].try_into().map_err(|_| {
Error::detailed(
Kind::MalformedKey,
format!("The AID {aid} does not decode to a key."),
aid,
)
})?;
if aid_of(&bytes) != aid {
return Err(Error::detailed(
Kind::MalformedKey,
format!("The AID {aid} is not the canonical spelling of its key."),
aid,
));
}
public_key(&bytes).ok_or_else(|| {
Error::detailed(
Kind::MalformedKey,
format!("The AID {aid} is not a usable Ed25519 public key."),
aid,
)
})
}
pub(crate) fn public_key(raw: &[u8; RAW_LEN]) -> Option<VerifyingKey> {
if !y_below_prime(raw) {
return None;
}
VerifyingKey::from_bytes(raw)
.ok()
.filter(|key| !key.is_weak())
}
pub(crate) fn y_below_prime(raw: &[u8; RAW_LEN]) -> bool {
!(raw[31] & 0x7f == 0x7f && raw[1..31].iter().all(|b| *b == 0xff) && raw[0] >= 0xed)
}
pub struct Key {
signing: SigningKey,
}
impl std::fmt::Debug for Key {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Key")
.field("aid", &self.aid())
.finish_non_exhaustive()
}
}
impl Key {
pub fn generate() -> Self {
Key {
signing: SigningKey::generate(&mut rand_core::OsRng),
}
}
pub fn from_seed(seed: &[u8]) -> Result<Self> {
let bytes: [u8; RAW_LEN] = seed.try_into().map_err(|_| {
Error::new(
Kind::MalformedKey,
format!("An Ed25519 seed is 32 bytes; this one is {}.", seed.len()),
)
})?;
Ok(Key {
signing: SigningKey::from_bytes(&bytes),
})
}
pub fn from_openssh(text: &str) -> Result<Self> {
Ok(Key {
signing: SigningKey::from_bytes(&crate::openssh::read_openssh(text)?),
})
}
pub fn aid(&self) -> String {
aid_of(self.signing.verifying_key().as_bytes())
}
pub fn keyid(&self) -> String {
b64url(self.signing.verifying_key().as_bytes())
}
pub fn seed(&self) -> [u8; RAW_LEN] {
self.signing.to_bytes()
}
pub fn sign(&self, data: &[u8]) -> [u8; 64] {
self.signing.sign(data).to_bytes()
}
}
const SPELLED_CODES: &[u8] = b"BDE";
pub(crate) fn well_formed_aid(keyid: &str) -> bool {
if keyid.len() != QB64_LEN || !SPELLED_CODES.contains(&keyid.as_bytes()[0]) {
return false;
}
match decode(&format!("A{}", &keyid[1..]), URL_ALPHABET) {
Some(mut decoded) => {
decoded[0] = 0;
b64url(&decoded).get(1..) == keyid.get(1..)
}
None => false,
}
}
pub(crate) fn raw_keyid(keyid: &str) -> Option<[u8; RAW_LEN]> {
if keyid.len() != 43 || !keyid.bytes().all(|b| URL_ALPHABET.contains(&b)) {
return None;
}
let raw: [u8; RAW_LEN] = decode(keyid, URL_ALPHABET)?.try_into().ok()?;
(b64url(&raw) == keyid).then_some(raw)
}