pqbox 1.1.0

Post-quantum crypto toolkit: hybrid ML-KEM-1024 + P-384 sealed boxes, composite ML-DSA-87 signatures, an opt-in paranoid suite adding Classic McEliece and SLH-DSA, AEAD, KDF, hashing and Argon2id
Documentation
//! Building blocks the suites use, exposed for known-answer testing.
//!
//! These are thin wrappers over `x25519-dalek`, `ed25519-dalek`, `p384` and `ml-dsa` with the
//! exact checks the suites apply (the same functions the suites call). They are not meant for
//! building protocols: use [`crate::kem`], [`crate::sign`] and [`crate::seal`] instead.

use ml_dsa::{EncodedVerifyingKey, MlDsa65, MlDsa87, MlDsaParams, SigningKey as MlSigningKey, VerifyingKey};
use x25519_dalek::{PublicKey as XPublicKey, StaticSecret};
use zeroize::Zeroizing;

use crate::{Error, Result, Rng};

/// X25519 (RFC 7748) that rejects non-contributory results: an all-zero shared secret, which a
/// low-order public key produces, is an error.
///
/// # Errors
/// [`Error::InvalidKey`] when the result is all zeros.
pub fn x25519(secret: &[u8; 32], public: &[u8; 32]) -> Result<Zeroizing<[u8; 32]>> {
    let sk = StaticSecret::from(*secret);
    let ss = sk.diffie_hellman(&XPublicKey::from(*public));
    if ss.was_contributory() {
        let mut out = Zeroizing::new([0u8; 32]);
        out.copy_from_slice(ss.as_bytes());
        Ok(out)
    } else {
        Err(Error::InvalidKey)
    }
}

/// The X25519 public key of `secret`.
#[must_use]
pub fn x25519_public(secret: &[u8; 32]) -> [u8; 32] {
    XPublicKey::from(&StaticSecret::from(*secret)).to_bytes()
}

/// Rejects low-order X25519 public keys: any clamped scalar (a multiple of the cofactor) maps
/// them to zero.
///
/// # Errors
/// [`Error::InvalidKey`] for a low-order point.
pub fn x25519_check_public(public: &[u8; 32]) -> Result<()> {
    x25519(&[0x55; 32], public).map(|_| ())
}

/// Strict Ed25519 verification (`ed25519-dalek`'s `verify_strict`: canonical encodings, no
/// small-order public keys or `R`), as used by the hybrid signatures.
#[must_use]
pub fn ed25519_verify(public: &[u8; 32], message: &[u8], signature: &[u8; 64]) -> bool {
    match ed25519_dalek::VerifyingKey::from_bytes(public) {
        Ok(vk) => vk
            .verify_strict(message, &ed25519_dalek::Signature::from_bytes(signature))
            .is_ok(),
        Err(_) => false,
    }
}

/// ECDH over P-384 as the `pqbox-max` and `pqbox-paranoid` KEMs run it: the peer point must be an
/// uncompressed SEC1 encoding (97 bytes) of a point on the curve other than the identity. Returns
/// the 48-byte x-coordinate.
///
/// # Errors
/// [`Error::InvalidKey`] for an invalid scalar or point.
pub fn ecdh_p384(secret: &[u8; 48], public: &[u8]) -> Result<Zeroizing<[u8; 48]>> {
    let sk = p384::SecretKey::from_slice(secret).map_err(|_| Error::InvalidKey)?;
    let pk = crate::kem::p384_point(public)?;
    let ss = sk.diffie_hellman(&pk);
    let mut out = Zeroizing::new([0u8; 48]);
    out.copy_from_slice(ss.raw_secret_bytes());
    Ok(out)
}

/// ECDSA P-384 with SHA-384 verification as the composite signatures run it: uncompressed SEC1
/// public key, fixed 96-byte `r || s` signature, and `s` in the lower half of the group order
/// (the high-`s` twin of a valid signature is refused).
#[must_use]
pub fn ecdsa_p384_verify(public: &[u8], message: &[u8], signature: &[u8]) -> bool {
    crate::sign::p384_vk(public).is_ok_and(|vk| crate::sign::ecdsa_p384_verify(&vk, message, signature))
}

fn mldsa_key<P: MlDsaParams>(seed: &[u8; 32]) -> MlSigningKey<P> {
    let xi = Zeroizing::new(ml_dsa::B32::from(*seed));
    MlSigningKey::from_seed(&xi)
}

fn mldsa_verify<P: MlDsaParams>(public: &[u8], message: &[u8], ctx: &[u8], signature: &[u8]) -> bool {
    EncodedVerifyingKey::<P>::try_from(public)
        .is_ok_and(|enc| crate::sign::mldsa_verify(&VerifyingKey::<P>::decode(&enc), message, ctx, signature))
}

/// The ML-DSA-65 public key of the key pair derived from the 32-byte seed `xi` (FIPS 204
/// ML-DSA.KeyGen_internal), as in the `xwing` suite's signing keys.
#[must_use]
pub fn mldsa65_public_key(seed: &[u8; 32]) -> Vec<u8> {
    crate::sign::mldsa_public_key(&mldsa_key::<MlDsa65>(seed))
}

/// The ML-DSA-87 public key of the key pair derived from the 32-byte seed `xi`, as in the
/// `pqbox-max` and `pqbox-paranoid` signing keys.
#[must_use]
pub fn mldsa87_public_key(seed: &[u8; 32]) -> Vec<u8> {
    crate::sign::mldsa_public_key(&mldsa_key::<MlDsa87>(seed))
}

/// ML-DSA-65 signing (FIPS 204 ML-DSA.Sign, external interface, pure) with the key derived from
/// `seed`, as the `xwing` composite signatures run it: `rnd` is 32 bytes drawn from `rng`, so an
/// RNG that yields zeros gives the deterministic variant.
///
/// # Errors
/// [`Error::InvalidParams`] when `ctx` is longer than 255 bytes.
pub fn mldsa65_sign<R: Rng + ?Sized>(seed: &[u8; 32], message: &[u8], ctx: &[u8], rng: &mut R) -> Result<Vec<u8>> {
    crate::sign::mldsa_sign(&mldsa_key::<MlDsa65>(seed), message, ctx, rng)
}

/// ML-DSA-87 signing, as [`mldsa65_sign`], as the `pqbox-max` and `pqbox-paranoid` composite
/// signatures run it.
///
/// # Errors
/// [`Error::InvalidParams`] when `ctx` is longer than 255 bytes.
pub fn mldsa87_sign<R: Rng + ?Sized>(seed: &[u8; 32], message: &[u8], ctx: &[u8], rng: &mut R) -> Result<Vec<u8>> {
    crate::sign::mldsa_sign(&mldsa_key::<MlDsa87>(seed), message, ctx, rng)
}

/// ML-DSA-65 verification (FIPS 204 ML-DSA.Verify, external interface, pure) of an encoded
/// signature under an encoded public key, as the `xwing` composite signatures run it.
#[must_use]
pub fn mldsa65_verify(public: &[u8], message: &[u8], ctx: &[u8], signature: &[u8]) -> bool {
    mldsa_verify::<MlDsa65>(public, message, ctx, signature)
}

/// ML-DSA-87 verification, as [`mldsa65_verify`], as the `pqbox-max` and `pqbox-paranoid`
/// composite signatures run it.
#[must_use]
pub fn mldsa87_verify(public: &[u8], message: &[u8], ctx: &[u8], signature: &[u8]) -> bool {
    mldsa_verify::<MlDsa87>(public, message, ctx, signature)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_util::hex;

    /// RFC 7748, section 6.1.
    #[test]
    fn rfc7748_diffie_hellman() {
        let a: [u8; 32] = hex("77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a")
            .try_into()
            .unwrap();
        let b: [u8; 32] = hex("5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb")
            .try_into()
            .unwrap();
        assert_eq!(
            x25519_public(&a).to_vec(),
            hex("8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a")
        );
        assert_eq!(
            x25519_public(&b).to_vec(),
            hex("de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f")
        );
        let k = hex("4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742");
        assert_eq!(x25519(&a, &x25519_public(&b)).unwrap().to_vec(), k);
        assert_eq!(x25519(&b, &x25519_public(&a)).unwrap().to_vec(), k);
    }

    #[test]
    fn low_order_points_are_rejected() {
        // The zero point and the point of order 1 (u = 1).
        assert_eq!(x25519_check_public(&[0u8; 32]), Err(Error::InvalidKey));
        let mut one = [0u8; 32];
        one[0] = 1;
        assert_eq!(x25519_check_public(&one), Err(Error::InvalidKey));
        x25519_check_public(&x25519_public(&[7u8; 32])).unwrap();
    }
}