use crate::{
Algorithm, Error, Result,
composite::{PublicKeyBytes, derive_public_key},
private::Ed25519PrivateKey,
public::Ed25519PublicKey,
};
use core::fmt;
use ctutils::{Choice, CtEq};
use encoding::{CheckedSum, Decode, Decoder, Encode, Reader, Writer};
use ml_dsa::{EncodedSignature, EncodedVerifyingKey, MlDsa44, Seed};
use rand_core::CryptoRng;
use signature::{Keypair, KeypairRef};
use zeroize::Zeroizing;
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub struct MlDsa44Ed25519PublicKey {
pub(super) mldsa: PublicKeyBytes<MlDsa44>,
ed25519: Ed25519PublicKey,
}
impl MlDsa44Ed25519PublicKey {
pub const BYTE_SIZE: usize =
size_of::<EncodedVerifyingKey<MlDsa44>>() + Ed25519PublicKey::BYTE_SIZE;
pub const SIGNATURE_SIZE: usize =
size_of::<EncodedSignature<MlDsa44>>() + ed25519_dalek::SIGNATURE_LENGTH;
pub fn new(key: impl AsRef<[u8]>) -> Result<Self> {
Self::decode_bytes(&mut Decoder::from_bytes(key.as_ref())?)
}
#[must_use]
pub fn algorithm(&self) -> Algorithm {
Algorithm::MlDsa44Ed25519
}
#[must_use]
pub fn ed25519(&self) -> &Ed25519PublicKey {
&self.ed25519
}
#[cfg(feature = "alloc")]
#[must_use]
pub fn to_bytes(&self) -> Vec<u8> {
let mut bytes = Vec::with_capacity(Self::BYTE_SIZE);
bytes.extend_from_slice(self.mldsa.as_slice());
bytes.extend_from_slice(self.ed25519.as_ref());
bytes
}
fn decode_bytes(reader: &mut Decoder<impl Reader>) -> Result<Self> {
if reader.remaining_len() != Self::BYTE_SIZE {
return Err(encoding::Error::Length.into());
}
let mut mldsa = PublicKeyBytes::<MlDsa44>::default();
reader.read(mldsa.as_mut_slice())?;
let ed25519 = Ed25519PublicKey(Decode::decode(reader)?);
Ok(Self { mldsa, ed25519 })
}
}
impl TryFrom<&[u8]> for MlDsa44Ed25519PublicKey {
type Error = Error;
fn try_from(bytes: &[u8]) -> Result<Self> {
Self::new(bytes)
}
}
impl Decode for MlDsa44Ed25519PublicKey {
type Error = Error;
fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self> {
reader.read_prefixed(Self::decode_bytes)
}
}
impl Encode for MlDsa44Ed25519PublicKey {
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())?;
writer.write(self.ed25519.as_ref())
}
}
impl fmt::Display for MlDsa44Ed25519PublicKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for byte in self.mldsa.as_slice() {
write!(f, "{byte:02x}")?;
}
write!(f, "{:x}", self.ed25519)
}
}
#[derive(Clone)]
pub struct MlDsa44Ed25519PrivateKey {
pub(super) mldsa: Zeroizing<Seed>,
ed25519: Ed25519PrivateKey,
}
impl MlDsa44Ed25519PrivateKey {
pub const BYTE_SIZE: usize = size_of::<Seed>() + Ed25519PrivateKey::BYTE_SIZE;
pub fn random<R: CryptoRng + ?Sized>(rng: &mut R) -> Result<Self> {
let mut seed = Zeroizing::new([0u8; Self::BYTE_SIZE]);
rng.fill_bytes(seed.as_mut_slice());
Self::from_bytes(&seed)
}
pub fn from_bytes(bytes: &[u8; Self::BYTE_SIZE]) -> Result<Self> {
let (mldsa, ed25519) = bytes.split_at(size_of::<Seed>());
Ok(Self {
mldsa: Zeroizing::new(mldsa.try_into()?),
ed25519: ed25519.try_into()?,
})
}
#[must_use]
pub fn to_bytes(&self) -> [u8; Self::BYTE_SIZE] {
let mut bytes = [0u8; Self::BYTE_SIZE];
let (mldsa, ed25519) = bytes.split_at_mut(size_of::<Seed>());
mldsa.copy_from_slice(self.mldsa.as_slice());
ed25519.copy_from_slice(self.ed25519.as_ref());
bytes
}
#[must_use]
pub fn ed25519(&self) -> &Ed25519PrivateKey {
&self.ed25519
}
pub fn public_key(&self) -> Result<MlDsa44Ed25519PublicKey> {
Ok(MlDsa44Ed25519PublicKey {
mldsa: derive_public_key::<MlDsa44>(&self.mldsa),
ed25519: Ed25519PublicKey::from(&self.ed25519),
})
}
pub(crate) fn checkint_bytes(&self) -> &[u8] {
self.mldsa.as_slice()
}
}
impl TryFrom<&[u8]> for MlDsa44Ed25519PrivateKey {
type Error = Error;
fn try_from(bytes: &[u8]) -> Result<Self> {
Self::from_bytes(bytes.try_into()?)
}
}
impl CtEq for MlDsa44Ed25519PrivateKey {
fn ct_eq(&self, other: &Self) -> Choice {
self.mldsa.as_slice().ct_eq(other.mldsa.as_slice()) & self.ed25519.ct_eq(&other.ed25519)
}
}
impl Eq for MlDsa44Ed25519PrivateKey {}
impl PartialEq for MlDsa44Ed25519PrivateKey {
fn eq(&self, other: &Self) -> bool {
self.ct_eq(other).into()
}
}
impl fmt::Debug for MlDsa44Ed25519PrivateKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("MlDsa44Ed25519PrivateKey")
.finish_non_exhaustive()
}
}
#[derive(Clone)]
pub struct MlDsa44Ed25519Keypair {
pub public: MlDsa44Ed25519PublicKey,
pub private: MlDsa44Ed25519PrivateKey,
}
impl MlDsa44Ed25519Keypair {
pub fn random<R: CryptoRng + ?Sized>(rng: &mut R) -> Result<Self> {
Self::new(MlDsa44Ed25519PrivateKey::random(rng)?)
}
pub fn from_seed(seed: &[u8; MlDsa44Ed25519PrivateKey::BYTE_SIZE]) -> Result<Self> {
Self::new(MlDsa44Ed25519PrivateKey::from_bytes(seed)?)
}
#[must_use]
pub fn algorithm(&self) -> Algorithm {
self.public.algorithm()
}
fn new(private: MlDsa44Ed25519PrivateKey) -> Result<Self> {
Ok(Self {
public: private.public_key()?,
private,
})
}
}
impl AsRef<MlDsa44Ed25519PublicKey> for MlDsa44Ed25519Keypair {
fn as_ref(&self) -> &MlDsa44Ed25519PublicKey {
&self.public
}
}
impl KeypairRef for MlDsa44Ed25519Keypair {
type VerifyingKey = MlDsa44Ed25519PublicKey;
}
impl CtEq for MlDsa44Ed25519Keypair {
fn ct_eq(&self, other: &Self) -> Choice {
Choice::from(u8::from(self.public == other.public)) & self.private.ct_eq(&other.private)
}
}
impl Eq for MlDsa44Ed25519Keypair {}
impl PartialEq for MlDsa44Ed25519Keypair {
fn eq(&self, other: &Self) -> bool {
self.ct_eq(other).into()
}
}
impl Decode for MlDsa44Ed25519Keypair {
type Error = Error;
fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self> {
let public = MlDsa44Ed25519PublicKey::decode(reader)?;
let mut seed = Zeroizing::new([0u8; MlDsa44Ed25519PrivateKey::BYTE_SIZE]);
let private =
MlDsa44Ed25519PrivateKey::try_from(reader.read_string_bytes(seed.as_mut_slice())?)?;
if private.public_key()? != public {
return Err(Error::PublicKey);
}
Ok(Self { public, private })
}
}
impl Encode for MlDsa44Ed25519Keypair {
fn encoded_len(&self) -> encoding::Result<usize> {
[
self.public.encoded_len()?,
4,
MlDsa44Ed25519PrivateKey::BYTE_SIZE,
]
.checked_sum()
}
fn encode(&self, writer: &mut impl Writer) -> encoding::Result<()> {
self.public.encode(writer)?;
MlDsa44Ed25519PrivateKey::BYTE_SIZE.encode(writer)?;
writer.write(self.private.mldsa.as_slice())?;
writer.write(self.private.ed25519.as_ref())
}
}
impl fmt::Debug for MlDsa44Ed25519Keypair {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("MlDsa44Ed25519Keypair")
.field("public", &self.public)
.finish_non_exhaustive()
}
}
impl From<MlDsa44Ed25519Keypair> for MlDsa44Ed25519PublicKey {
fn from(keypair: MlDsa44Ed25519Keypair) -> Self {
keypair.public
}
}
impl From<&MlDsa44Ed25519Keypair> for MlDsa44Ed25519PublicKey {
fn from(keypair: &MlDsa44Ed25519Keypair) -> Self {
keypair.verifying_key()
}
}