Files
opaque-vx/src/key_exchange/group/x25519.rs
T

52 lines
1.6 KiB
Rust
Raw Normal View History

2021-10-25 02:54:32 -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.
2021-10-25 02:54:32 -07:00
2022-01-04 00:50:40 +01:00
//! Key Exchange group implementation for X25519
2021-10-25 02:54:32 -07:00
use super::KeGroup;
use crate::errors::InternalError;
use generic_array::{typenum::U32, GenericArray};
use rand::{CryptoRng, RngCore};
2022-01-04 00:50:40 +01:00
use x25519_dalek::{PublicKey, StaticSecret};
2021-10-25 02:54:32 -07:00
/// The implementation of such a subgroup for Ristretto
2022-01-04 00:50:40 +01:00
impl KeGroup for PublicKey {
2021-10-25 02:54:32 -07:00
type PkLen = U32;
type SkLen = U32;
fn from_pk_slice(element_bits: &GenericArray<u8, Self::PkLen>) -> Result<Self, InternalError> {
2022-01-04 00:50:40 +01:00
Ok(Self::from(<[u8; 32]>::from(*element_bits)))
2021-10-25 02:54:32 -07:00
}
fn random_sk<R: RngCore + CryptoRng>(rng: &mut R) -> GenericArray<u8, Self::SkLen> {
2022-01-04 00:50:40 +01:00
let mut scalar_bytes = [0u8; 32];
2021-10-25 02:54:32 -07:00
2022-01-04 00:50:40 +01:00
loop {
rng.fill_bytes(&mut scalar_bytes);
2021-10-25 02:54:32 -07:00
2022-01-04 00:50:40 +01:00
if scalar_bytes != [0u8; 32] {
break StaticSecret::from(scalar_bytes).to_bytes().into();
2021-10-25 02:54:32 -07:00
}
}
}
fn public_key(sk: &GenericArray<u8, Self::SkLen>) -> Self {
2022-01-04 00:50:40 +01:00
Self::from(&StaticSecret::from(<[u8; 32]>::from(*sk)))
2021-10-25 02:54:32 -07:00
}
fn to_arr(&self) -> GenericArray<u8, Self::PkLen> {
self.to_bytes().into()
}
2022-01-04 00:50:40 +01:00
fn diffie_hellman(&self, sk: &GenericArray<u8, Self::SkLen>) -> GenericArray<u8, Self::SkLen> {
StaticSecret::from(<[u8; 32]>::from(*sk))
.diffie_hellman(self)
.to_bytes()
.into()
2021-10-25 02:54:32 -07:00
}
}