-
Notifications
You must be signed in to change notification settings - Fork 0
/
luhn-valid
executable file
·43 lines (36 loc) · 1.02 KB
/
luhn-valid
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#!/usr/bin/env python
import re
import sys
from getpass import getpass
def luhn_checksum(card_number):
def digits_of(n):
return [int(d) for d in str(n)]
digits = digits_of(card_number)
odd_digits = digits[-1::-2]
even_digits = digits[-2::-2]
checksum = 0
checksum += sum(odd_digits)
for d in even_digits:
checksum += sum(digits_of(d*2))
return checksum % 10
def is_luhn_valid(card_number):
return luhn_checksum(card_number) == 0
def redacted(card_number):
if len(card_number) < 10:
return card_number
first6 = card_number[:6]
last4 = card_number[-4:]
middle = card_number[6:-4]
return first6 + '*' * len(middle) + last4
if __name__ == '__main__':
orig_number = getpass('number: ')
number = re.sub('\D+', '', orig_number)
if not number:
print 'no number provided'
sys.exit(2)
print redacted(number),
if is_luhn_valid(number):
print 'is luhn valid'
else:
print 'is NOT luhn valid'
sys.exit(1)