1"""Signer utils for internal use."""
2
3from __future__ import annotations
4
5import hashlib
6from typing import Any
7
8from securesystemslib.exceptions import FormatError
9from securesystemslib.formats import encode_canonical
10
11
12def compute_default_keyid(keytype: str, scheme: str, keyval: dict[str, Any]) -> str:
13 """Return sha256 hexdigest of the canonical json of the key."""
14 data: str | None = encode_canonical(
15 {
16 "keytype": keytype,
17 "scheme": scheme,
18 "keyval": keyval,
19 }
20 )
21 if isinstance(data, str):
22 byte_data: bytes = data.encode("utf-8")
23 else:
24 raise FormatError("Failed to encode data into canonical json")
25
26 return hashlib.sha256(byte_data).hexdigest()
27
28
29def get_mldsa_payload(data: bytes, version: int) -> bytes:
30 """Compute and format ML-DSA payload per TAP 21 spec."""
31 if version != 1:
32 raise ValueError(f"Unsupported ml-dsa key version {version}")
33
34 # Version 1 uses SHA-512
35 return b"tuf" + bytes([version]) + hashlib.sha512(data).digest()