use ring::rand::SystemRandom;
use ring::signature::{ECDSA_P256_SHA256_ASN1_SIGNING, EcdsaKeyPair, KeyPair};
use rustls::pki_types::CertificateDer;
use rustls::pki_types::pem::PemObject;
pub const ALPHABET: &[u8; 32] = b"ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
const SPKI_HEAD: [u8; 26] = [
0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a,
0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00,
];
const NO_KEY: &str = "this box could not generate a P-256 key";
pub struct Made {
pub pkcs8: Vec<u8>,
pub spki: Vec<u8>,
}
pub fn make() -> Result<Made, String> {
let rng = SystemRandom::new();
let alg = &ECDSA_P256_SHA256_ASN1_SIGNING;
let pkcs8 = EcdsaKeyPair::generate_pkcs8(alg, &rng).map_err(|_| NO_KEY.to_owned())?;
let pair =
EcdsaKeyPair::from_pkcs8(alg, pkcs8.as_ref(), &rng).map_err(|_| NO_KEY.to_owned())?;
let mut spki = SPKI_HEAD.to_vec();
spki.extend_from_slice(pair.public_key().as_ref());
Ok(Made {
pkcs8: pkcs8.as_ref().to_vec(),
spki,
})
}
pub fn pem(label: &str, der: &[u8]) -> String {
let body = base64(der);
let lines: Vec<_> = body
.as_bytes()
.chunks(64)
.map(String::from_utf8_lossy)
.collect();
format!(
"-----BEGIN {label}-----\n{}\n-----END {label}-----\n",
lines.join("\n")
)
}
fn base64(bytes: &[u8]) -> String {
const SYMBOLS: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let symbol =
|index: u32| char::from(SYMBOLS.get((index & 63) as usize).copied().unwrap_or(b'='));
let mut text = String::new();
for chunk in bytes.chunks(3) {
let word = chunk
.iter()
.chain([0, 0].iter())
.take(3)
.fold(0u32, |word, byte| (word << 8) | u32::from(*byte));
text.push(symbol(word >> 18));
text.push(symbol(word >> 12));
text.push(if chunk.len() > 1 {
symbol(word >> 6)
} else {
'='
});
text.push(if chunk.len() > 2 { symbol(word) } else { '=' });
}
text
}
pub fn word(spki: &[u8], ca_pem: &str) -> Result<String, String> {
let ca = CertificateDer::pem_slice_iter(ca_pem.as_bytes())
.next()
.and_then(Result::ok)
.ok_or("the server's answer carried no CA certificate")?;
let mut hashed = ring::digest::Context::new(&ring::digest::SHA256);
hashed.update(spki);
hashed.update(ca.as_ref());
let digest = hashed.finish();
let bits = digest
.as_ref()
.iter()
.take(4)
.fold(0u32, |bits, byte| (bits << 8) | u32::from(*byte));
Ok((0..6)
.map(|n| {
let index = (bits >> (27 - 5 * n)) & 31;
char::from(ALPHABET.get(index as usize).copied().unwrap_or(b'?'))
})
.collect())
}
#[cfg(test)]
mod tests;