msr90

- Documentation & Code Examples for the MSR90 Magnetic Strip Card Reader 💳
git clone git://git.acid.vegas/msr90.git
Log | Files | Refs | Archive | README | LICENSE

luhn_algo.py (911B)

      1 #!/usr/bin/env python
      2 # Luhn Algorithm Example - Developed by acidvegas in Python (https://git.acid.vegas/msr90)
      3 
      4 def modulo10(card_number: str) -> str:
      5 	'''
      6 	Validate a card number using the Luhn Algorithm
      7 
      8 	:param card_number: The card number to validate
      9 	'''
     10 
     11 	digits = [int(d) for d in card_number]
     12 	total_sum = 0
     13 
     14 	for i, digit in enumerate(reversed(digits)):
     15 		if i % 2 == 0:
     16 			digit = digit * 2
     17 
     18 			if digit > 9:
     19 				digit -= 9
     20 
     21 		total_sum += digit
     22 
     23 	check_digit = (10 - total_sum % 10) % 10
     24 	full_card_number = card_number + str(check_digit)
     25 
     26 	if (total_sum + check_digit) % 10 != 0:
     27 		raise ValueError('failed luhn check (non-divisible by 10)')
     28 
     29 	return full_card_number
     30 
     31 
     32 if __name__ == '__main__':
     33 	card_number = input('Enter your card number without the last digit: ')
     34 
     35 	if not card_number.isdigit():
     36 		raise ValueError('invalid card number')
     37 
     38 	print(f'Full card number: {modulo10(card_number)}')