DEV Community

Cover image for Credit Card Generator in Python (All Code)
Wilson Reddy
Wilson Reddy

Posted on

Credit Card Generator in Python (All Code)

If you just need a bunch of numbers use the online credit card number generator.

Python, Java, C#, PHP and Javascript programs to generate valid credit card numbers (MOD 10). Useful for testing payment systems. This generates VISA, Mastercard, Amex, and a whole bunch of others.

The Luhn algorithm, also known as the "modulus 10" algorithm, is a checksum formula used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, National Provider Identifier numbers in the United States, Canadian Social Insurance Numbers, and Israel ID Numbers.

Algorithm:

The formula verifies a number against its included check digit, which is usually appended to a partial account number to generate the full account number.

Generating check digit:

Lets assume you have a number as: 3 - 7 - 5 - 6 - 2 - 1 - 9 - 8 - 6 - 7 - X where X is the check digit.
Now starting from the rightmost digit i.e. check digit, double every second digit. New number will be: 3 - 14 - 5 - 12 - 2 - 2 - 9 - 16 - 6 - 14 - X
Now if double of a digit is more then 9, add the digits. So the number will become: 3 - 5 - 5 - 3 - 2 - 2 - 9 - 7 - 6 - 5 - X
Now add all digits. 47 + X
Multiply the non-check part by 9. So it will be 47 * 9 = 423
The unit digit in the multiplication result is the check digit. X = 3
The valid number would be 37562198673.
Validating the generated number:
You can use tools available online to validate that the number generated is valid as per Luhn's algorithm or not. You can validate the number by visiting this site.

from random import randint

cc_number = []
multiplied_by_two = []
remaining_numbers = []
new_number = ''

Ask for a first 15 digits of a card

starting_15 = input('Enter first 15 digits: ')

z = 0
y = 0

while z < 25:
for i in str(starting_15):
cc_number.append(int(i))

# extract all the numbers that have to be multiplied by 2
for i in cc_number[0:16:2]:
    i *= 2
    if len(str(i)) == 2:        # check if the multiplied number is a two digit number
        for x in str(i):        # if it is, separate them, and add them together
            y += int(str(x))
        i = y
    multiplied_by_two.append(i)
    y = 0

for i in cc_number[1:15:2]:     # extract remaining numbers
    remaining_numbers.append(i)

# Luhn's algorithm
last_digit = ((sum(multiplied_by_two) + sum(remaining_numbers)) * 9) % 10

for i in cc_number:
    new_number += str(i)

print(new_number + str(last_digit))
cc_number = []
multiplied_by_two = []
remaining_numbers = []
new_number = ''

starting_15 = int(starting_15) + randint(-15, 25)
z += 1
Enter fullscreen mode Exit fullscreen mode

Top comments (0)