const MOTIF_SHA256 = /^[0-9a-f]{64}$/;

/** Vrai si la chaîne est une empreinte SHA-256 en hexadécimal minuscule (64 caractères). */
export function estEmpreinteSha256(valeur: string): boolean {
  return MOTIF_SHA256.test(valeur);
}

/** Convertit une empreinte SHA-256 hexadécimale en 32 octets. Lève une erreur si elle est invalide. */
export function octetsDepuisEmpreinte(empreinteHex: string): Uint8Array {
  if (!estEmpreinteSha256(empreinteHex)) {
    throw new TypeError('Empreinte invalide : 64 caractères hexadécimaux minuscules attendus.');
  }
  const octets = new Uint8Array(32);
  for (let i = 0; i < 32; i += 1) {
    octets[i] = parseInt(empreinteHex.slice(i * 2, i * 2 + 2), 16);
  }
  return octets;
}
