Skulaurun

Python Credit Card Number Generator

Jun 12th, 2021
1,369
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # Copyright (c) 2021 Adam Charvát
  2.  
  3. # Visa
  4. # - MII: 4
  5. # - IIN: (4)
  6. # - Length: 13 or 16 digits
  7.  
  8. # Mastercard
  9. # - MII: 5
  10. # - IIN: (51 - 55)
  11. # - Length: 16 digits
  12.  
  13. # American Express
  14. # - MII: 3
  15. # - IIN: (34, 37)
  16. # - Length: 15 digits
  17.  
  18. import random
  19. from enum import Enum
  20.  
  21. class Card(Enum):
  22.     Visa = 0
  23.     Mastercard = 1
  24.     AmericanExpress = 2
  25.  
  26. def computeCheckDigit(cardNumber):
  27.     total = 0
  28.     digits = cardNumber[::-1]
  29.     for i in range(len(digits)):
  30.         digit = int(digits[i])
  31.         if i % 2 == 0:
  32.             digit *= 2
  33.         total += sum(map(int, str(digit)))
  34.     return (total * 9) % 10
  35.  
  36. def fillToLength(text, length):
  37.     toAdd = length - len(text)
  38.     for _ in range(toAdd):
  39.         text += str(random.randint(0, 9))
  40.     return text
  41.  
  42. def genCardNumber(cardType):
  43.     if cardType == Card.Visa:
  44.         length = 16
  45.         prefix = str(4)
  46.     elif cardType == Card.Mastercard:
  47.         length = 16
  48.         prefix = str(random.randint(51, 55))
  49.     elif cardType == Card.AmericanExpress:
  50.         length = 15
  51.         prefix = str(random.choice([34, 37]))
  52.     else:
  53.         raise Exception("Invalid card type!")
  54.     cardNumber = fillToLength(prefix, length - 1)
  55.     return cardNumber + str(computeCheckDigit(cardNumber))
  56.  
  57. print("Visa: " + genCardNumber(Card.Visa))
  58. print("Mastercard: " + genCardNumber(Card.Mastercard))
  59. print("American Express: " + genCardNumber(Card.AmericanExpress))
  60.  
RAW Paste Data