Files
opaque-vx/src/keypair.rs
T

384 lines
12 KiB
Rust
Raw Normal View History

2023-05-22 23:04:26 -07:00
// Copyright (c) Meta Platforms, Inc. and affiliates.
2020-06-05 09:35:14 -07:00
//
2023-05-22 23:04:26 -07:00
// This source code is dual-licensed under either the MIT license found in the
// LICENSE-MIT file in the root directory of this source tree or the Apache
2021-12-03 14:38:11 -08:00
// License, Version 2.0 found in the LICENSE-APACHE file in the root directory
2023-05-22 23:04:26 -07:00
// of this source tree. You may select, at your option, one of the above-listed
// licenses.
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
use crate::errors::ProtocolError;
2022-01-06 06:19:02 +01:00
use crate::key_exchange::group::KeGroup;
use crate::key_exchange::tripledh::DiffieHellman;
2022-01-06 06:19:02 +01:00
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)]
pub struct KeyPair<KG: KeGroup, S: Clone = PrivateKey<KG>> {
2021-10-25 02:54:32 -07:00
pk: PublicKey<KG>,
sk: S,
2021-01-25 13:20:36 -08:00
}
2020-06-05 09:35:14 -07:00
impl<KG: KeGroup, S: Clone> KeyPair<KG, S> {
/// Creates a new [`KeyPair`] from the given keys.
pub fn new(sk: S, pk: PublicKey<KG>) -> Self {
Self { pk, sk }
}
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
}
}
2021-10-25 02:54:32 -07:00
impl<KG: KeGroup> KeyPair<KG> {
/// Generating a random key pair given a cryptographic rng
pub(crate) fn generate_random<CS: voprf::CipherSuite, R: RngCore + CryptoRng>(
rng: &mut R,
2025-04-15 22:31:37 +02:00
) -> Self {
let mut scalar_bytes = GenericArray::<_, <KG as KeGroup>::SkLen>::default();
rng.fill_bytes(&mut scalar_bytes);
2025-04-15 22:31:37 +02:00
let sk = KG::derive_auth_keypair::<CS>(scalar_bytes).unwrap();
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
2023-10-08 21:48:43 +02:00
/// [`Self::generate_random`]
fn uniform_keypair_strategy<CS: voprf::CipherSuite>() -> proptest::prelude::BoxedStrategy<Self>
{
2021-08-17 05:11:53 +02:00
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);
Some(Self::generate_random::<CS, _>(&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
impl<KG: KeGroup> PrivateKey<KG> {
/// Returns public key from private key
pub fn public_key(&self) -> PublicKey<KG> {
PublicKey(KG::public_key(self.0))
}
pub(crate) fn serialize(&self) -> GenericArray<u8, KG::SkLen> {
KG::serialize_sk(self.0)
}
2021-07-20 11:49:37 +02:00
/// Creates a [`PrivateKey`] from the given bytes.
pub fn deserialize(input: &[u8]) -> Result<Self, ProtocolError> {
KG::deserialize_sk(input).map(Self)
}
}
impl<KG: KeGroup> PrivateKey<KG>
where
KG::Sk: DiffieHellman<KG>,
{
/// Diffie-Hellman key exchange implementation
pub(crate) fn ke_diffie_hellman(&self, pk: &PublicKey<KG>) -> GenericArray<u8, KG::PkLen> {
self.0.diffie_hellman(pk.0)
}
}
/// A trait to facilitate
/// [`ServerSetup::de/serialize`](crate::ServerSetup::serialize).
pub trait PrivateKeySerialization<KG: KeGroup>: Clone {
/// Custom error type that can be passed down to `ProtocolError::Custom`
type Error;
/// Serialization size in bytes.
type Len: ArrayLength<u8>;
/// Serialization into bytes
fn serialize_key_pair(key_pair: &KeyPair<KG, Self>) -> GenericArray<u8, Self::Len>;
/// Deserialization from bytes
fn deserialize_key_pair(input: &[u8]) -> Result<KeyPair<KG, Self>, ProtocolError<Self::Error>>;
}
impl<KG: KeGroup> PrivateKeySerialization<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
fn serialize_key_pair(key_pair: &KeyPair<KG, Self>) -> GenericArray<u8, Self::Len> {
key_pair.private().serialize()
}
fn deserialize_key_pair(input: &[u8]) -> Result<KeyPair<KG, Self>, ProtocolError> {
let sk = PrivateKey::deserialize(input)?;
let pk = sk.public_key();
Ok(KeyPair::new(sk, pk))
2022-04-02 01:10:00 +02:00
}
}
#[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
pub fn deserialize(key_bytes: &[u8]) -> Result<Self, ProtocolError> {
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
}
/// Returns the inner [`KeGroup::Pk`].
pub fn to_group_type(&self) -> KG::Pk {
self.0
}
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::*;
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>();
2023-03-06 20:28:19 +01:00
inner::<::p384::NistP384>();
2023-11-16 20:07:46 +01:00
inner::<::p521::NistP521>();
}
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::<$point>()) {
2022-01-04 00:50:40 +01:00
let pk = kp.public();
let sk = kp.private();
prop_assert_eq!(&sk.public_key(), pk);
2022-01-04 00:50:40 +01:00
}
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::<$point>(),
kp2 in KeyPair::<$point>::uniform_keypair_strategy::<$point>()) {
2020-06-12 18:46:08 -04:00
let dh1 = kp2.private().ke_diffie_hellman(&kp1.public());
let dh2 = kp1.private().ke_diffie_hellman(kp2.public());
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::<$point>()) {
2022-02-25 07:13:22 +01:00
let sk_bytes = kp.private().serialize().to_vec();
let kp2 = PrivateKey::<$point>::deserialize_key_pair(&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);
2023-03-06 20:28:19 +01:00
test!(p384, ::p384::NistP384);
2023-11-16 20:07:46 +01:00
test!(p521, ::p521::NistP521);
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
const PASSWORD: &str = "password";
let sk = PrivateKey(KeCurve::random_sk(&mut OsRng));
let pk = sk.public_key();
let sk = RemoteKey(sk);
let keypair = KeyPair::new(sk, pk);
2021-07-20 14:16:59 +02:00
let server_setup =
ServerSetup::<Default, RemoteKey>::new_with_key_pair(&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();
let builder = ServerLogin::builder(
2021-07-20 14:16:59 +02:00
&mut OsRng,
&server_setup,
Some(file),
message,
&[],
ServerLoginStartParameters::default(),
2021-08-12 06:25:07 +02:00
)
.unwrap();
let shared_secret = builder.private_key().0.ke_diffie_hellman(builder.data());
let ServerLoginStartResult {
message,
state: server,
..
} = builder.build(shared_secret).unwrap();
2021-08-12 06:25:07 +02:00
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
}
}