Created
December 20, 2016 13:49
-
-
Save LLCampos/ea03a095d68f66662eec8ee2d2c9cc75 to your computer and use it in GitHub Desktop.
My implementation of a random generator of valid credit card numbers
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
from numpy import random | |
def luhn_checksum(n): | |
"""Calculates Luhn's Checksum of a number. n must be a string. | |
Check Wikipedia to understand the algorithm.""" | |
even = 0 | |
odd = 1 | |
# If number has an even length, you double the digits in odd indexes. | |
# Otherwise, you double the digits in even indexes | |
if len(n) % 2 == 0: | |
to_double = odd | |
else: | |
to_double = even | |
sum_digits = [] | |
for i in range(len(n)): | |
if (i + 1) % 2 == to_double: | |
sum_digit = (int(n[i]) * 2) % 9 | |
sum_digits.append(sum_digit) | |
else: | |
sum_digits.append(int(n[i])) | |
return sum(sum_digits) % 10 | |
def is_luhn_valid(n): | |
return luhn_checksum(n) == 0 | |
def generate(prefix, credit_card_number_length): | |
"""Generate a valid credit card number with length | |
'credit_card_number_length' and prefix 'prefix'. | |
'prefix' must be a string.""" | |
len_check_digit = 1 | |
id_length = credit_card_number_length - len(prefix) - len_check_digit | |
array_random_int_digits = random.choice(range(0, 10), id_length) | |
random_id = ''.join(map(lambda x: str(x), array_random_int_digits)) | |
check_digit = '0' | |
cc_number = prefix + random_id + check_digit | |
cc_checksum = luhn_checksum(cc_number) | |
if cc_checksum != 0: | |
check_digit = str(10 - cc_checksum) | |
cc_number = cc_number[:-1] + check_digit | |
return cc_number | |
# Sanity check tests | |
prefix = "372542" | |
for i in range(1, 1000): | |
n = generate(prefix, len(prefix) + i) | |
assert is_luhn_valid(n) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment