febrezo

NTC_gen.py Generador de Números de Tarjetas de Crédito

Apr 22nd, 2012
1,166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.13 KB | None | 0 0
  1. # -*- coding: cp1252 -*-
  2. ##==============================================================================##
  3. ##                                          ##
  4. ##    Copyright 2012 Félix Brezo (febrezo @ www.felixbrezo.com)                 ##
  5. ##                                      ##
  6. ##    This program is free software: you can redistribute it and/or modify  ##
  7. ##    it under the terms of the GNU General Public License as published by  ##
  8. ##    the Free Software Foundation, either version 3 of the License, or     ##
  9. ##    (at your option) any later version.                   ##
  10. ##                                      ##
  11. ##    Sira is distributed in the hope that it will be useful,           ##
  12. ##    but WITHOUT ANY WARRANTY; without even the implied warranty of        ##
  13. ##    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the     ##
  14. ##    GNU General Public License for more details.              ##
  15. ##                                      ##
  16. ##    You should have received a copy of the GNU General Public License     ##
  17. ##    along with numtarcre_gen.py.  If not, see <http://www.gnu.org/licenses/>. ##
  18. ##                                      ##
  19. ##    Additional comments by the author:                    ##
  20. ##    ----------------------------------                    ##
  21. ##  En.:    This script was coded only for educational purpouses to show    ##
  22. ##        the characteristics of the validation algorithms linked to    ##
  23. ##        credit-cards.                         ##
  24. ##      The use or missuse of this script is responsible of the final   ##
  25. ##        user.                             ##
  26. ##      The author condemns any illegal use of this script and      ##
  27. ##        encourages its users to pursue and inform the corresponding   ##
  28. ##         authorities about the use of this code.          ##
  29. ##  Es.:    Este script ha sido codificado solamente con fines educativos   ##
  30. ##        para mostrar las características intrínsecas de los           ##
  31. ##        algoritmos de generación de números de tarjetas de crédito.   ##
  32. ##      El uso o mal uso de este script es responsabilidad única de     ##
  33. ##        su usuario final.                     ##
  34. ##      El autor condena cualquier uso ilegal de este script y      ##
  35. ##        anima a sus usuarios a poner en mano de la justicia       ##
  36. ##        cualquier uso ilegal del mismo.               ##
  37. ##                                      ##
  38. ##==============================================================================##
  39.  
  40. import sys
  41. import argparse
  42. import random
  43.  
  44. parser = argparse.ArgumentParser(description='Generador y verificador de la validez de números de tarjeta de crédito.', prog='NTC_GEN.py')
  45. grFunction = parser.add_mutually_exclusive_group()
  46. grFunction.add_argument('-g', '--generador', metavar='CANT_NUM', type=int, required=False, help='para indicar el total de números de tarjeta a generar.')
  47. grFunction.add_argument('-c', '--comprobante', metavar='NUM_TAR', required=False, help = 'para especificar: a) el número de tarjeta individual a verificar (admite como carácter separador el guión (-)) o b), si existe fichero de entrada, la verificación del fichero de entrada')
  48. parser.add_argument('-i', '--inicio', metavar='ID_CIA', required=False, help='para establecer el número (o números) iniciales de las tarjetas a generar (3xx..x - American Express, 4xx..x - Visa, 5xx..x - MasterCard, 6xx..x - Discover).')
  49. parser.add_argument('-f', '--fichero', metavar='FICH_I/O', required=False, help='para determinar el nombre del fichero de entrada/salida.')
  50. parser.add_argument('-q', '--quiet', required=False, action='store_true', default=False, help = 'para no mostrar ninguna salida en la consola.')
  51. parser.add_argument('-s', '--separador', metavar='CARAC', required=False, default='-', help = 'para indicar un carácter de separación diferente a \'-\'.')
  52. parser.add_argument('-v', '--verbose', required=False, action='store_true', default=False, help = 'para mostrar detalles de ejecución en pantalla.')
  53. parser.add_argument('--version', action='version', version='%(prog)s 1.0')
  54. args = parser.parse_args()
  55.  
  56. if not args.quiet:
  57.     print "Iniciando el NTC_GEN.py..."
  58.  
  59. if not args.quiet:
  60.     print "Definiendo procedimientos auxiliares..."
  61. # ----------------------
  62. # - Métodos auxiliares -
  63. # ----------------------
  64. # Método auxiliar para tokenizar el número de tarjeta dado por parámetro. Return <nIm, nPa>.
  65. #   Nota: admite como carácter separador el guión (-)
  66. def parsear(parNumTar):
  67.     # si no se ha facilitado cabecera
  68.     if not parNumTar:  
  69.         return [], []
  70.     nIm = []
  71.     nPa = []
  72.     aux = ""
  73.     for k in range(len(parNumTar.split(args.separador))):
  74.         aux += parNumTar.split(args.separador)[k]  
  75.     for i in range(len(aux)):
  76.         if i%2 == 0:
  77.             #ojo índice 0 = impar
  78.             nIm.append(int(aux[i]))
  79.         else:
  80.             #ojo índice 1 = par
  81.             nPa.append(int(aux[i]))
  82.     return nIm, nPa
  83.  
  84. # Método auxiliar para calcular la suma parcial. Recibe dos arrays de int. Return <int> .
  85. #   1.- Números impares * 2 (si > 9, se toma el resultado indivial -9)
  86. #   2.- Números pares
  87. def calcularSumaParcial(nIm, nPa):
  88.     suma = 0
  89.     for i in nIm:
  90.         c = i*2
  91.         if (i*2)>9:
  92.             suma += c-9
  93.         else:
  94.             suma += c
  95.     for i in nPa:
  96.         suma += i
  97.     return suma
  98.  
  99. # Método de verificación. Return <boolean>.
  100. #   1.- Calcula la suma total
  101. #   2.- Comprueba si es mod10=0 y <= 150
  102. def verificar(numTar):
  103.     numIm, numPa = parsear(numTar)
  104.     aux = calcularSumaParcial(numIm, numPa)
  105.     if (aux %10 == 0) & (aux <= 150):
  106.         return True
  107.     return False
  108.  
  109. # Método de generación de números aleatorios. Return <string>.
  110. #   0.- Leemos todos los números iniciales introducidos
  111. #   1.- Generamos números impares
  112. #   2.- Generamos números pares restantes - el último
  113. #   3.- Generamos el último número para que cumpla la condición de mod % 10 = 0
  114. def generarNumero(cabecera):
  115.     if args.verbose:
  116.         print ("\tGenerando un nuevo número de tarjeta...")
  117.     numIm, numPa = parsear(cabecera)
  118.     # generamos números impares
  119.     for i in range(8-len(numIm)):
  120.         numIm.append(random.randrange(0,10))
  121.     # calculamos la suma parcial
  122.     suma = calcularSumaParcial(numIm, numPa)
  123.     # calculamos los números que faltan por generar
  124.     faltan = 8-len(numPa)
  125.     # generamos números aleatorios
  126.     for i in range(faltan-1):  
  127.         n = random.randrange(0,10)
  128.         suma += n
  129.         numPa.append(n)
  130.     # el último número lo generamos a mano para que encaje
  131.     num = 10-(suma%10)
  132.     # comprobación para evitar añadir un '10' al final, en lugar de '0'
  133.     if num == 10:
  134.         num = 0
  135.     numPa.append(num)
  136.    
  137.     n = ""
  138.     for i in range(8):
  139.         n += str(numIm[i])+str(numPa[i])
  140.     if args.verbose:
  141.         print "\tNúmero generado:\t"+n
  142.     return n
  143.  
  144. # -------------------
  145. # - Parte principal -
  146. # -------------------
  147. try:
  148.     if args.comprobante:
  149.         #verificador
  150.         if not args.quiet:
  151.             print "Rama de verificación..."
  152.         if args.fichero:
  153.             tarVer = {}
  154.             if not args.quiet:
  155.                 print "Leyendo el fichero "+args.fichero+"..."
  156.             f = open (args.fichero, "r")
  157.             contenido = f.readlines()
  158.             for linea in contenido:
  159.                 num = linea[:len(linea)-1]
  160.                 if num not in tarVer:
  161.                     tarVer[num]=verificar(num)
  162.                     if args.verbose:
  163.                         print "La validez del número de tarjeta "+num+"es:\t"+str(tarVer[num])
  164.             f.close()
  165.             if not args.quiet:
  166.                 print "Escribiendo en el fichero ver_"+args.fichero+"..."
  167.             s = open ("ver_"+args.fichero, "w")
  168.             for num in tarVer:
  169.                 s.write(str(num)+"\t"+str(tarVer[num])+"\n")
  170.             s.close()
  171.         else:
  172.             print "La validez del número de tarjeta "+args.comprobante+" es:\t"+str(verificar(args.comprobante))
  173.     else:
  174.         #generador
  175.         if not args.quiet:
  176.             print "Rama de generación..."
  177.  
  178.         numGenerados = []
  179.  
  180.         completado=0
  181.  
  182.         # bucle de generación de tarjetas
  183.         for i in range(args.generador):
  184.             nuevo = generarNumero(args.inicio)
  185.             while nuevo in numGenerados:
  186.                 nuevo = generarNumero(args.inicio) 
  187.             numGenerados.append(nuevo)
  188.             # mostrar mensaje de estado
  189.             if int(float(i+1)/float(args.generador)*100) > completado:
  190.                 completado = int(float(i+1)/float(args.generador)*100)
  191.                 if not args.quiet:
  192.                     print "Estado del proceso de generación:\t"+str(completado).rjust(3)+"%"
  193.         if args.fichero:
  194.             if not args.quiet:
  195.                 print "Escribiendo fichero de salida en "+args.fichero+"..."
  196.             f = open (args.fichero, "w")
  197.             for num in numGenerados:
  198.                 f.write(str(num)+"\n")
  199.             f.close()
  200. except Exception:
  201.     print "ERROR INESPERADO: algo ha ido mal... Revisa los parámetros de entrada:\n", sys.exc_info()[0]
  202.     print "Si aún así no sabes qué ha ido mal, consúltame en www.felixbrezo.com o en twitter (@febrezo)."
  203.     parser.print_help()
Add Comment
Please, Sign In to add comment