Created
November 19, 2020 14:25
-
-
Save maxpietsch/c4e8c7588c4c8069b561c0d782f9ac5b to your computer and use it in GitHub Desktop.
check dHCP subject ID for validity.
This file contains 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/env python3 | |
# check subject ID for validity. | |
usage=""" | |
usage: | |
is_valid_id.py <dhcp_subject_id> | |
example: ./is_valid_id.py CC01253XX08 | |
No output if valid, stdout and nonzero exit if not valid | |
""" | |
def valid_dhcp_checksum (pid, verbose=True): | |
# luhnCheckFast | |
# converted from http://dev.paediatrics.co.uk/connectome/ | |
if len(pid) < 11: | |
if verbose: print ("Invalid study ID (too short)") | |
return False | |
if len(pid) > 11: | |
if verbose: print ("Invalid study ID (too long)") | |
return False | |
numeric = [int(x) for x in filter( lambda x: x in '0123456789', pid )] | |
mid_id = numeric[:-2] | |
luhn_id = numeric[-2:] | |
ca = 0 | |
sm = 0 | |
mul = 1 | |
for i in mid_id: | |
ca = i * mul | |
sm += ca - (ca>9)*9 | |
mul ^= 3 | |
return sm == numeric[-2] * 10 + numeric[-1] | |
if __name__ == '__main__': | |
import sys | |
if len(sys.argv) != 2: | |
print (usage) | |
sys.exit() | |
if not valid_dhcp_checksum((sys.argv[1].lstrip('sub-'))): | |
sys.exit(sys.argv[1] + " is not a valid study ID") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment