Created
June 25, 2025 16:26
-
-
Save bhattisatish/4eddc599bc3d03d8dae3dac17ef0114a to your computer and use it in GitHub Desktop.
Python code to generate the MRZ from the passport data. It also corrects a padding error
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
| from itertools import cycle | |
| def add_checksum(value): | |
| s = sum( | |
| w * int(v, 36) for i, (v, w) in enumerate(zip(value, cycle([7, 3, 1]))) | |
| ) | |
| return f"{value}{s % 10}" | |
| def mrz(pp_nr, dob, expiry, sex, country): | |
| """ | |
| Machine-readable zone of passport. dob and expiry are formatted as YYMMDD. | |
| sex is M, F, or <. country is a 3-letter code. | |
| """ | |
| pp_cs = add_checksum(pp_nr) | |
| dob_cs = add_checksum(dob) | |
| expiry_cs = add_checksum(expiry) | |
| mrz_cs = add_checksum(f"{pp_cs}{dob_cs}{expiry_cs}") | |
| return f"{pp_cs}{country}{dob_cs}{sex}{expiry_cs}{mrz_cs[-1]:<>16}" | |
| print(mrz("123456789", "841213", "220229", "M", "XXX")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment