use crate::{
Algorithm, Error, Result,
composite::{PublicKeyBytes, derive_public_key},
};
use cipher::cipher::common::Generate;
use core::fmt;
use ctutils::{Choice, CtEq};
use encoding::{CheckedSum, Decode, Decoder, Encode, MpintRef, Reader, Writer};
use ml_dsa::{EncodedVerifyingKey, MlDsa87, Seed};
use p384::elliptic_curve::sec1::ToSec1Point;
use rand_core::CryptoRng;
use signature::KeypairRef;
use zeroize::Zeroizing;
const POINT_SIZE: usize = 97;
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct MlDsa87P384PublicKey {
pub(super) mldsa: PublicKeyBytes<MlDsa87>,
pub(super) p384: p384::Sec1Point,
}
impl MlDsa87P384PublicKey {
pub const BYTE_SIZE: usize = size_of::<EncodedVerifyingKey<MlDsa87>>() + 4 + POINT_SIZE;
#[must_use]
pub fn algorithm(&self) -> Algorithm {
Algorithm::MlDsa87P384
}
}
impl Decode for MlDsa87P384PublicKey {
type Error = Error;
fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self> {
reader.read_prefixed(|reader| {
if reader.remaining_len() != Self::BYTE_SIZE {
return Err(encoding::Error::Length.into());
}
let mut mldsa = PublicKeyBytes::<MlDsa87>::default();
reader.read(mldsa.as_mut_slice())?;
let point = reader.read_prefixed(<[u8; POINT_SIZE]>::decode)?;
let p384 = p384::Sec1Point::from_bytes(point)?;
p384::PublicKey::try_from(&p384).map_err(|_| Error::PublicKey)?;
Ok(Self { mldsa, p384 })
})
}
}
impl Encode for MlDsa87P384PublicKey {
fn encoded_len(&self) -> encoding::Result<usize> {
Ok(4 + Self::BYTE_SIZE)
}
fn encode(&self, writer: &mut impl Writer) -> encoding::Result<()> {
Self::BYTE_SIZE.encode(writer)?;
writer.write(self.mldsa.as_slice())?;
self.p384.as_bytes().encode(writer)
}
}
#[derive(Clone)]
pub struct MlDsa87P384PrivateKey {
pub(super) mldsa: Zeroizing<Seed>,
pub(super) p384: p384::SecretKey,
}
impl MlDsa87P384PrivateKey {
#[must_use]
pub fn new(mldsa: Seed, p384: p384::SecretKey) -> Self {
Self {
mldsa: Zeroizing::new(mldsa),
p384,
}
}
pub fn random<R: CryptoRng + ?Sized>(rng: &mut R) -> Self {
let mut seed = Seed::default();
rng.fill_bytes(&mut seed);
Self::new(seed, p384::SecretKey::generate_from_rng(rng))
}
#[must_use]
pub fn public_key(&self) -> MlDsa87P384PublicKey {
MlDsa87P384PublicKey {
mldsa: derive_public_key::<MlDsa87>(&self.mldsa),
p384: self.p384.public_key().to_sec1_point(false),
}
}
pub(crate) fn checkint_bytes(&self) -> &[u8] {
self.mldsa.as_slice()
}
}
impl Decode for MlDsa87P384PrivateKey {
type Error = Error;
fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self> {
reader.read_prefixed(|reader| {
let mut mldsa = Seed::default();
reader.read(&mut mldsa)?;
if reader.remaining_len() > 4 + 1 + size_of::<p384::FieldBytes>() {
return Err(encoding::Error::Length.into());
}
let mut bytes = Zeroizing::new(p384::FieldBytes::default());
reader.read_mpint_bytes(&mut bytes)?;
let p384 = p384::SecretKey::from_bytes(&bytes).map_err(|_| Error::Crypto)?;
Ok(Self::new(mldsa, p384))
})
}
}
impl Encode for MlDsa87P384PrivateKey {
fn encoded_len(&self) -> encoding::Result<usize> {
let bytes = Zeroizing::new(self.p384.to_bytes());
[
4,
size_of::<Seed>(),
MpintRef::from_bytes(&bytes)?.encoded_len()?,
]
.checked_sum()
}
fn encode(&self, writer: &mut impl Writer) -> encoding::Result<()> {
let bytes = Zeroizing::new(self.p384.to_bytes());
let d = MpintRef::from_bytes(&bytes)?;
[size_of::<Seed>(), d.encoded_len()?]
.checked_sum()?
.encode(writer)?;
writer.write(self.mldsa.as_slice())?;
d.encode(writer)
}
}
impl CtEq for MlDsa87P384PrivateKey {
fn ct_eq(&self, other: &Self) -> Choice {
self.mldsa.as_slice().ct_eq(other.mldsa.as_slice())
& Choice::from(u8::from(self.p384 == other.p384))
}
}
impl PartialEq for MlDsa87P384PrivateKey {
fn eq(&self, other: &Self) -> bool {
self.ct_eq(other).into()
}
}
impl Eq for MlDsa87P384PrivateKey {}
impl fmt::Debug for MlDsa87P384PrivateKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("MlDsa87P384PrivateKey")
.finish_non_exhaustive()
}
}
#[derive(Clone, Debug, Encode)]
pub struct MlDsa87P384Keypair {
public: MlDsa87P384PublicKey,
private: MlDsa87P384PrivateKey,
}
impl MlDsa87P384Keypair {
pub fn random<R: CryptoRng + ?Sized>(rng: &mut R) -> Self {
MlDsa87P384PrivateKey::random(rng).into()
}
#[must_use]
pub fn algorithm(&self) -> Algorithm {
self.public.algorithm()
}
#[must_use]
pub fn private(&self) -> &MlDsa87P384PrivateKey {
&self.private
}
}
impl From<MlDsa87P384PrivateKey> for MlDsa87P384Keypair {
fn from(private: MlDsa87P384PrivateKey) -> Self {
Self {
public: private.public_key(),
private,
}
}
}
impl AsRef<MlDsa87P384PublicKey> for MlDsa87P384Keypair {
fn as_ref(&self) -> &MlDsa87P384PublicKey {
&self.public
}
}
impl KeypairRef for MlDsa87P384Keypair {
type VerifyingKey = MlDsa87P384PublicKey;
}
impl From<MlDsa87P384Keypair> for MlDsa87P384PublicKey {
fn from(keypair: MlDsa87P384Keypair) -> Self {
keypair.public
}
}
impl From<&MlDsa87P384Keypair> for MlDsa87P384PublicKey {
fn from(keypair: &MlDsa87P384Keypair) -> Self {
keypair.public.clone()
}
}
impl CtEq for MlDsa87P384Keypair {
fn ct_eq(&self, other: &Self) -> Choice {
self.private.ct_eq(&other.private)
}
}
impl PartialEq for MlDsa87P384Keypair {
fn eq(&self, other: &Self) -> bool {
self.ct_eq(other).into()
}
}
impl Eq for MlDsa87P384Keypair {}
impl Decode for MlDsa87P384Keypair {
type Error = Error;
fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self> {
let public = MlDsa87P384PublicKey::decode(reader)?;
let private = MlDsa87P384PrivateKey::decode(reader)?;
if private.public_key() != public {
return Err(Error::PublicKey);
}
Ok(Self { public, private })
}
}