Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: cp1252 -*-
- ##==============================================================================##
- ## ##
- ## Copyright 2012 Félix Brezo (febrezo @ www.felixbrezo.com) ##
- ## ##
- ## This program is free software: you can redistribute it and/or modify ##
- ## it under the terms of the GNU General Public License as published by ##
- ## the Free Software Foundation, either version 3 of the License, or ##
- ## (at your option) any later version. ##
- ## ##
- ## Sira is distributed in the hope that it will be useful, ##
- ## but WITHOUT ANY WARRANTY; without even the implied warranty of ##
- ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ##
- ## GNU General Public License for more details. ##
- ## ##
- ## You should have received a copy of the GNU General Public License ##
- ## along with numtarcre_gen.py. If not, see <http://www.gnu.org/licenses/>. ##
- ## ##
- ## Additional comments by the author: ##
- ## ---------------------------------- ##
- ## En.: This script was coded only for educational purpouses to show ##
- ## the characteristics of the validation algorithms linked to ##
- ## credit-cards. ##
- ## The use or missuse of this script is responsible of the final ##
- ## user. ##
- ## The author condemns any illegal use of this script and ##
- ## encourages its users to pursue and inform the corresponding ##
- ## authorities about the use of this code. ##
- ## Es.: Este script ha sido codificado solamente con fines educativos ##
- ## para mostrar las características intrínsecas de los ##
- ## algoritmos de generación de números de tarjetas de crédito. ##
- ## El uso o mal uso de este script es responsabilidad única de ##
- ## su usuario final. ##
- ## El autor condena cualquier uso ilegal de este script y ##
- ## anima a sus usuarios a poner en mano de la justicia ##
- ## cualquier uso ilegal del mismo. ##
- ## ##
- ##==============================================================================##
- import sys
- import argparse
- import random
- parser = argparse.ArgumentParser(description='Generador y verificador de la validez de números de tarjeta de crédito.', prog='NTC_GEN.py')
- grFunction = parser.add_mutually_exclusive_group()
- grFunction.add_argument('-g', '--generador', metavar='CANT_NUM', type=int, required=False, help='para indicar el total de números de tarjeta a generar.')
- 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')
- 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).')
- parser.add_argument('-f', '--fichero', metavar='FICH_I/O', required=False, help='para determinar el nombre del fichero de entrada/salida.')
- parser.add_argument('-q', '--quiet', required=False, action='store_true', default=False, help = 'para no mostrar ninguna salida en la consola.')
- parser.add_argument('-s', '--separador', metavar='CARAC', required=False, default='-', help = 'para indicar un carácter de separación diferente a \'-\'.')
- parser.add_argument('-v', '--verbose', required=False, action='store_true', default=False, help = 'para mostrar detalles de ejecución en pantalla.')
- parser.add_argument('--version', action='version', version='%(prog)s 1.0')
- args = parser.parse_args()
- if not args.quiet:
- print "Iniciando el NTC_GEN.py..."
- if not args.quiet:
- print "Definiendo procedimientos auxiliares..."
- # ----------------------
- # - Métodos auxiliares -
- # ----------------------
- # Método auxiliar para tokenizar el número de tarjeta dado por parámetro. Return <nIm, nPa>.
- # Nota: admite como carácter separador el guión (-)
- def parsear(parNumTar):
- # si no se ha facilitado cabecera
- if not parNumTar:
- return [], []
- nIm = []
- nPa = []
- aux = ""
- for k in range(len(parNumTar.split(args.separador))):
- aux += parNumTar.split(args.separador)[k]
- for i in range(len(aux)):
- if i%2 == 0:
- #ojo índice 0 = impar
- nIm.append(int(aux[i]))
- else:
- #ojo índice 1 = par
- nPa.append(int(aux[i]))
- return nIm, nPa
- # Método auxiliar para calcular la suma parcial. Recibe dos arrays de int. Return <int> .
- # 1.- Números impares * 2 (si > 9, se toma el resultado indivial -9)
- # 2.- Números pares
- def calcularSumaParcial(nIm, nPa):
- suma = 0
- for i in nIm:
- c = i*2
- if (i*2)>9:
- suma += c-9
- else:
- suma += c
- for i in nPa:
- suma += i
- return suma
- # Método de verificación. Return <boolean>.
- # 1.- Calcula la suma total
- # 2.- Comprueba si es mod10=0 y <= 150
- def verificar(numTar):
- numIm, numPa = parsear(numTar)
- aux = calcularSumaParcial(numIm, numPa)
- if (aux %10 == 0) & (aux <= 150):
- return True
- return False
- # Método de generación de números aleatorios. Return <string>.
- # 0.- Leemos todos los números iniciales introducidos
- # 1.- Generamos números impares
- # 2.- Generamos números pares restantes - el último
- # 3.- Generamos el último número para que cumpla la condición de mod % 10 = 0
- def generarNumero(cabecera):
- if args.verbose:
- print ("\tGenerando un nuevo número de tarjeta...")
- numIm, numPa = parsear(cabecera)
- # generamos números impares
- for i in range(8-len(numIm)):
- numIm.append(random.randrange(0,10))
- # calculamos la suma parcial
- suma = calcularSumaParcial(numIm, numPa)
- # calculamos los números que faltan por generar
- faltan = 8-len(numPa)
- # generamos números aleatorios
- for i in range(faltan-1):
- n = random.randrange(0,10)
- suma += n
- numPa.append(n)
- # el último número lo generamos a mano para que encaje
- num = 10-(suma%10)
- # comprobación para evitar añadir un '10' al final, en lugar de '0'
- if num == 10:
- num = 0
- numPa.append(num)
- n = ""
- for i in range(8):
- n += str(numIm[i])+str(numPa[i])
- if args.verbose:
- print "\tNúmero generado:\t"+n
- return n
- # -------------------
- # - Parte principal -
- # -------------------
- try:
- if args.comprobante:
- #verificador
- if not args.quiet:
- print "Rama de verificación..."
- if args.fichero:
- tarVer = {}
- if not args.quiet:
- print "Leyendo el fichero "+args.fichero+"..."
- f = open (args.fichero, "r")
- contenido = f.readlines()
- for linea in contenido:
- num = linea[:len(linea)-1]
- if num not in tarVer:
- tarVer[num]=verificar(num)
- if args.verbose:
- print "La validez del número de tarjeta "+num+"es:\t"+str(tarVer[num])
- f.close()
- if not args.quiet:
- print "Escribiendo en el fichero ver_"+args.fichero+"..."
- s = open ("ver_"+args.fichero, "w")
- for num in tarVer:
- s.write(str(num)+"\t"+str(tarVer[num])+"\n")
- s.close()
- else:
- print "La validez del número de tarjeta "+args.comprobante+" es:\t"+str(verificar(args.comprobante))
- else:
- #generador
- if not args.quiet:
- print "Rama de generación..."
- numGenerados = []
- completado=0
- # bucle de generación de tarjetas
- for i in range(args.generador):
- nuevo = generarNumero(args.inicio)
- while nuevo in numGenerados:
- nuevo = generarNumero(args.inicio)
- numGenerados.append(nuevo)
- # mostrar mensaje de estado
- if int(float(i+1)/float(args.generador)*100) > completado:
- completado = int(float(i+1)/float(args.generador)*100)
- if not args.quiet:
- print "Estado del proceso de generación:\t"+str(completado).rjust(3)+"%"
- if args.fichero:
- if not args.quiet:
- print "Escribiendo fichero de salida en "+args.fichero+"..."
- f = open (args.fichero, "w")
- for num in numGenerados:
- f.write(str(num)+"\n")
- f.close()
- except Exception:
- print "ERROR INESPERADO: algo ha ido mal... Revisa los parámetros de entrada:\n", sys.exc_info()[0]
- print "Si aún así no sabes qué ha ido mal, consúltame en www.felixbrezo.com o en twitter (@febrezo)."
- parser.print_help()
Add Comment
Please, Sign In to add comment