Skip to main content

crypto_dispatch/
validation.rs

1// SPDX-FileCopyrightText: Copyright © 2026 ReallyMe LLC. All rights reserved
2//
3// SPDX-License-Identifier: Apache-2.0
4
5use crate::AlgorithmError;
6use codec_multikey::{parse_multikey, validate_key_binding, KeyBindingInput};
7use crypto_core::Algorithm;
8
9/// Structural validation of a typed public-key binding.
10///
11/// This performs NO cryptography.
12/// It checks:
13/// - multikey encoding
14/// - codec ↔ algorithm match
15/// - key length
16pub fn validate_verification_method_multikey(
17    algorithm: Algorithm,
18    binding_type: &str,
19    public_key_multibase: &str,
20) -> Result<(), AlgorithmError> {
21    let parsed =
22        parse_multikey(public_key_multibase).map_err(|_| AlgorithmError::InvalidKey(algorithm))?;
23
24    // Validate that the declared binding label is compatible with the key algorithm.
25    validate_key_binding(
26        KeyBindingInput {
27            binding_type,
28            algorithm: Some(algorithm.as_str()),
29        },
30        &parsed,
31    )
32    .map_err(|_| AlgorithmError::InvalidKey(algorithm))?;
33
34    // Enforce key length expectations
35    let expected_len = match algorithm {
36        Algorithm::Ed25519 => 32,
37        Algorithm::X25519 => 32,
38        Algorithm::P256 => 33,
39        Algorithm::P384 => crypto_p384::P384_PUBLIC_KEY_COMPRESSED_LEN,
40        Algorithm::P521 => crypto_p521::P521_PUBLIC_KEY_COMPRESSED_LEN,
41        Algorithm::Secp256k1 => 33,
42        Algorithm::MlDsa44 => 1312,
43        Algorithm::MlDsa65 => 1952,
44        Algorithm::MlDsa87 => 2592,
45        Algorithm::MlKem512 => 800,
46        Algorithm::MlKem768 => 1184,
47        Algorithm::MlKem1024 => 1568,
48        Algorithm::XWing768 => crypto_x_wing::X_WING_768_PUBLIC_KEY_LEN,
49        Algorithm::XWing1024 => crypto_x_wing::X_WING_1024_PUBLIC_KEY_LEN,
50    };
51
52    if parsed.public_key.len() != expected_len {
53        return Err(AlgorithmError::InvalidKey(algorithm));
54    }
55
56    Ok(())
57}