noirci-bench / pii /checksums.py
5000.dev
Noirci Bench : benchmark PII francais, avec son outil de mesure
7ba64dc
Raw
History Blame Contribute Delete
4.46 kB
"""Validateurs et generateurs d'identifiants francais a checksum.
Ces fonctions servent deux usages :
- generation de PII valides pour le corpus synthetique (bench)
- plus tard, la couche A de detection (un match regex + checksum OK = decision)
"""
import random
import string
# ---------------------------------------------------------------- Luhn (CB, SIREN, SIRET)
def luhn_checksum(digits: str) -> int:
total = 0
for i, ch in enumerate(reversed(digits)):
d = int(ch)
if i % 2 == 1:
d *= 2
if d > 9:
d -= 9
total += d
return total % 10
def luhn_valid(digits: str) -> bool:
return digits.isdigit() and luhn_checksum(digits) == 0
def _luhn_complete(prefix: str) -> str:
"""Ajoute le digit de controle rendant prefix+d valide au sens de Luhn."""
check = (10 - luhn_checksum(prefix + "0")) % 10
return prefix + str(check)
def gen_siren(rng: random.Random) -> str:
return _luhn_complete("".join(rng.choices(string.digits, k=8)))
def gen_siret(rng: random.Random, siren: str | None = None) -> str:
"""SIRET = SIREN + NIC (5 chiffres), le tout valide Luhn sur 14 chiffres."""
siren = siren or gen_siren(rng)
nic4 = "".join(rng.choices(string.digits, k=4))
return _luhn_complete(siren + nic4)
def siren_valid(s: str) -> bool:
return len(s) == 9 and luhn_valid(s)
def siret_valid(s: str) -> bool:
return len(s) == 14 and luhn_valid(s)
def gen_carte_bancaire(rng: random.Random) -> str:
prefix = rng.choice(["4", "51", "52", "53", "54", "55"]) # Visa / MC
body = "".join(rng.choices(string.digits, k=15 - len(prefix)))
return _luhn_complete(prefix + body)
# ---------------------------------------------------------------- NIR (n° de securite sociale)
_NIR_DEPTS = [f"{d:02d}" for d in range(1, 96) if d != 20] + ["2A", "2B", "97"]
def nir_key(nir13: str) -> int:
"""Cle = 97 - (NIR mod 97). Corse : 2A -> -1e6, 2B -> -2e6 sur le nombre."""
s = nir13.upper()
if "A" in s:
n = int(s.replace("A", "0")) - 1_000_000
elif "B" in s:
n = int(s.replace("B", "0")) - 2_000_000
else:
n = int(s)
return 97 - (n % 97)
def gen_nir(rng: random.Random) -> str:
"""NIR complet 15 caracteres (13 + cle), checksum valide, Corse incluse."""
sexe = rng.choice("12")
annee = f"{rng.randint(0, 99):02d}"
mois = f"{rng.randint(1, 12):02d}"
dept = rng.choice(_NIR_DEPTS)
commune = f"{rng.randint(1, 990):03d}"
ordre = f"{rng.randint(1, 999):03d}"
nir13 = sexe + annee + mois + dept + commune + ordre
return nir13 + f"{nir_key(nir13):02d}"
def nir_valid(s: str) -> bool:
s = s.replace(" ", "").upper()
if len(s) != 15:
return False
nir13, key = s[:13], s[13:]
if not key.isdigit():
return False
core = nir13.replace("A", "").replace("B", "")
if not core.isdigit() or len(core) < 12:
return False
return nir_key(nir13) == int(key)
# ---------------------------------------------------------------- IBAN
def _iban_mod97(iban: str) -> int:
rearranged = iban[4:] + iban[:4]
num = "".join(str(int(c, 36)) for c in rearranged)
return int(num) % 97
def iban_valid(s: str) -> bool:
s = s.replace(" ", "").upper()
if len(s) < 15 or not s[:2].isalpha() or not s[2:4].isdigit():
return False
return _iban_mod97(s) == 1
def gen_iban_fr(rng: random.Random) -> str:
"""IBAN FR : FRkk BBBBB GGGGG CCCCCCCCCCC KK (cle RIB + cle IBAN valides)."""
banque = "".join(rng.choices(string.digits, k=5))
guichet = "".join(rng.choices(string.digits, k=5))
compte = "".join(rng.choices(string.digits, k=11))
cle_rib = 97 - ((89 * int(banque) + 15 * int(guichet) + 3 * int(compte)) % 97)
bban = f"{banque}{guichet}{compte}{cle_rib:02d}"
check = 98 - _iban_mod97(f"FR00{bban}")
return f"FR{check:02d}{bban}"
# ---------------------------------------------------------------- TVA intracommunautaire FR
def gen_tva_fr(rng: random.Random, siren: str | None = None) -> str:
siren = siren or gen_siren(rng)
key = (12 + 3 * (int(siren) % 97)) % 97
return f"FR{key:02d}{siren}"
def tva_fr_valid(s: str) -> bool:
s = s.replace(" ", "").upper()
if len(s) != 13 or not s.startswith("FR") or not s[2:].isdigit():
return False
siren = s[4:]
return int(s[2:4]) == (12 + 3 * (int(siren) % 97)) % 97 and siren_valid(siren)