Created
April 23, 2025 09:38
-
-
Save D3Ext/7401792d394be7f4a1f24f5fc7ff46a3 to your computer and use it in GitHub Desktop.
Simple python utility capable of verifying DNI and guessing the last character
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
# Based on: https://calculadorasonline.com/calcular-la-letra-del-dni-validar-un-dni/ | |
# 1. Get the numeric part of the DNI | |
# 2. Get the remainder of: n mod 23 | |
# 3. The last character is assigned based on the remainder | |
import sys | |
def check_character(src_char, found_char): | |
if src_char == found_char: | |
print("The DNI is valid") | |
else: | |
print("The DNI is not valid") | |
if len(sys.argv) <= 2: | |
print("Usage: python3 " + sys.argv[0] + " verify <dni> \t\t(check if a DNI is valid)") | |
print("Usage: python3 " + sys.argv[0] + " guess <dni w/o char> \t(guess the last character of a DNI based on the numbers)") | |
print() | |
print("Example: python3 " + sys.argv[0] + " verify 50235402K") | |
print("Example: python3 " + sys.argv[0] + " guess 50235402") | |
sys.exit(0) | |
# Parse mode | |
mode = sys.argv[1] | |
# Parse CLI argument | |
dni = sys.argv[2] | |
# Pad DNI with zeros | |
if mode == "verify": | |
dni = dni.zfill(9) | |
# Get only the number | |
num = dni[:-1] | |
# Get only the character | |
char = dni[-1] | |
elif mode == "guess": | |
dni = dni.zfill(8) | |
num = dni | |
res = int(num) % 23 | |
match res: | |
case 0: | |
found_char = "T" | |
case 1: | |
found_char = "R" | |
case 2: | |
found_char = "W" | |
case 3: | |
found_char = "A" | |
case 4: | |
found_char = "G" | |
case 5: | |
found_char = "M" | |
case 6: | |
found_char = "Y" | |
case 7: | |
found_char = "F" | |
case 8: | |
found_char = "P" | |
case 9: | |
found_char = "D" | |
case 10: | |
found_char = "X" | |
case 11: | |
found_char = "B" | |
case 12: | |
found_char = "N" | |
case 13: | |
found_char = "J" | |
case 14: | |
found_char = "Z" | |
case 15: | |
found_char = "S" | |
case 16: | |
found_char = "Q" | |
case 17: | |
found_char = "V" | |
case 18: | |
found_char = "H" | |
case 19: | |
found_char = "L" | |
case 20: | |
found_char = "C" | |
case 21: | |
found_char = "K" | |
case 22: | |
found_char = "E" | |
if mode == "verify": | |
check_character(char, found_char) | |
elif mode == "guess": | |
print("The DNI should be: " + dni + found_char) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment