Files
opaque-vx/src/keypair.rs
T

386 lines
12 KiB
Rust
Raw Normal View History

2020-06-05 09:35:14 -07:00
// Copyright (c) Facebook, Inc. and its affiliates.
//
2021-12-03 14:38:11 -08:00
// This source code is licensed under both the MIT license found in the
// LICENSE-MIT file in the root directory of this source tree and the Apache
// License, Version 2.0 found in the LICENSE-APACHE file in the root directory
// of this source tree.
2020-06-05 09:35:14 -07:00
//! Contains the keypair types that must be supplied for the OPAQUE API
#![allow(unsafe_code)]
2022-02-25 07:13:22 +01:00
use derive_where::derive_where;
2021-07-06 13:27:13 +02:00
use generic_array::{ArrayLength, GenericArray};
2021-02-11 18:10:48 -08:00
use rand::{CryptoRng, RngCore};
2020-06-05 09:35:14 -07:00
2022-01-06 06:19:02 +01:00
use crate::errors::{InternalError, ProtocolError};
use crate::key_exchange::group::KeGroup;
2020-06-05 09:35:14 -07:00
/// A Keypair trait with public-private verification
2021-07-06 14:17:44 +02:00
#[cfg_attr(
2022-01-04 00:50:40 +01:00
feature = "serde",
2022-04-02 01:10:00 +02:00
derive(serde::Deserialize, serde::Serialize),
2023-02-04 22:25:41 +01:00
serde(bound(
deserialize = "S: serde::Deserialize<'de>",
serialize = "S: serde::Serialize"
))
2021-07-06 14:17:44 +02:00
)]
2022-02-25 07:13:22 +01:00
#[derive_where(Clone)]
#[derive_where(Debug, Eq, Hash, Ord, PartialEq, PartialOrd; KG::Pk, S)]
2021-10-25 02:54:32 -07:00
pub struct KeyPair<KG: KeGroup, S: SecretKey<KG> = PrivateKey<KG>> {
pk: PublicKey<KG>,
sk: S,
2021-01-25 13:20:36 -08:00
}
2020-06-05 09:35:14 -07:00
2021-10-25 02:54:32 -07:00
impl<KG: KeGroup, S: SecretKey<KG>> KeyPair<KG, S> {
2020-06-05 09:35:14 -07:00
/// The public key component
2021-10-25 02:54:32 -07:00
pub fn public(&self) -> &PublicKey<KG> {
2021-01-25 13:20:36 -08:00
&self.pk
}
2020-06-05 09:35:14 -07:00
/// The private key component
pub fn private(&self) -> &S {
2021-01-25 13:20:36 -08:00
&self.sk
}
2020-06-05 09:35:14 -07:00
/// Obtains a KeyPair from a slice representing the private key
2021-07-20 11:49:37 +02:00
pub fn from_private_key_slice(input: &[u8]) -> Result<Self, ProtocolError<S::Error>> {
2021-07-20 14:16:53 +02:00
Self::from_private_key(S::deserialize(input)?)
}
/// Obtains a KeyPair from a private key
pub fn from_private_key(sk: S) -> Result<Self, ProtocolError<S::Error>> {
let pk = sk.public_key()?;
2021-07-06 14:17:44 +02:00
Ok(Self { pk, sk })
}
}
2021-10-25 02:54:32 -07:00
impl<KG: KeGroup> KeyPair<KG> {
/// Generating a random key pair given a cryptographic rng
2022-01-04 00:50:40 +01:00
pub(crate) fn generate_random<R: RngCore + CryptoRng>(rng: &mut R) -> Self {
2021-10-25 02:54:32 -07:00
let sk = KG::random_sk(rng);
2022-04-02 01:10:00 +02:00
let pk = KG::public_key(sk);
2022-01-04 00:50:40 +01:00
Self {
2022-02-25 07:13:22 +01:00
pk: PublicKey(pk),
sk: PrivateKey(sk),
2022-01-04 00:50:40 +01:00
}
}
}
2021-08-17 05:11:53 +02:00
#[cfg(test)]
2022-02-25 07:13:22 +01:00
impl<KG: KeGroup> KeyPair<KG>
where
KG::Pk: std::fmt::Debug,
KG::Sk: std::fmt::Debug,
{
/// Test-only strategy returning a proptest Strategy based on
/// generate_random
2021-08-17 05:11:53 +02:00
fn uniform_keypair_strategy() -> proptest::prelude::BoxedStrategy<Self> {
use proptest::prelude::*;
2022-01-06 06:19:02 +01:00
use rand::rngs::StdRng;
use rand::SeedableRng;
2021-08-17 05:11:53 +02:00
2022-01-06 06:19:02 +01:00
// The no_shrink is because keypairs should be fixed -- shrinking would cause a
// different keypair to be generated, which appears to not be very useful.
any::<[u8; 32]>()
.prop_filter_map("valid random keypair", |seed| {
let mut rng = StdRng::from_seed(seed);
2022-01-04 00:50:40 +01:00
Some(Self::generate_random(&mut rng))
})
.no_shrink()
.boxed()
}
2020-06-05 09:35:14 -07:00
}
2021-06-15 10:48:29 +02:00
/// Wrapper around a Key to enforce that it's a private one.
2022-04-02 01:10:00 +02:00
#[derive_where(Clone, ZeroizeOnDrop)]
2022-02-25 07:13:22 +01:00
#[derive_where(Debug, Eq, Hash, Ord, PartialEq, PartialOrd; KG::Sk)]
pub struct PrivateKey<KG: KeGroup>(KG::Sk);
2021-07-06 13:27:13 +02:00
/// A trait specifying the requirements for a private key container
2022-02-25 07:13:22 +01:00
pub trait SecretKey<KG: KeGroup>: Clone + Sized {
2021-08-22 12:28:19 -07:00
/// Custom error type that can be passed down to `InternalError::Custom`
2021-07-20 11:49:37 +02:00
type Error;
2022-01-04 00:50:40 +01:00
/// Serialization size in bytes.
type Len: ArrayLength<u8>;
2021-07-20 11:49:37 +02:00
/// Diffie-Hellman key exchange implementation
2022-01-04 00:50:40 +01:00
fn diffie_hellman(
&self,
pk: PublicKey<KG>,
) -> Result<GenericArray<u8, KG::PkLen>, InternalError<Self::Error>>;
/// Returns public key from private key
2021-10-25 02:54:32 -07:00
fn public_key(&self) -> Result<PublicKey<KG>, InternalError<Self::Error>>;
/// Serialization into bytes
2022-01-04 00:50:40 +01:00
fn serialize(&self) -> GenericArray<u8, Self::Len>;
/// Deserialization from bytes
2021-08-22 12:28:19 -07:00
fn deserialize(input: &[u8]) -> Result<Self, InternalError<Self::Error>>;
}
2021-10-25 02:54:32 -07:00
impl<KG: KeGroup> SecretKey<KG> for PrivateKey<KG> {
2021-08-12 06:25:07 +02:00
type Error = core::convert::Infallible;
2022-01-04 00:50:40 +01:00
type Len = KG::SkLen;
2021-07-20 11:49:37 +02:00
2022-01-04 00:50:40 +01:00
fn diffie_hellman(
&self,
pk: PublicKey<KG>,
) -> Result<GenericArray<u8, KG::PkLen>, InternalError> {
2022-04-02 01:10:00 +02:00
Ok(KG::diffie_hellman(pk.0, self.0))
}
2021-10-25 02:54:32 -07:00
fn public_key(&self) -> Result<PublicKey<KG>, InternalError> {
2022-04-02 01:10:00 +02:00
Ok(PublicKey(KG::public_key(self.0)))
}
2022-01-04 00:50:40 +01:00
fn serialize(&self) -> GenericArray<u8, Self::Len> {
2022-04-02 01:10:00 +02:00
KG::serialize_sk(self.0)
}
2021-08-22 12:28:19 -07:00
fn deserialize(input: &[u8]) -> Result<Self, InternalError> {
2022-04-02 01:10:00 +02:00
KG::deserialize_sk(input).map(Self)
}
}
#[cfg(feature = "serde")]
impl<'de, KG: KeGroup> serde::Deserialize<'de> for PrivateKey<KG> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de::Error;
KG::deserialize_sk(&GenericArray::<_, KG::SkLen>::deserialize(deserializer)?)
.map(Self)
.map_err(D::Error::custom)
}
}
#[cfg(feature = "serde")]
impl<KG: KeGroup> serde::Serialize for PrivateKey<KG> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
KG::serialize_sk(self.0).serialize(serializer)
}
}
2021-06-15 10:48:29 +02:00
/// Wrapper around a Key to enforce that it's a public one.
2022-04-02 01:10:00 +02:00
#[derive_where(Clone, ZeroizeOnDrop)]
2022-02-25 07:13:22 +01:00
#[derive_where(Debug, Eq, Hash, Ord, PartialEq, PartialOrd; KG::Pk)]
pub struct PublicKey<KG: KeGroup>(KG::Pk);
2021-06-15 10:48:29 +02:00
2021-10-25 02:54:32 -07:00
impl<KG: KeGroup> PublicKey<KG> {
2021-08-17 05:11:53 +02:00
/// Convert from bytes
2022-04-02 01:10:00 +02:00
pub fn deserialize(key_bytes: &[u8]) -> Result<Self, InternalError> {
2022-02-25 07:13:22 +01:00
KG::deserialize_pk(key_bytes).map(Self)
}
/// Convert to bytes
2022-04-02 01:10:00 +02:00
pub fn serialize(&self) -> GenericArray<u8, KG::PkLen> {
KG::serialize_pk(self.0)
2021-06-15 10:48:29 +02:00
}
2022-04-02 01:10:00 +02:00
}
#[cfg(feature = "serde")]
impl<'de, KG: KeGroup> serde::Deserialize<'de> for PublicKey<KG> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de::Error;
KG::deserialize_pk(&GenericArray::<_, KG::PkLen>::deserialize(deserializer)?)
.map(Self)
.map_err(D::Error::custom)
}
}
2021-06-15 10:48:29 +02:00
2022-04-02 01:10:00 +02:00
#[cfg(feature = "serde")]
impl<KG: KeGroup> serde::Serialize for PublicKey<KG> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
KG::serialize_pk(self.0).serialize(serializer)
2020-06-05 09:35:14 -07:00
}
}
#[cfg(test)]
mod tests {
use rand::rngs::OsRng;
2022-01-06 06:19:02 +01:00
use super::*;
use crate::errors::*;
2022-02-25 07:13:22 +01:00
use crate::util;
#[test]
2022-02-25 07:13:22 +01:00
fn test_zeroize_key() {
2022-01-04 00:50:40 +01:00
fn inner<G: KeGroup>() {
let mut rng = OsRng;
2022-02-25 07:13:22 +01:00
let mut key = PrivateKey::<G>(G::random_sk(&mut rng));
util::test_zeroize_on_drop(&mut key);
2022-01-04 00:50:40 +01:00
}
2022-01-04 00:50:40 +01:00
#[cfg(feature = "ristretto255")]
2022-02-25 07:13:22 +01:00
inner::<crate::Ristretto255>();
inner::<::p256::NistP256>();
}
2022-01-04 00:50:40 +01:00
macro_rules! test {
($mod:ident, $point:ty) => {
mod $mod {
2022-01-06 00:10:57 +01:00
use std::format;
2022-01-06 06:19:02 +01:00
use proptest::prelude::*;
use super::*;
2022-01-04 00:50:40 +01:00
proptest! {
#[test]
fn pub_from_priv(kp in KeyPair::<$point>::uniform_keypair_strategy()) {
let pk = kp.public();
let sk = kp.private();
prop_assert_eq!(&sk.public_key()?, pk);
}
2020-06-12 18:46:08 -04:00
2022-01-04 00:50:40 +01:00
#[test]
fn dh(kp1 in KeyPair::<$point>::uniform_keypair_strategy(),
kp2 in KeyPair::<$point>::uniform_keypair_strategy()) {
2020-06-12 18:46:08 -04:00
2022-01-04 00:50:40 +01:00
let dh1 = kp2.private().diffie_hellman(kp1.public().clone())?;
let dh2 = kp1.private().diffie_hellman(kp2.public().clone())?;
2022-01-04 00:50:40 +01:00
prop_assert_eq!(dh1, dh2);
}
2022-01-04 00:50:40 +01:00
#[test]
fn private_key_slice(kp in KeyPair::<$point>::uniform_keypair_strategy()) {
2022-02-25 07:13:22 +01:00
let sk_bytes = kp.private().serialize().to_vec();
2022-01-04 00:50:40 +01:00
let kp2 = KeyPair::<$point>::from_private_key_slice(&sk_bytes)?;
2022-02-25 07:13:22 +01:00
let kp2_private_bytes = kp2.private().serialize().to_vec();
2022-01-04 00:50:40 +01:00
prop_assert_eq!(sk_bytes, kp2_private_bytes);
}
}
}
};
}
2021-07-20 14:16:59 +02:00
2022-01-04 00:50:40 +01:00
#[cfg(feature = "ristretto255")]
2022-02-25 07:13:22 +01:00
test!(ristretto, crate::Ristretto255);
test!(p256, ::p256::NistP256);
2022-01-04 00:50:40 +01:00
2021-07-20 14:16:59 +02:00
#[test]
2021-08-12 06:25:07 +02:00
fn remote_key() {
2022-01-06 06:19:02 +01:00
use rand::rngs::OsRng;
2021-07-20 14:16:59 +02:00
use crate::{
CipherSuite, ClientLogin, ClientLoginFinishParameters, ClientLoginFinishResult,
ClientLoginStartResult, ClientRegistration, ClientRegistrationFinishParameters,
ClientRegistrationFinishResult, ClientRegistrationStartResult, ServerLogin,
ServerLoginStartParameters, ServerLoginStartResult, ServerRegistration,
ServerRegistrationStartResult, ServerSetup,
};
struct Default;
impl CipherSuite for Default {
2022-01-04 00:50:40 +01:00
#[cfg(feature = "ristretto255")]
2022-04-02 01:10:00 +02:00
type OprfCs = crate::Ristretto255;
2022-01-04 00:50:40 +01:00
#[cfg(not(feature = "ristretto255"))]
2022-04-02 01:10:00 +02:00
type OprfCs = ::p256::NistP256;
2022-01-04 00:50:40 +01:00
#[cfg(feature = "ristretto255")]
2022-02-25 07:13:22 +01:00
type KeGroup = crate::Ristretto255;
2022-01-04 00:50:40 +01:00
#[cfg(not(feature = "ristretto255"))]
2022-02-25 07:13:22 +01:00
type KeGroup = ::p256::NistP256;
2022-04-02 01:10:00 +02:00
type KeyExchange = crate::key_exchange::tripledh::TripleDh;
type Ksf = crate::ksf::Identity;
2021-07-20 14:16:59 +02:00
}
2022-02-25 07:13:22 +01:00
type KeCurve = <Default as CipherSuite>::KeGroup;
#[derive(Clone)]
2022-01-04 00:50:40 +01:00
struct RemoteKey(PrivateKey<KeCurve>);
2021-07-20 14:16:59 +02:00
2022-01-04 00:50:40 +01:00
impl SecretKey<KeCurve> for RemoteKey {
2021-08-12 06:25:07 +02:00
type Error = core::convert::Infallible;
2022-01-04 00:50:40 +01:00
type Len = <KeCurve as KeGroup>::SkLen;
2021-07-20 14:16:59 +02:00
fn diffie_hellman(
&self,
2022-01-04 00:50:40 +01:00
pk: PublicKey<KeCurve>,
) -> Result<GenericArray<u8, <KeCurve as KeGroup>::PkLen>, InternalError<Self::Error>>
{
2021-07-20 14:16:59 +02:00
self.0.diffie_hellman(pk)
}
2022-01-04 00:50:40 +01:00
fn public_key(&self) -> Result<PublicKey<KeCurve>, InternalError<Self::Error>> {
2021-07-20 14:16:59 +02:00
self.0.public_key()
}
2022-01-04 00:50:40 +01:00
fn serialize(&self) -> GenericArray<u8, Self::Len> {
2021-07-20 14:16:59 +02:00
self.0.serialize()
}
2021-08-22 12:28:19 -07:00
fn deserialize(input: &[u8]) -> Result<Self, InternalError<Self::Error>> {
2021-07-20 14:16:59 +02:00
PrivateKey::deserialize(input).map(Self)
}
}
const PASSWORD: &str = "password";
2022-01-04 00:50:40 +01:00
let sk = KeCurve::random_sk(&mut OsRng);
2022-02-25 07:13:22 +01:00
let sk = RemoteKey(PrivateKey(sk));
2021-08-12 06:25:07 +02:00
let keypair = KeyPair::from_private_key(sk).unwrap();
2021-07-20 14:16:59 +02:00
2022-01-04 00:50:40 +01:00
let server_setup = ServerSetup::<Default, RemoteKey>::new_with_key(&mut OsRng, keypair);
2021-07-20 14:16:59 +02:00
let ClientRegistrationStartResult {
message,
state: client,
2021-08-12 06:25:07 +02:00
} = ClientRegistration::<Default>::start(&mut OsRng, PASSWORD.as_bytes()).unwrap();
2021-07-30 14:00:23 +02:00
let ServerRegistrationStartResult { message, .. } =
2021-08-12 06:25:07 +02:00
ServerRegistration::start(&server_setup, message, &[]).unwrap();
let ClientRegistrationFinishResult { message, .. } = client
.finish(
&mut OsRng,
2022-01-06 00:10:57 +01:00
PASSWORD.as_bytes(),
2021-08-12 06:25:07 +02:00
message,
2021-09-02 11:28:21 +02:00
ClientRegistrationFinishParameters::default(),
2021-08-12 06:25:07 +02:00
)
.unwrap();
2021-07-20 14:16:59 +02:00
let file = ServerRegistration::finish(message);
let ClientLoginStartResult {
message,
state: client,
2021-08-12 06:25:07 +02:00
} = ClientLogin::<Default>::start(&mut OsRng, PASSWORD.as_bytes()).unwrap();
2021-07-20 14:16:59 +02:00
let ServerLoginStartResult {
message,
state: server,
2021-07-30 12:54:16 +02:00
..
2021-07-20 14:16:59 +02:00
} = ServerLogin::start(
&mut OsRng,
&server_setup,
Some(file),
message,
&[],
ServerLoginStartParameters::default(),
2021-08-12 06:25:07 +02:00
)
.unwrap();
let ClientLoginFinishResult { message, .. } = client
2022-01-06 00:10:57 +01:00
.finish(
PASSWORD.as_bytes(),
message,
ClientLoginFinishParameters::default(),
)
2021-08-12 06:25:07 +02:00
.unwrap();
server.finish(message).unwrap();
2021-07-20 14:16:59 +02:00
}
}