mod p256;
pub use self::p256::*;
#[cfg(feature = "ring")]
mod ring;
#[cfg(feature = "ring")]
pub use self::ring::*;
use core::fmt;
use rand_core::{CryptoRng, RngCore};
pub struct PublicKey(pub [u8; 64]);
pub struct SharedSecret(pub [u8; 32]);
#[derive(Debug)]
pub struct InvalidPublicKey {}
impl InvalidPublicKey {
pub fn new() -> Self {
Self {}
}
}
impl fmt::Display for InvalidPublicKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("invalid public key")
}
}
pub trait EcdhProvider {
type SecretKey: SecretKey;
fn generate_keypair<R>(&mut self, rng: &mut R) -> (Self::SecretKey, PublicKey)
where
R: RngCore + CryptoRng;
}
pub trait SecretKey: Sized {
fn agree(self, foreign_key: &PublicKey) -> Result<SharedSecret, InvalidPublicKey>;
}
pub fn run_tests(mut provider: impl EcdhProvider) {
static RNG: &[u8] = &[
0x1e, 0x66, 0x81, 0xb6, 0xa3, 0x4e, 0x06, 0x97, 0x75, 0xbe, 0xd4, 0x5c, 0xf9, 0x52, 0x3f,
0xf1, 0x5b, 0x6a, 0x72, 0xe2, 0xb8, 0x35, 0xb3, 0x29, 0x5e, 0xe0, 0xbb, 0x92, 0x35, 0xa5,
0xb9, 0x60, 0xc9, 0xaf, 0xe2, 0x72, 0x12, 0xf1, 0xc4, 0xfc, 0x10, 0x2d, 0x63, 0x2f, 0x05,
0xd6, 0xe5, 0x0a, 0xbf, 0x2c, 0xb9, 0x02, 0x3a, 0x67, 0x23, 0x63, 0x36, 0x7a, 0x62, 0xe6,
0x63, 0xce, 0x28, 0x98,
];
struct Rng(&'static [u8]);
impl RngCore for Rng {
fn next_u32(&mut self) -> u32 {
rand_core::impls::next_u32_via_fill(self)
}
fn next_u64(&mut self) -> u64 {
rand_core::impls::next_u64_via_fill(self)
}
fn fill_bytes(&mut self, dest: &mut [u8]) {
if self.0.len() < dest.len() {
panic!("p256::run_tests: ran out of pregenerated entropy");
}
for chunk in dest.chunks_mut(self.0.len()) {
chunk.copy_from_slice(&self.0[..chunk.len()]);
self.0 = &self.0[chunk.len()..];
}
}
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> {
self.fill_bytes(dest);
Ok(())
}
}
impl CryptoRng for Rng {}
let mut rng = Rng(RNG);
let (secret1, public1) = provider.generate_keypair(&mut rng);
let (secret2, public2) = provider.generate_keypair(&mut rng);
assert_ne!(&public1.0[..], &public2.0[..]);
let shared1 = secret1.agree(&public2).unwrap();
let shared2 = secret2.agree(&public1).unwrap();
assert_eq!(shared1.0, shared2.0);
let infty = PublicKey([0; 64]);
let (secret, _) = provider.generate_keypair(&mut Rng(RNG));
assert!(secret.agree(&infty).is_err());
let x = [
0xb7, 0x0b, 0xf0, 0x43, 0xc1, 0x44, 0x93, 0x57, 0x56, 0xf8, 0xf4, 0x57, 0x8c, 0x36, 0x9c,
0xf9, 0x60, 0xee, 0x51, 0x0a, 0x5a, 0x0f, 0x90, 0xe9, 0x3a, 0x37, 0x3a, 0x21, 0xf0, 0xd1,
0x39, 0x7f,
];
let y = [
0x4a, 0x2e, 0x0d, 0xed, 0x57, 0xa5, 0x15, 0x6b, 0xb8, 0x2e, 0xb4, 0x31, 0x4c, 0x37, 0xfd,
0x41, 0x55, 0x39, 0x5a, 0x7e, 0x51, 0x98, 0x8a, 0xf2, 0x89, 0xcc, 0xe5, 0x31, 0xb9, 0xc1,
0x71, 0x92,
];
let mut key = [0; 64];
key[..32].copy_from_slice(&x);
key[32..].copy_from_slice(&y);
let (secret, _) = provider.generate_keypair(&mut Rng(RNG));
assert!(secret.agree(&PublicKey(key)).is_err());
}