code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
#!/bin/bash cd ../src make > /dev/null cp -a ./tp0 ../tests cd ../tests/ chmod 100 archivoSoloLectura #Setea los permisos del archivo en solo lectura ./tp0 -e -i prueba.txt -o archivoSoloLectura
12014orgcomp
trunk/orgaTP0/tests/.svn/text-base/pruebaArchivoSoloLectura.sh.svn-base
Shell
epl
195
#!/bin/bash cd ../src make > /dev/null cp -a ./tp0 ../tests cd ../tests/ ARCHIVOENTRADA="prueba.txt" SALIDATP0="pruebaStdinConTp0" SALIDABASE64="pruebaStdinConBase64" #Mostrar archivos de prueba echo "Archivo de prueba:" cat $ARCHIVOENTRADA if [ "$?" = "0" ]; then #Se ingresa por stdin el archivo prueba.txt y se guarda la salida estandar en un archivo cat $ARCHIVOENTRADA| ./tp0 -e > $SALIDATP0 echo -e "\nSalida obtenida con base64 de tp0" cat $SALIDATP0 #Se ingresa por stdin prueba.txt a base64 de unix y se dirige stdout a un archivo cat $ARCHIVOENTRADA | base64 -w 0 $RANDOMDUMP > $SALIDABASE64 echo -e "\n\nSalida obtenida con base64 de unix" cat $SALIDABASE64 echo -e "\n\nComparando ambos archivos... " #Comparacion de ambas salidas diff $SALIDATP0 $SALIDABASE64 if [ "$?" = "0" ]; then echo -e " Los archivos son iguales\n" #END else echo -e " Los archivos son distintos\n" #END #Borrar archivos temporales fi rm $SALIDATP0 rm $SALIDABASE64 rm ./tp0 else exit 1 fi exit 0
12014orgcomp
trunk/orgaTP0/tests/.svn/text-base/pruebaStdinStdout.sh.svn-base
Shell
epl
1,038
#!/bin/bash cd ../src make > /dev/null cp -a ./tp0 ../tests cd ../tests/ ./tp0 -e -i "archivoInexistente"
12014orgcomp
trunk/orgaTP0/tests/.svn/text-base/pruebaArchivoInexistente.sh.svn-base
Shell
epl
106
#!/bin/bash cd ../src make > /dev/null cp -a ./tp0 ../tests cd ../tests/ ARCHIVOENTRADA="prueba.txt" SALIDATP0="pruebaStdinConTp0" SALIDABASE64="pruebaStdinConBase64" #Mostrar archivos de prueba echo "Archivo de prueba:" cat $ARCHIVOENTRADA if [ "$?" = "0" ]; then #Se ingresa por stdin el archivo prueba.txt y se utiliza tp0 para guardar el resultado en un archivo cat $ARCHIVOENTRADA| ./tp0 -e -o $SALIDATP0 echo -e "\nSalida obtenida con base64 de tp0" cat $SALIDATP0 #Se ingresa por stdin prueba.txt a base64 de unix y se dirige stdout a un archivo cat $ARCHIVOENTRADA | base64 -w 0 $RANDOMDUMP > $SALIDABASE64 echo -e "\n\nSalida obtenida con base64 de unix" cat $SALIDABASE64 echo -e "\n\nComparando ambos archivos... " #Comparacion de ambas salidas diff $SALIDATP0 $SALIDABASE64 if [ "$?" = "0" ]; then echo -e " Los archivos son iguales\n" #END else echo -e " Los archivos son distintos\n" #END #Borrar archivos temporales fi rm $SALIDATP0 rm $SALIDABASE64 rm ./tp0 else exit 1 fi exit 0
12014orgcomp
trunk/orgaTP0/tests/.svn/text-base/pruebaStdinYSalidaArchivo.sh.svn-base
Shell
epl
1,051
#!/bin/bash #Pararlo con Ctrl+C cd ../src make > /dev/null cp -a ./tp0 ../tests cd ../tests/ cat -v /dev/urandom | ./tp0 -e
12014orgcomp
trunk/orgaTP0/tests/.svn/text-base/pruebaInfinita.sh.svn-base
Shell
epl
125
#!/bin/bash cd ../src make > /dev/null cp -a ./tp0 ../tests cd ../tests/ ARCHIVOENTRADA="archivoBase64.txt" SALIDATP0="salidaTp0" SALIDABASE64="salidaBase64" #Mostrar archivos de prueba echo "Archivo de prueba:" cat $ARCHIVOENTRADA if [ "$?" = "0" ]; then #Se ingresa el archivo a tp0, se decodifica y se dirige stdout a un archivo ./tp0 -d -i $ARCHIVOENTRADA > $SALIDATP0 echo -e "\nSalida obtenida con base64 de tp0" cat $SALIDATP0 #Se ingresa el archivo a base64, se decodifica y se dirige stdout a un archivo base64 -d $ARCHIVOENTRADA > $SALIDABASE64 echo -e "\nSalida obtenida con base64 de unix" cat $SALIDABASE64 echo -e "\nComparando ambos archivos... " #Comparacion de ambas salidas diff $SALIDATP0 $SALIDABASE64 if [ "$?" = "0" ]; then echo -e " Los archivos son iguales\n" #END else echo -e " Los archivos son distintos\n" #END #Borrar archivos temporales fi rm $SALIDATP0 rm $SALIDABASE64 rm ./tp0 else exit 1 fi exit 0
12014orgcomp
trunk/orgaTP0/tests/.svn/text-base/pruebaStdoutYEntradaArchivoDecod.sh.svn-base
Shell
epl
986
#!/bin/bash cd ../src make > /dev/null cp -a ./tp0 ../tests cd ../tests/ echo -n 'foo' | ./tp0 -e | ./tp0 -d echo ""
12014orgcomp
trunk/orgaTP0/tests/.svn/text-base/pruebaIdaYVueltaSinArchivos.sh.svn-base
Shell
epl
117
#!/bin/bash cd ../src make > /dev/null cp -a ./tp0 ../tests cd ../tests/ ENTRADA="archivoBinario" TMP="binarioBase64" SALIDA="binarioNuevo" if [ "$?" = "0" ]; then ./tp0 -e -i $ENTRADA -o $TMP ./tp0 -d -i $TMP -o $SALIDA diff $ENTRADA $SALIDA if [ "$?" = "0" ]; then echo "Los archivos son iguales" else echo "Los archivos son distintos" fi rm $TMP rm $SALIDA else exit 1 fi exit 0
12014orgcomp
trunk/orgaTP0/tests/.svn/text-base/pruebaIdaYVuelta.sh.svn-base
Shell
epl
412
#!/bin/bash cd ../src make > /dev/null cp -a ./tp0 ../tests cd ../tests/ #El archivo tiene caracteres que no son parte del alfabeto cat base64Incorrecto.txt ./tp0 -d -i base64Incorrecto.txt -o archivoBasura rm archivoBasura
12014orgcomp
trunk/orgaTP0/tests/pruebaBase64Incorrecto.sh
Shell
epl
224
#!/bin/bash cd ../src make > /dev/null cp -a ./tp0 ../tests cd ../tests/ ARCHIVOENTRADA="prueba.txt" SALIDATP0="pruebaStdoutConTp0" SALIDABASE64="pruebaStdoutConBase64" #Mostrar archivos de prueba echo "Archivo de prueba:" cat $ARCHIVOENTRADA if [ "$?" = "0" ]; then #Se ingresa el archivo a tp0 y se dirige stdout a un archivo ./tp0 -e -i $ARCHIVOENTRADA > $SALIDATP0 echo -e "\nSalida obtenida con base64 de tp0" cat $SALIDATP0 #Se ingresa el archivo a base64 y se dirige stdout a un archivo base64 -w 0 $ARCHIVOENTRADA > $SALIDABASE64 echo -e "\n\nSalida obtenida con base64 de unix" cat $SALIDABASE64 echo -e "\n\nComparando ambos archivos... " #Comparacion de ambas salidas diff $SALIDATP0 $SALIDABASE64 if [ "$?" = "0" ]; then echo -e " Los archivos son iguales\n" #END else echo -e " Los archivos son distintos\n" #END #Borrar archivos temporales fi rm $SALIDATP0 rm $SALIDABASE64 rm ./tp0 else exit 1 fi exit 0
12014orgcomp
trunk/orgaTP0/tests/pruebaStdoutYEntradaArchivo.sh
Shell
epl
975
#!/bin/bash #Pararlo con Ctrl+C cd ../src make > /dev/null cp -a ./tp0 ../tests cd ../tests/ cat -v /dev/urandom | base64 -w0 | ./tp0 -d
12014orgcomp
trunk/orgaTP0/tests/pruebaInfinitaDecod.sh
Shell
epl
138
#!/bin/bash cd ../src make > /dev/null cp -a ./tp0 ../tests cd ../tests/ ENTRADA="archivoBinario" TMP="binarioBase64" SALIDA="binarioNuevo" if [ "$?" = "0" ]; then ./tp0 -e -i $ENTRADA -o $TMP ./tp0 -d -i $TMP -o $SALIDA diff $ENTRADA $SALIDA if [ "$?" = "0" ]; then echo "Los archivos son iguales" else echo "Los archivos son distintos" fi rm $TMP rm $SALIDA else exit 1 fi exit 0
12014orgcomp
trunk/orgaTP0/tests/pruebaIdaYVuelta.sh
Shell
epl
412
#!/bin/bash cd ../src make > /dev/null cp -a ./tp0 ../tests cd ../tests/ echo -n 'foo' | ./tp0 -e | ./tp0 -d echo ""
12014orgcomp
trunk/orgaTP0/tests/pruebaIdaYVueltaSinArchivos.sh
Shell
epl
117
#!/bin/bash cd ../src make > /dev/null cp -a ./tp0 ../tests cd ../tests/ ARCHIVOENTRADA="prueba.txt" SALIDATP0="pruebaStdinConTp0" SALIDABASE64="pruebaStdinConBase64" #Mostrar archivos de prueba echo "Archivo de prueba:" cat $ARCHIVOENTRADA if [ "$?" = "0" ]; then #Se ingresa por stdin el archivo prueba.txt y se guarda la salida estandar en un archivo cat $ARCHIVOENTRADA| ./tp0 -e > $SALIDATP0 echo -e "\nSalida obtenida con base64 de tp0" cat $SALIDATP0 #Se ingresa por stdin prueba.txt a base64 de unix y se dirige stdout a un archivo cat $ARCHIVOENTRADA | base64 -w 0 $RANDOMDUMP > $SALIDABASE64 echo -e "\n\nSalida obtenida con base64 de unix" cat $SALIDABASE64 echo -e "\n\nComparando ambos archivos... " #Comparacion de ambas salidas diff $SALIDATP0 $SALIDABASE64 if [ "$?" = "0" ]; then echo -e " Los archivos son iguales\n" #END else echo -e " Los archivos son distintos\n" #END #Borrar archivos temporales fi rm $SALIDATP0 rm $SALIDABASE64 rm ./tp0 else exit 1 fi exit 0
12014orgcomp
trunk/orgaTP0/tests/pruebaStdinStdout.sh
Shell
epl
1,038
#!/bin/bash #Pararlo con Ctrl+C cd ../src make > /dev/null cp -a ./tp0 ../tests cd ../tests/ cat -v /dev/urandom | ./tp0 -e
12014orgcomp
trunk/orgaTP0/tests/pruebaInfinita.sh
Shell
epl
125
#!/bin/bash cd ../src make > /dev/null cp -a ./tp0 ../tests cd ../tests/ chmod 100 archivoSoloLectura #Setea los permisos del archivo en solo lectura ./tp0 -e -i prueba.txt -o archivoSoloLectura
12014orgcomp
trunk/orgaTP0/tests/pruebaArchivoSoloLectura.sh
Shell
epl
195
#!/bin/bash cd ../src make > /dev/null cp -a ./tp0 ../tests cd ../tests/ SALIDATP0="BinTp0" SALIDABASE64="BinBase64" ENTRADA="archivoBase64.txt" echo "Archivo de prueba:" cat $ENTRADA if [ "$?" = "0" ]; then #Decodifica el archivo codificado usando tp0 cat $ENTRADA | ./tp0 -d > $SALIDATP0 echo -e "\nSalida obtenida con base64 de tp0" cat $SALIDATP0 #Decodifica el archivo codificado usando base64 cat $ENTRADA | base64 -d > $SALIDABASE64 echo -e "\nSalida obtenida con base64 de unix" cat $SALIDABASE64 echo -e "\nComparando ambos archivos... " #Compara ambas conversiones diff $SALIDATP0 $SALIDABASE64 if [ "$?" = "0" ]; then echo "Los archivos son iguales" else echo "Los archivos son distintos" fi rm $SALIDATP0 rm $SALIDABASE64 rm ./tp0 else exit 1 fi exit 0
12014orgcomp
trunk/orgaTP0/tests/pruebaStdinStdoutDecod.sh
Shell
epl
894
#!/bin/bash cd ../src make > /dev/null cp -a ./tp0 ../tests cd ../tests/ echo -n 'foo' | ./tp0 -e echo ""
12014orgcomp
trunk/orgaTP0/tests/pruebaStdinEncode.sh
Shell
epl
106
#!/bin/bash directorio="../src/" nombre_ejecutable="tp0" nombre_entrada1="prueba.txt" cd ../src make > /dev/null cp -a ./tp0 ../tests cd ../tests/ valgrind --leak-check=full -v ./$nombre_ejecutable -d -i $archivoBase64.txt
12014orgcomp
trunk/orgaTP0/tests/valgrind.sh
Shell
epl
225
#!/bin/bash cd ../src make > /dev/null cp -a ./tp0 ../tests cd ../tests/ ARCHIVOENTRADA="prueba.txt" SALIDATP0="pruebaStdinConTp0" SALIDABASE64="pruebaStdinConBase64" #Mostrar archivos de prueba echo "Archivo de prueba:" cat $ARCHIVOENTRADA if [ "$?" = "0" ]; then #Se ingresa por stdin el archivo prueba.txt y se utiliza tp0 para guardar el resultado en un archivo cat $ARCHIVOENTRADA| ./tp0 -e -o $SALIDATP0 echo -e "\nSalida obtenida con base64 de tp0" cat $SALIDATP0 #Se ingresa por stdin prueba.txt a base64 de unix y se dirige stdout a un archivo cat $ARCHIVOENTRADA | base64 -w 0 $RANDOMDUMP > $SALIDABASE64 echo -e "\n\nSalida obtenida con base64 de unix" cat $SALIDABASE64 echo -e "\n\nComparando ambos archivos... " #Comparacion de ambas salidas diff $SALIDATP0 $SALIDABASE64 if [ "$?" = "0" ]; then echo -e " Los archivos son iguales\n" #END else echo -e " Los archivos son distintos\n" #END #Borrar archivos temporales fi rm $SALIDATP0 rm $SALIDABASE64 rm ./tp0 else exit 1 fi exit 0
12014orgcomp
trunk/orgaTP0/tests/pruebaStdinYSalidaArchivo.sh
Shell
epl
1,051
#include "Errors.h" void open_file_error(const char* fileName) { fprintf(stderr, "Error al intentar abrir archivo de entrada: %s\n", fileName); } void read_file_error(const char* fileName) { fprintf(stderr, "Error al leer del archivo de entrada: %s\n", fileName); } void close_file_error(const char* fileName) { fprintf(stderr, "Error al intentar cerrar el archivo de entrada: %s\n", fileName); } void printInvalidArgument() { fprintf(stderr, "Parametro invalido\n"); exit(ERROR_ARGUMENTO); }
12014orgcomp
trunk/orgaTP1/src/Errors.c
C
epl
503
#ifndef HELP_H_ #define HELP_H_ #include <stdio.h> void printHelp(char*); void printVersion(); void printNeedOption(char*); #endif /* HELP_H_ */
12014orgcomp
trunk/orgaTP1/src/Help.h
C
epl
149
#include <mips/regdef.h> #include <sys/syscall.h> //////////////// STACK /////////////////////////////////////////////////// //-------------SRA--------------pos reg // // 28 pad // // 24 ra // // 20 fp // // 16 gp // //-------------SRA---------------- // //-------------ABA---------------- // // 12 // // 8 // // 4 // # llama a count que tiene un argumento // 0 a0 // //-------------ABA---------------- // ////////////////////////////////////////////////////////////////////////// #define SPACE_CHAR 32 #define NEWLINE_CHAR 10 # Constantes para que sea mas clara la ABI #define STACK_SP 32 #define STACK_RA 24 #define STACK_FP 20 #define STACK_GP 16 # Variables globales y el tamanio en bytes de cada una .extern characters, 4 .extern words, 4 .extern lines, 4 .text .align 2 .globl count # Dice que count es global .ent count count: .frame $fp, STACK_SP, ra .set noreorder .cpload t9 .set reorder # Preparo el frame stack. subu sp,sp, STACK_SP .cprestore STACK_GP sw $fp, STACK_FP(sp) sw ra, STACK_RA(sp) move $fp, sp # Guardo argumentos en ABA de la funcion padre sw a0,STACK_SP($fp) # Pongo a0 en el ABA+0 de la funcion padre sw a1,STACK_SP+4($fp) # Pongo a1 en el ABA+4 de la funcionp padre # Cargo los argumentos en registros temporales lw t0, STACK_SP($fp) #t0<-actual lw t1, STACK_SP+4($fp) #t1<-last versipalabra: # llamada a isSpace move a0,t0 # pongo actual en a0 jal isSpace bne v0, 1, versisalto # si no es separador sigue # actual es separador, veo si last es separador # llamada a isSpace # pongo last en a0 lw a0, STACK_SP+4($fp) jal isSpace beq v0, 1, versisalto # si no es separador suma palabra sumarpalabra: # Incremento la variable global words lw t2, words addi t2, t2, 1 sw t2, words versisalto: lw t0, STACK_SP($fp) #t0<-actual bne t0, NEWLINE_CHAR, versieof # veo si actual=newline sumarlinea: lw t4, lines # actual=newline, incremento la variable global lines addi t4, t4, 1 sw t4, lines versieof: blt t0,zero,fin # veo si actual=eof, si es menor que 0 es porque es eof sumarcaracter: # No es eof, incremento la variable global characters lw t3, characters addi t3, t3, 1 sw t3, characters fin: #Dejo el stack como estaba move sp,$fp lw $fp, STACK_FP(sp) lw ra, STACK_RA(sp) addu sp, sp, STACK_SP j ra # Retorno .end count
12014orgcomp
trunk/orgaTP1/src/Count.S
Motorola 68K Assembly
epl
2,426
#include <mips/regdef.h> #include <sys/syscall.h> //////////////// STACK /////////////////////////////////////////////////// //-------------SRA--------------pos reg // // 44 pad // // 40 ra // // 36 fp // // 32 gp // //-------------SRA---------------- // //-------------LTA---------------- // // 28 PAD // // 24 result // // 20 last // // 16 actual // //-------------LTA---------------- // //-------------ABA---------------- // // 12 // // 8 // // 4 // #Va a llamar a read que tiene 3 argumentos // 0 // //-------------ABA---------------- // ////////////////////////////////////////////////////////////////////////// # Constantes para hacer mas clara la ABI #define STACK_SP 48 #define STACK_RA 40 #define STACK_FP 36 #define STACK_GP 32 #define STACK_RESULT 24 #define STACK_LAST 20 #define STACK_ACTUAL 16 #define LA 16 #Local Area. #define ABA 0 #Argument Build Area. #define SYS_read 3 # Codigo de la syscall read # Variables globales y el tamanio en bytes de cada una .extern characters, 4 .extern words, 4 .extern lines, 4 .text .align 2 .globl wc .ent wc wc: .frame $fp,STACK_SP, ra .set noreorder .cpload t9 .set reorder #Stack Frame. subu sp, sp, STACK_SP .cprestore STACK_GP sw ra, STACK_RA(sp) sw $fp, STACK_FP(sp) move $fp, sp sw a0,STACK_SP($fp) # Guardo mi argumento en la ABA de la funcion padre lw t0,0($fp) # Cargo mi argumento en registro temporal inicializarvariables: # Inicializo variables y locales, guardo resultados en la memoria li t1, -1 sw t1, STACK_LAST($fp) # last <- -1 sw zero, STACK_RESULT($fp) # result <- 0 sw zero, STACK_ACTUAL($fp) # actual <- 0 sw zero, characters # characters <- 0 sw zero, lines # lines <- 0 sw zero, words # words <- 0 while: doread: #Preparo para la llamada a la funcion syscall READ. lw a0,STACK_SP($fp) # File Descriptor del archivo de entrada la a1,STACK_ACTUAL($fp) # Puntero al buffer (actual) li a2,1 # Tamanio a leer. read: #Cargo SYS_read li v0,SYS_read syscall # Al hacer la syscall me pone en la pos de memoria de actual el caracter leido bltz v0, errorread #Verifico si hay error, si read me devuelve < 0, hay error beqz v0, eof #Comparo si lei 1 byte, sino es fin de archivo. # Si no hay error y no estoy en eof voy a cuenta docount: # Preparo para llamar a count lw a0, STACK_ACTUAL($fp) # Argumento 1 del count: actual lw a1, STACK_LAST($fp) # Argumento 2 del count: last jal count lw t0, STACK_ACTUAL($fp) sw t0, STACK_LAST($fp) # last <- actual b while # Siguiente ciclo del while errorread: li v0,1 # Devuelvo un 1 porque hubo error de lectura b fin eof: li v0,0 # Devuelvo 0 porque llegue al eof fin: move sp,$fp lw ra,STACK_RA(sp) #recupero ra lw $fp,STACK_FP(sp) #recupero fp addu sp, sp, STACK_SP j ra # vuelvo al programa. .end wc
12014orgcomp
trunk/orgaTP1/src/Wc.S
Motorola 68K Assembly
epl
3,017
#include "Count.h" extern int characters; extern int words; extern int lines; /*Mantiene actualizado las variables globales para contar respecto de lo que va leyendo wcount*/ void count(int actual, int last) { if ( isSpace(actual) && !isSpace(last) ) { /* Descarta espacios en blanco consecutivos */ words++; } if ( actual == NEWLINE_CHAR ) { lines++; } if ( actual != EOF ) { characters++; } }
12014orgcomp
trunk/orgaTP1/src/Count.c
C
epl
437
#ifndef GLOBALVARIABLES_H_ #define GLOBALVARIABLES_H_ /* Declaracion de variables globales */ extern int characters; extern int words; extern int lines; #endif /* GLOBALVARIABLES_H_ */
12014orgcomp
trunk/orgaTP1/src/GlobalVariables.h
C
epl
188
#ifndef COUNT_H_ #define COUNT_H_ #include <stdio.h> #include <stdlib.h> #include "GlobalVariables.h" #include "IsSpace.h" void count(int actual, int last); #endif /* COUNT_H_ */
12014orgcomp
trunk/orgaTP1/src/Count.h
C
epl
182
#ifndef INFO_H_ #define INFO_H_ #include <stdio.h> #include <stdlib.h> #include "GlobalVariables.h" void showFields(int wordMode, int lineMode, int byteMode, int words, int lines, int bytes); void info(int wordMode, int lineMode, int byteMode); void infoParam(int wordMode, int lineMode, int byteMode, char* inputFileName); void infoAcum(int wordMode, int lineMode, int byteMode, int words, int lines, int bytes); #endif /* INFO_H_ */
12014orgcomp
trunk/orgaTP1/src/Info.h
C
epl
438
#include "IsSpace.h" int isSpace(int c) { switch(c) { case SPACE_CHAR: return 1; break; case HORIZONTAL_TAB_CHAR: return 1; break; case FEED_CHAR: return 1; break; case NEWLINE_CHAR: return 1; break; case VERTICAL_TAB_CHAR: return 1; break; case CARRIAGE_RETURN_CHAR: return 1; break; default: break; } return 0; }
12014orgcomp
trunk/orgaTP1/src/IsSpace.c
C
epl
352
#ifndef ERRORS_H_ #define ERRORS_H_ #include <stdlib.h> #include <stdio.h> enum codigoDeError { ERROR_LECTURA_ARCHIVO = 1, ERROR_APERTURA_ARCHIVO = 2, ERROR_CIERRE_ARCHIVO = 3, ERROR_ARGUMENTO = 6, }; void open_file_error(const char* fileName); void read_file_error(const char* fileName); void close_file_error(const char* fileName); void printInvalidArgument(); #endif /* ERRORS_H_ */
12014orgcomp
trunk/orgaTP1/src/Errors.h
C
epl
395
#include <mips/regdef.h> #include <sys/syscall.h> //////////////// STACK /////////////////////////////////////////////////// //-------------SRA--------------pos reg // // 4 fp // // 0 gp // //-------------SRA---------------- // ////////////////////////////////////////////////////////////////////////// # Ascii de los separadores de palabra #define SPACE_CHAR 32 #define HORIZONTAL_TAB_CHAR 9 #define NEWLINE_CHAR 10 #define VERTICAL_TAB_CHAR 11 #define FEED_CHAR 12 #define CARRIAGE_RETURN_CHAR 13 # Constantes para que sea mas clara la ABI #define STACK_SP 8 #define STACK_FP 4 #define STACK_GP 0 .text .align 2 .globl isSpace # Dice que isSpace es global .ent isSpace isSpace: .frame $fp, STACK_SP, ra .set noreorder .cpload t9 .set reorder # Preparo el frame stack. subu sp,sp, STACK_SP .cprestore STACK_GP sw $fp,STACK_FP(sp) move $fp, sp # Guardo argumentos en ABA de la funcion padre sw a0,STACK_SP($fp) # Pongo a0 en el ABA+0 de la funcion padre # Cargo el argumento en registros temporales lw t0, STACK_SP($fp) #t0<-c versiespacio: # Si c es igual a alguno de los separados, devuelvo uno beq t0, SPACE_CHAR, devolveruno beq t0, HORIZONTAL_TAB_CHAR, devolveruno beq t0, NEWLINE_CHAR, devolveruno beq t0, VERTICAL_TAB_CHAR ,devolveruno beq t0, FEED_CHAR, devolveruno beq t0, CARRIAGE_RETURN_CHAR, devolveruno devolvercero: li v0,0 b fin devolveruno: li v0,1 fin: # Dejo el stack como estaba move sp,$fp lw $fp, STACK_FP(sp) addu sp, sp, STACK_SP j ra # Retorno .end isSpace
12014orgcomp
trunk/orgaTP1/src/IsSpace.S
Unix Assembly
epl
1,561
#include "GlobalVariables.h" /* Definicion de variables globales, se inicializan en 0 */ int characters; int words; int lines;
12014orgcomp
trunk/orgaTP1/src/GlobalVariables.c
C
epl
131
#include "Help.h" #include <getopt.h> #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include "Errors.h" #include "Info.h" #include "GlobalVariables.h" #include "Wc.h" int main(int argc, char** argv) { int next_option; int state = 0; char* inputFilename = NULL; int paramCounter = 1; /* Puntero de argumentos que recibe el programa */ FILE *input = NULL; int byteCountMode = 0, lineCountMode = 0, wordCountMode = 0, assemblyMode = 0; const char* const short_options = "ahvwlc"; /* Agregar las demas y/o modificar */ const struct option long_options[] = { { "help", 0, NULL, 'h' }, { "version", 0, NULL, 'v' }, { "words", 0, NULL, 'w' }, { "lines", 0, NULL, 'l' }, { "bytes", 0, NULL, 'c' }, { "assemblyMode", 0, NULL, 'a' }, { NULL, 0, NULL, 0 } }; do { next_option = getopt_long(argc, argv, short_options, long_options, NULL); switch (next_option) { case 'h': printHelp(argv[0]); exit(0); case 'v': printVersion(); exit(0); case 'w': paramCounter++; wordCountMode = 1; break; case 'l': paramCounter++; lineCountMode = 1; break; case 'c': paramCounter++; byteCountMode = 1; break; case 'a': paramCounter++; assemblyMode = 1; break; case '?': exit(1); default: break; } } while (next_option != -1); /* Comportamiento por default igual que en Wc */ if(!wordCountMode && !lineCountMode && !byteCountMode) { wordCountMode = 1; lineCountMode = 1; byteCountMode = 1; } /* Contador de archivos */ int filesCount = argc - paramCounter; /* Proceso los archivos, ya sea de stdin o si tengo por parametros */ if (filesCount == 0) /*Mi archivo viene de stdin*/ { input = stdin; if (assemblyMode) { input = fileno(input); } if (wc(input) == ERROR_LECTURA_ARCHIVO) { read_file_error("STDIN"); state = ERROR_LECTURA_ARCHIVO; } else { info(wordCountMode, lineCountMode, byteCountMode); printf("\n"); } } else { /* Mis archivos vienen como parametro */ if (filesCount > 0) { int acumBytes = 0; /* Acumuladores para los archivos */ int acumLines = 0; int acumWords = 0; int i; for (i = 0; i < filesCount; i++) { inputFilename = argv[(paramCounter) + i]; input = fopen(inputFilename, "rb"); if (input == NULL) { open_file_error(inputFilename); state = ERROR_APERTURA_ARCHIVO; continue; /* Pasa al siguiente archivo */ } int wcResult; /* Proceso cada archivo */ if (assemblyMode) { wcResult = wc(fileno(input)); } else { wcResult = wc(input); } if (wcResult == ERROR_LECTURA_ARCHIVO) { read_file_error(inputFilename); state = ERROR_LECTURA_ARCHIVO; continue; /* Proceso el siguiente archivo */ } else { infoParam(wordCountMode, lineCountMode, byteCountMode, inputFilename); acumBytes += characters; /* Acumulo los datos */ acumLines += lines; acumWords += words; } if (fclose(input) < 0) { close_file_error(inputFilename); state = ERROR_CIERRE_ARCHIVO; } } // Si tengo mas de un archivo muestro el total if (filesCount > 1) { infoAcum(wordCountMode, lineCountMode, byteCountMode, acumWords, acumLines, acumBytes); } } } return state; }
12014orgcomp
trunk/orgaTP1/src/Main.c
C
epl
3,267
#include "Info.h" /* Escribe los valores correspondientes por pantalla */ void showFields(int wordMode, int lineMode, int byteMode, int words, int lines, int bytes) { int fieldsToShow = wordMode+lineMode+byteMode; int i; for(i=0; i<fieldsToShow; i++) { if(fieldsToShow > 1) { printf(" "); } if (lineMode == 1) { printf("%d", lines); lineMode = 0; } else if (wordMode == 1) { printf("%d", words); wordMode = 0; } else if (byteMode == 1) printf("%d", bytes); } } void info(int wordMode, int lineMode, int byteMode) { showFields(wordMode, lineMode, byteMode, words, lines, characters); } void infoParam(int wordMode, int lineMode, int byteMode, char* inputFileName) { info(wordMode, lineMode, byteMode); printf(" %s \n", inputFileName); } void infoAcum(int wordMode, int lineMode, int byteMode, int acumWords, int acumLines, int acumBytes) { /*Salida archivos acumulados*/ showFields(wordMode, lineMode, byteMode, acumWords, acumLines, acumBytes); printf(" total \n"); }
12014orgcomp
trunk/orgaTP1/src/Info.c
C
epl
1,019
#ifndef WC_H_ #define WC_H_ #include <stdio.h> #include <stdlib.h> #include "Count.h" #include "GlobalVariables.h" #include "Errors.h" #include <unistd.h> /* Lee byte por byte del archivo de input * Y le pasa cada byte a count para que cuente */ int wc(FILE* input); // Devuelve un codigo de error !=0 si hubo error #endif /* WC_H_ */
12014orgcomp
trunk/orgaTP1/src/Wc.h
C
epl
343
all: gcc -Wall -lm Main.c Errors.c Help.c Count.c Wc.c GlobalVariables.c IsSpace.c Info.c -o tp1
12014orgcomp
trunk/orgaTP1/src/makefile
Makefile
epl
98
#include "Help.h" void printHelp( char* executableName ) { printf (" Modo de uso: \n"); printf (" %s [ OPCION ] \n", executableName); printf (" %s [ FICHERO ] \n", executableName); printf (" Realiza el calculo -wc en c y assembly \n"); printf ("\n Opciones: \n"); printf (" -v, --version Print version and quit.\n"); printf (" -h, --help Print this information and quit.\n"); printf (" -w, --words Print the number of words.\n"); printf (" -l, --lines Print the number of lines.\n"); printf (" -c, --bytes Print the number of bytes.\n"); printf ("\n Ejemplo de uso: \n"); printf (" %s echo hola mundo | ./tp1 ", executableName); } void printVersion() { printf (" Version 1.0 \n"); } void printNeedOption ( char* executableName ) { printf (" Se requiere alguna opcion para correr el programa. \n Ejecute %s -h para ver las opciones validas. \n", executableName); }
12014orgcomp
trunk/orgaTP1/src/Help.c
C
epl
925
#ifndef ISSPACE_H_ #define ISSPACE_H_ #define SPACE_CHAR 32 #define HORIZONTAL_TAB_CHAR 9 #define NEWLINE_CHAR 10 #define VERTICAL_TAB_CHAR 11 #define FEED_CHAR 12 #define CARRIAGE_RETURN_CHAR 13 int isSpace(int c); #endif /* ISSPACE_H_ */
12014orgcomp
trunk/orgaTP1/src/IsSpace.h
C
epl
244
#include "Wc.h" int wc(FILE* input) { int result = 0; int last = -1; /* Guarda el byte anterior al actual */ int actual; characters = 0; words = 0; lines = 0; do { actual = fgetc(input); result = ferror(input); if ( result!= 0) { result = ERROR_LECTURA_ARCHIVO; break; /* No sigue la cuenta */ } count(actual, last); last = actual; } while (actual != EOF); return result; }
12014orgcomp
trunk/orgaTP1/src/Wc.c
C
epl
406
#!/bin/bash TEXTO_PRUEBA="Don’t panic" echo "> Texto de prueba:" echo $TEXTO_PRUEBA SALIDA_TP=`echo "$TEXTO_PRUEBA" | ./tp1` echo "> Salida de TP1:" echo "$SALIDA_TP" SALIDA_WC=`echo "$TEXTO_PRUEBA" | wc` echo "> Salida de WC de UNIX:" echo "$SALIDA_WC" echo "> Comparación de las salidas con diff:" diff --ignore-all-space <(echo "$SALIDA_TP") <(echo "$SALIDA_WC") if [ "$?" = "0" ]; then echo "Las salidas son iguales" else echo "Las salidas son distintas" fi
12014orgcomp
trunk/orgaTP1/tests/testEntradaStdin.sh
Shell
epl
473
#!/bin/bash directorio="../src/" nombre_ejecutable="tp1C" nombre_entrada1="arch1.in" sh compilarLINUX.sh valgrind --leak-check=full -v ./$nombre_ejecutable -w -l -c $nombre_entrada1
12014orgcomp
trunk/orgaTP1/tests/.svn/text-base/valgrind.sh.svn-base
Shell
epl
183
#!/bin/bash ARCHIVO_PRUEBA="arch1.in" ARGUMENTOS=("-l" "-w" "-c" "-l -w" "-w -c" "-l -c" "-l -w -c") echo "> Contenido del archivo de prueba $ARCHIVO_PRUEBA:" cat $ARCHIVO_PRUEBA for i in "${ARGUMENTOS[@]}" do echo "" echo "> Argumentos configurados: $i" SALIDA_TP=`./tp1 $i $ARCHIVO_PRUEBA` echo "> Salida de TP1:" echo $SALIDA_TP SALIDA_WC=`wc $i $ARCHIVO_PRUEBA` echo "> Salida de WC de UNIX:" echo $SALIDA_WC echo "> Comparación de las salidas con diff:" diff --ignore-all-space <(echo "$SALIDA_TP") <(echo "$SALIDA_WC") if [ "$?" = "0" ]; then echo "Las salidas son iguales" else echo "Las salidas son distintas" fi done
12014orgcomp
trunk/orgaTP1/tests/.svn/text-base/testSeleccionarArgs.sh.svn-base
Shell
epl
653
#!/bin/bash TEXTO_PRUEBA="Don’t panic" echo "> Texto de prueba:" echo $TEXTO_PRUEBA SALIDA_TP=`echo "$TEXTO_PRUEBA" | ./tp1` echo "> Salida de TP1:" echo "$SALIDA_TP" SALIDA_WC=`echo "$TEXTO_PRUEBA" | wc` echo "> Salida de WC de UNIX:" echo "$SALIDA_WC" echo "> Comparación de las salidas con diff:" diff --ignore-all-space <(echo "$SALIDA_TP") <(echo "$SALIDA_WC") if [ "$?" = "0" ]; then echo "Las salidas son iguales" else echo "Las salidas son distintas" fi
12014orgcomp
trunk/orgaTP1/tests/.svn/text-base/testEntradaStdin.sh.svn-base
Shell
epl
473
#!/bin/bash directorio="../src" nombre_ejecutable="tp1C" gcc -Wall -lm -o $nombre_ejecutable ${directorio}/*.c
12014orgcomp
trunk/orgaTP1/tests/.svn/text-base/compilarCLINUX.sh.svn-base
Shell
epl
113
#!/bin/bash directorio="/root/orgaTP1" nombre_ejecutable="tp1C" gcc -Wall -lm -o ${directorio}/tests/${nombre_ejecutable} -g ${directorio}/src/*.c
12014orgcomp
trunk/orgaTP1/tests/.svn/text-base/compilarCMIPS.sh.svn-base
Shell
epl
148
#!/bin/bash sudo ifconfig lo:0 172.20.0.1 EJECUTABLE="tp1A" DIRECTORIO_PROYECTO="/home/dario/workspace/orgaTP1" DIRECTORIO_GUEST="/root/orgaTP1" #Eliminar la version vieja ssh -p 2222 root@127.0.0.1 rm -rf orgaTP1 #Copiar la version nueva scp -q -P 2222 -r $DIRECTORIO_PROYECTO root@127.0.0.1:/root #Compilar echo "--------------COMPILANDO-----------------" ssh -p 2222 root@127.0.0.1 sh ./orgaTP1/tests/compilarMIPS.sh #Ejecutar echo "--------------EJECUTANDO-----------------" ssh -p 2222 root@127.0.0.1 ${DIRECTORIO_GUEST}/tests/${EJECUTABLE} -w -l -c -a ${DIRECTORIO_GUEST}/tests/arch3.in ${DIRECTORIO_GUEST}/tests/arch2.in ${DIRECTORIO_GUEST}/tests/arch1.in
12014orgcomp
trunk/orgaTP1/tests/.svn/text-base/compilarRemotamente.sh.svn-base
Shell
epl
668
#!/bin/bash directorio="/root/orgaTP1/src" nombre_ejecutable="/root/orgaTP1/tests/tp1A" gcc -Wall -lm -o $nombre_ejecutable -g $directorio/Count.S $directorio/Errors.c $directorio/Help.c $directorio/GlobalVariables.c $directorio/Main.c $directorio/Info.c $directorio/Wc.S $directorio/IsSpace.S
12014orgcomp
trunk/orgaTP1/tests/.svn/text-base/compilarMIPS.sh.svn-base
Shell
epl
297
#!/bin/bash ARCHIVOS_PRUEBA=("1.in" "2.in") for i in "${ARCHIVOS_PRUEBA[@]}" do echo "> Contenido del archivo de prueba $i:" cat $i done SALIDA_TP=`./tp1 "${ARCHIVOS_PRUEBA[@]}"` echo "> Salida de TP1:" echo "$SALIDA_TP" SALIDA_WC=`wc "${ARCHIVOS_PRUEBA[@]}"` echo "> Salida de WC de UNIX:" echo "$SALIDA_WC" echo "> Comparación de las salidas con diff:" diff --ignore-all-space <(echo "$SALIDA_TP") <(echo "$SALIDA_WC") if [ "$?" = "0" ]; then echo "Las salidas son iguales" else echo "Las salidas son distintas" fi
12014orgcomp
trunk/orgaTP1/tests/.svn/text-base/testEntradaArchivos.sh.svn-base
Shell
epl
528
#!/bin/bash ARCHIVO_PRUEBA="arch2.in" LINEAS_IMPRIMIR="600" echo "> Primeras $LINEAS_IMPRIMIR lineas del archivo de prueba $ARCHIVO_PRUEBA:" head -c$LINEAS_IMPRIMIR $ARCHIVO_PRUEBA echo "" SALIDA_TP=`./tp1 $ARCHIVO_PRUEBA` echo "> Salida de TP1:" echo $SALIDA_TP SALIDA_WC=`wc $ARCHIVO_PRUEBA` echo "> Salida de WC de UNIX:" echo $SALIDA_WC echo "> Comparación de las salidas con diff:" diff --ignore-all-space <(echo "$SALIDA_TP") <(echo "$SALIDA_WC") if [ "$?" = "0" ]; then echo "Las salidas son iguales" else echo "Las salidas son distintas" fi
12014orgcomp
trunk/orgaTP1/tests/.svn/text-base/testEntradaArchivoBin.sh.svn-base
Shell
epl
558
#!/bin/bash ./tp1 "archivo.inexistente"
12014orgcomp
trunk/orgaTP1/tests/.svn/text-base/testArchivoInexistente.sh.svn-base
Shell
epl
40
#!/bin/bash ARCHIVO_PRUEBA="arch1.in" echo "> Contenido del archivo de prueba $ARCHIVO_PRUEBA:" cat $ARCHIVO_PRUEBA SALIDA_TP=`./tp1 $ARCHIVO_PRUEBA` echo "> Salida de TP1:" echo $SALIDA_TP SALIDA_WC=`wc $ARCHIVO_PRUEBA` echo "> Salida de WC de UNIX:" echo $SALIDA_WC echo "> Comparación de las salidas con diff:" diff --ignore-all-space <(echo "$SALIDA_TP") <(echo "$SALIDA_WC") if [ "$?" = "0" ]; then echo "Las salidas son iguales" else echo "Las salidas son distintas" fi
12014orgcomp
trunk/orgaTP1/tests/.svn/text-base/testEntradaArchivo.sh.svn-base
Shell
epl
485
#!/bin/bash directorio="../src/" nombre_ejecutable="tp1C" gcc -Wall -lm -o $nombre_ejecutable -g $directorio/*.c
12014orgcomp
trunk/orgaTP1/tests/.svn/text-base/compilarLINUX.sh.svn-base
Shell
epl
116
#!/bin/bash ARCHIVO_PRUEBA="arch1.in" ARGUMENTOS=("-l" "-w" "-c" "-l -w" "-w -c" "-l -c" "-l -w -c") echo "> Contenido del archivo de prueba $ARCHIVO_PRUEBA:" cat $ARCHIVO_PRUEBA for i in "${ARGUMENTOS[@]}" do echo "" echo "> Argumentos configurados: $i" SALIDA_TP=`./tp1 $i $ARCHIVO_PRUEBA` echo "> Salida de TP1:" echo $SALIDA_TP SALIDA_WC=`wc $i $ARCHIVO_PRUEBA` echo "> Salida de WC de UNIX:" echo $SALIDA_WC echo "> Comparación de las salidas con diff:" diff --ignore-all-space <(echo "$SALIDA_TP") <(echo "$SALIDA_WC") if [ "$?" = "0" ]; then echo "Las salidas son iguales" else echo "Las salidas son distintas" fi done
12014orgcomp
trunk/orgaTP1/tests/testSeleccionarArgs.sh
Shell
epl
653
#!/bin/bash directorio="/root/orgaTP1" nombre_ejecutable="tp1C" gcc -Wall -lm -o ${directorio}/tests/${nombre_ejecutable} -g ${directorio}/src/*.c
12014orgcomp
trunk/orgaTP1/tests/compilarCMIPS.sh
Shell
epl
148
#!/bin/bash directorio="../src" nombre_ejecutable="tp1C" gcc -Wall -lm -o $nombre_ejecutable ${directorio}/*.c
12014orgcomp
trunk/orgaTP1/tests/compilarCLINUX.sh
Shell
epl
113
#!/bin/bash directorio="/root/orgaTP1/src" nombre_ejecutable="/root/orgaTP1/tests/tp1A" gcc -Wall -lm -o $nombre_ejecutable -g $directorio/Count.S $directorio/Errors.c $directorio/Help.c $directorio/GlobalVariables.c $directorio/Main.c $directorio/Info.c $directorio/Wc.S $directorio/IsSpace.S
12014orgcomp
trunk/orgaTP1/tests/compilarMIPS.sh
Shell
epl
297
#!/bin/bash ARCHIVOS_PRUEBA=("1.in" "2.in") for i in "${ARCHIVOS_PRUEBA[@]}" do echo "> Contenido del archivo de prueba $i:" cat $i done SALIDA_TP=`./tp1 "${ARCHIVOS_PRUEBA[@]}"` echo "> Salida de TP1:" echo "$SALIDA_TP" SALIDA_WC=`wc "${ARCHIVOS_PRUEBA[@]}"` echo "> Salida de WC de UNIX:" echo "$SALIDA_WC" echo "> Comparación de las salidas con diff:" diff --ignore-all-space <(echo "$SALIDA_TP") <(echo "$SALIDA_WC") if [ "$?" = "0" ]; then echo "Las salidas son iguales" else echo "Las salidas son distintas" fi
12014orgcomp
trunk/orgaTP1/tests/testEntradaArchivos.sh
Shell
epl
528
#!/bin/bash directorio="../src/" nombre_ejecutable="tp1C" gcc -Wall -lm -o $nombre_ejecutable -g $directorio/*.c
12014orgcomp
trunk/orgaTP1/tests/compilarLINUX.sh
Shell
epl
116
#!/bin/bash directorio="../src/" nombre_ejecutable="tp1C" nombre_entrada1="arch1.in" sh compilarLINUX.sh valgrind --leak-check=full -v ./$nombre_ejecutable -w -l -c $nombre_entrada1
12014orgcomp
trunk/orgaTP1/tests/valgrind.sh
Shell
epl
183
#!/bin/bash ARCHIVO_PRUEBA="arch2.in" LINEAS_IMPRIMIR="600" echo "> Primeras $LINEAS_IMPRIMIR lineas del archivo de prueba $ARCHIVO_PRUEBA:" head -c$LINEAS_IMPRIMIR $ARCHIVO_PRUEBA echo "" SALIDA_TP=`./tp1 $ARCHIVO_PRUEBA` echo "> Salida de TP1:" echo $SALIDA_TP SALIDA_WC=`wc $ARCHIVO_PRUEBA` echo "> Salida de WC de UNIX:" echo $SALIDA_WC echo "> Comparación de las salidas con diff:" diff --ignore-all-space <(echo "$SALIDA_TP") <(echo "$SALIDA_WC") if [ "$?" = "0" ]; then echo "Las salidas son iguales" else echo "Las salidas son distintas" fi
12014orgcomp
trunk/orgaTP1/tests/testEntradaArchivoBin.sh
Shell
epl
558
#!/bin/bash ARCHIVO_PRUEBA="arch1.in" echo "> Contenido del archivo de prueba $ARCHIVO_PRUEBA:" cat $ARCHIVO_PRUEBA SALIDA_TP=`./tp1 $ARCHIVO_PRUEBA` echo "> Salida de TP1:" echo $SALIDA_TP SALIDA_WC=`wc $ARCHIVO_PRUEBA` echo "> Salida de WC de UNIX:" echo $SALIDA_WC echo "> Comparación de las salidas con diff:" diff --ignore-all-space <(echo "$SALIDA_TP") <(echo "$SALIDA_WC") if [ "$?" = "0" ]; then echo "Las salidas son iguales" else echo "Las salidas son distintas" fi
12014orgcomp
trunk/orgaTP1/tests/testEntradaArchivo.sh
Shell
epl
485
#!/bin/bash sudo ifconfig lo:0 172.20.0.1 EJECUTABLE="tp1A" DIRECTORIO_PROYECTO="/home/dario/workspace/orgaTP1" DIRECTORIO_GUEST="/root/orgaTP1" #Eliminar la version vieja ssh -p 2222 root@127.0.0.1 rm -rf orgaTP1 #Copiar la version nueva scp -q -P 2222 -r $DIRECTORIO_PROYECTO root@127.0.0.1:/root #Compilar echo "--------------COMPILANDO-----------------" ssh -p 2222 root@127.0.0.1 sh ./orgaTP1/tests/compilarMIPS.sh #Ejecutar echo "--------------EJECUTANDO-----------------" ssh -p 2222 root@127.0.0.1 ${DIRECTORIO_GUEST}/tests/${EJECUTABLE} -w -l -c -a ${DIRECTORIO_GUEST}/tests/arch3.in ${DIRECTORIO_GUEST}/tests/arch2.in ${DIRECTORIO_GUEST}/tests/arch1.in
12014orgcomp
trunk/orgaTP1/tests/compilarRemotamente.sh
Shell
epl
668
#!/bin/bash ./tp1 "archivo.inexistente"
12014orgcomp
trunk/orgaTP1/tests/testArchivoInexistente.sh
Shell
epl
40
#include "Errors.h" void open_file_error(const char* fileName) { fprintf(stderr, "Error al intentar abrir archivo de entrada: %s\n", fileName); } void read_file_error(const char* fileName) { fprintf(stderr, "Error al leer del archivo de entrada: %s\n", fileName); } void close_file_error(const char* fileName) { fprintf(stderr, "Error al intentar cerrar el archivo de entrada: %s\n", fileName); }
12014orgcomp
trunk/orgaTP2/src/Errors.c
C
epl
403
#ifndef HELP_H_ #define HELP_H_ #include <stdio.h> void printHelp(char*); void printVersion(); void printNeedOption(char*); #endif /* HELP_H_ */
12014orgcomp
trunk/orgaTP2/src/Help.h
C
epl
149
/* * This is an OpenSSL-compatible implementation of the RSA Data Security, Inc. * MD5 Message-Digest Algorithm (RFC 1321). * * Homepage: * http://openwall.info/wiki/people/solar/software/public-domain-source-code/md5 * * Author: * Alexander Peslyak, better known as Solar Designer <solar at openwall.com> * * This software was written by Alexander Peslyak in 2001. No copyright is * claimed, and the software is hereby placed in the public domain. * In case this attempt to disclaim copyright and place the software in the * public domain is deemed null and void, then the software is * Copyright (c) 2001 Alexander Peslyak and it is hereby released to the * general public under the following terms: * * Redistribution and use in source and binary forms, with or without * modification, are permitted. * * There's ABSOLUTELY NO WARRANTY, express or implied. * * (This is a heavily cut-down "BSD license".) * * This differs from Colin Plumb's older public domain implementation in that * no exactly 32-bit integer data type is required (any 32-bit or wider * unsigned integer data type will do), there's no compile-time endianness * configuration, and the function prototypes match OpenSSL's. No code from * Colin Plumb's implementation has been reused; this comment merely compares * the properties of the two independent implementations. * * The primary goals of this implementation are portability and ease of use. * It is meant to be fast, but not as fast as possible. Some known * optimizations are not included to reduce source code size and avoid * compile-time configuration. */ #ifndef HAVE_OPENSSL #include <string.h> #include "md5.h" /* * The basic MD5 functions. * * F and G are optimized compared to their RFC 1321 definitions for * architectures that lack an AND-NOT instruction, just like in Colin Plumb's * implementation. */ #define F(x, y, z) ((z) ^ ((x) & ((y) ^ (z)))) #define G(x, y, z) ((y) ^ ((z) & ((x) ^ (y)))) #define H(x, y, z) (((x) ^ (y)) ^ (z)) #define H2(x, y, z) ((x) ^ ((y) ^ (z))) #define I(x, y, z) ((y) ^ ((x) | ~(z))) /* * The MD5 transformation for all four rounds. */ #define STEP(f, a, b, c, d, x, t, s) \ (a) += f((b), (c), (d)) + (x) + (t); \ (a) = (((a) << (s)) | (((a) & 0xffffffff) >> (32 - (s)))); \ (a) += (b); /* * SET reads 4 input bytes in little-endian byte order and stores them * in a properly aligned word in host byte order. * * The check for little-endian architectures that tolerate unaligned * memory accesses is just an optimization. Nothing will break if it * doesn't work. */ #if defined(__i386__) || defined(__x86_64__) || defined(__vax__) #define SET(n) \ (*(MD5_u32plus *)&ptr[(n) * 4]) #define GET(n) \ SET(n) #else #define SET(n) \ (ctx->block[(n)] = \ (MD5_u32plus)ptr[(n) * 4] | \ ((MD5_u32plus)ptr[(n) * 4 + 1] << 8) | \ ((MD5_u32plus)ptr[(n) * 4 + 2] << 16) | \ ((MD5_u32plus)ptr[(n) * 4 + 3] << 24)) #define GET(n) \ (ctx->block[(n)]) #endif /* * This processes one or more 64-byte data blocks, but does NOT update * the bit counters. There are no alignment requirements. */ static const void *body(MD5_CTX *ctx, const void *data, unsigned long size) { const unsigned char *ptr; MD5_u32plus a, b, c, d; MD5_u32plus saved_a, saved_b, saved_c, saved_d; ptr = (const unsigned char *)data; a = ctx->a; b = ctx->b; c = ctx->c; d = ctx->d; do { saved_a = a; saved_b = b; saved_c = c; saved_d = d; /* Round 1 */ STEP(F, a, b, c, d, SET(0), 0xd76aa478, 7) STEP(F, d, a, b, c, SET(1), 0xe8c7b756, 12) STEP(F, c, d, a, b, SET(2), 0x242070db, 17) STEP(F, b, c, d, a, SET(3), 0xc1bdceee, 22) STEP(F, a, b, c, d, SET(4), 0xf57c0faf, 7) STEP(F, d, a, b, c, SET(5), 0x4787c62a, 12) STEP(F, c, d, a, b, SET(6), 0xa8304613, 17) STEP(F, b, c, d, a, SET(7), 0xfd469501, 22) STEP(F, a, b, c, d, SET(8), 0x698098d8, 7) STEP(F, d, a, b, c, SET(9), 0x8b44f7af, 12) STEP(F, c, d, a, b, SET(10), 0xffff5bb1, 17) STEP(F, b, c, d, a, SET(11), 0x895cd7be, 22) STEP(F, a, b, c, d, SET(12), 0x6b901122, 7) STEP(F, d, a, b, c, SET(13), 0xfd987193, 12) STEP(F, c, d, a, b, SET(14), 0xa679438e, 17) STEP(F, b, c, d, a, SET(15), 0x49b40821, 22) /* Round 2 */ STEP(G, a, b, c, d, GET(1), 0xf61e2562, 5) STEP(G, d, a, b, c, GET(6), 0xc040b340, 9) STEP(G, c, d, a, b, GET(11), 0x265e5a51, 14) STEP(G, b, c, d, a, GET(0), 0xe9b6c7aa, 20) STEP(G, a, b, c, d, GET(5), 0xd62f105d, 5) STEP(G, d, a, b, c, GET(10), 0x02441453, 9) STEP(G, c, d, a, b, GET(15), 0xd8a1e681, 14) STEP(G, b, c, d, a, GET(4), 0xe7d3fbc8, 20) STEP(G, a, b, c, d, GET(9), 0x21e1cde6, 5) STEP(G, d, a, b, c, GET(14), 0xc33707d6, 9) STEP(G, c, d, a, b, GET(3), 0xf4d50d87, 14) STEP(G, b, c, d, a, GET(8), 0x455a14ed, 20) STEP(G, a, b, c, d, GET(13), 0xa9e3e905, 5) STEP(G, d, a, b, c, GET(2), 0xfcefa3f8, 9) STEP(G, c, d, a, b, GET(7), 0x676f02d9, 14) STEP(G, b, c, d, a, GET(12), 0x8d2a4c8a, 20) /* Round 3 */ STEP(H, a, b, c, d, GET(5), 0xfffa3942, 4) STEP(H2, d, a, b, c, GET(8), 0x8771f681, 11) STEP(H, c, d, a, b, GET(11), 0x6d9d6122, 16) STEP(H2, b, c, d, a, GET(14), 0xfde5380c, 23) STEP(H, a, b, c, d, GET(1), 0xa4beea44, 4) STEP(H2, d, a, b, c, GET(4), 0x4bdecfa9, 11) STEP(H, c, d, a, b, GET(7), 0xf6bb4b60, 16) STEP(H2, b, c, d, a, GET(10), 0xbebfbc70, 23) STEP(H, a, b, c, d, GET(13), 0x289b7ec6, 4) STEP(H2, d, a, b, c, GET(0), 0xeaa127fa, 11) STEP(H, c, d, a, b, GET(3), 0xd4ef3085, 16) STEP(H2, b, c, d, a, GET(6), 0x04881d05, 23) STEP(H, a, b, c, d, GET(9), 0xd9d4d039, 4) STEP(H2, d, a, b, c, GET(12), 0xe6db99e5, 11) STEP(H, c, d, a, b, GET(15), 0x1fa27cf8, 16) STEP(H2, b, c, d, a, GET(2), 0xc4ac5665, 23) /* Round 4 */ STEP(I, a, b, c, d, GET(0), 0xf4292244, 6) STEP(I, d, a, b, c, GET(7), 0x432aff97, 10) STEP(I, c, d, a, b, GET(14), 0xab9423a7, 15) STEP(I, b, c, d, a, GET(5), 0xfc93a039, 21) STEP(I, a, b, c, d, GET(12), 0x655b59c3, 6) STEP(I, d, a, b, c, GET(3), 0x8f0ccc92, 10) STEP(I, c, d, a, b, GET(10), 0xffeff47d, 15) STEP(I, b, c, d, a, GET(1), 0x85845dd1, 21) STEP(I, a, b, c, d, GET(8), 0x6fa87e4f, 6) STEP(I, d, a, b, c, GET(15), 0xfe2ce6e0, 10) STEP(I, c, d, a, b, GET(6), 0xa3014314, 15) STEP(I, b, c, d, a, GET(13), 0x4e0811a1, 21) STEP(I, a, b, c, d, GET(4), 0xf7537e82, 6) STEP(I, d, a, b, c, GET(11), 0xbd3af235, 10) STEP(I, c, d, a, b, GET(2), 0x2ad7d2bb, 15) STEP(I, b, c, d, a, GET(9), 0xeb86d391, 21) a += saved_a; b += saved_b; c += saved_c; d += saved_d; ptr += 64; } while (size -= 64); ctx->a = a; ctx->b = b; ctx->c = c; ctx->d = d; return ptr; } void MD5_Init(MD5_CTX *ctx) { ctx->a = 0x67452301; ctx->b = 0xefcdab89; ctx->c = 0x98badcfe; ctx->d = 0x10325476; ctx->lo = 0; ctx->hi = 0; } void MD5_Update(MD5_CTX *ctx, const void *data, unsigned long size) { MD5_u32plus saved_lo; unsigned long used, available; saved_lo = ctx->lo; if ((ctx->lo = (saved_lo + size) & 0x1fffffff) < saved_lo) ctx->hi++; ctx->hi += size >> 29; used = saved_lo & 0x3f; if (used) { available = 64 - used; if (size < available) { memcpy(&ctx->buffer[used], data, size); return; } memcpy(&ctx->buffer[used], data, available); data = (const unsigned char *)data + available; size -= available; body(ctx, ctx->buffer, 64); } if (size >= 64) { data = body(ctx, data, size & ~(unsigned long)0x3f); size &= 0x3f; } memcpy(ctx->buffer, data, size); } void MD5_Final(unsigned char *result, MD5_CTX *ctx) { unsigned long used, available; used = ctx->lo & 0x3f; ctx->buffer[used++] = 0x80; available = 64 - used; if (available < 8) { memset(&ctx->buffer[used], 0, available); body(ctx, ctx->buffer, 64); used = 0; available = 64; } memset(&ctx->buffer[used], 0, available - 8); ctx->lo <<= 3; ctx->buffer[56] = ctx->lo; ctx->buffer[57] = ctx->lo >> 8; ctx->buffer[58] = ctx->lo >> 16; ctx->buffer[59] = ctx->lo >> 24; ctx->buffer[60] = ctx->hi; ctx->buffer[61] = ctx->hi >> 8; ctx->buffer[62] = ctx->hi >> 16; ctx->buffer[63] = ctx->hi >> 24; body(ctx, ctx->buffer, 64); result[0] = ctx->a; result[1] = ctx->a >> 8; result[2] = ctx->a >> 16; result[3] = ctx->a >> 24; result[4] = ctx->b; result[5] = ctx->b >> 8; result[6] = ctx->b >> 16; result[7] = ctx->b >> 24; result[8] = ctx->c; result[9] = ctx->c >> 8; result[10] = ctx->c >> 16; result[11] = ctx->c >> 24; result[12] = ctx->d; result[13] = ctx->d >> 8; result[14] = ctx->d >> 16; result[15] = ctx->d >> 24; memset(ctx, 0, sizeof(*ctx)); } #endif
12014orgcomp
trunk/orgaTP2/src/md5.c
C
epl
8,587
#include "Decrypter.h" void get_md5(unsigned char *input, unsigned char *output) { int i; MD5_CTX contexto; unsigned char *buffer = (unsigned char *) malloc(17); MD5_Init(&contexto); MD5_Update(&contexto, input, strlen((char*) input)); MD5_Final(buffer, &contexto); *output = 0; for (i = 0; i < 16; i++) { sprintf((char*) output, "%s%02x", (char*) output, buffer[i]); } } void incrementPassword(unsigned char actualPassword[], int passwordLength) { actualPassword[0] = actualPassword[0] + 1; int i; /* Se consideran solo caracteres imprimibles */ for (i = 0; i < passwordLength - 1; i++) { if (actualPassword[i] > 126) { actualPassword[i] = 32; actualPassword[i + 1] = actualPassword[i + 1] + 1; } } } int bruteForce(unsigned char encryptedPassword[], int passwordLength, unsigned char salt[], int saltMode, unsigned char result[]) { int passwordFound = 0; /* Se pone en 1 cuando se logro matchear una pass */ unsigned char actualPassword[MAX_PWD_LENGTH+1]; /*Aca vamos a ir probando las pass, suponemos un maximo de passwds de 32 bytes*/ unsigned char md5Buffer[MD5_LENGTH+1]; memset(md5Buffer, 0, MD5_LENGTH+1); int j; /* Inicializo en el primer caracter imprimible */ for (j = 0; j < passwordLength; j++) { actualPassword[j] = FIRST_PRINTABLE_CHARACTER; } actualPassword[passwordLength] = 0; if (saltMode == 1) { int saltLength = strlen((char*) salt); /* ultimos 2 bytes son fijos : la salt */ actualPassword[passwordLength - 2] = salt[0]; actualPassword[passwordLength - 1] = salt[1]; passwordLength -= saltLength; /* Despues lo trato como una de los (salt-length) caracteres restantes */ } while (passwordFound == 0) { get_md5(actualPassword, md5Buffer); passwordFound = (strcmp((char*) md5Buffer, (char*) encryptedPassword) == 0); if (passwordFound == 1) { strcpy((char*) result, (char*) actualPassword); break; } else { incrementPassword(actualPassword, passwordLength); if (actualPassword[passwordLength - 1] > LAST_PRINTABLE_CHARACTER) { break; } } } return passwordFound; /* Devuelve 0 si no logro desencriptar */ }
12014orgcomp
trunk/orgaTP2/src/Decrypter.c
C
epl
2,118
/* * This is an OpenSSL-compatible implementation of the RSA Data Security, Inc. * MD5 Message-Digest Algorithm (RFC 1321). * * Homepage: * http://openwall.info/wiki/people/solar/software/public-domain-source-code/md5 * * Author: * Alexander Peslyak, better known as Solar Designer <solar at openwall.com> * * This software was written by Alexander Peslyak in 2001. No copyright is * claimed, and the software is hereby placed in the public domain. * In case this attempt to disclaim copyright and place the software in the * public domain is deemed null and void, then the software is * Copyright (c) 2001 Alexander Peslyak and it is hereby released to the * general public under the following terms: * * Redistribution and use in source and binary forms, with or without * modification, are permitted. * * There's ABSOLUTELY NO WARRANTY, express or implied. * * See md5.c for more information. */ #ifdef HAVE_OPENSSL #include <openssl/md5.h> #elif !defined(_MD5_H) #define _MD5_H /* Any 32-bit or wider unsigned integer data type will do */ typedef unsigned int MD5_u32plus; typedef struct { MD5_u32plus lo, hi; MD5_u32plus a, b, c, d; unsigned char buffer[64]; MD5_u32plus block[16]; } MD5_CTX; extern void MD5_Init(MD5_CTX *ctx); extern void MD5_Update(MD5_CTX *ctx, const void *data, unsigned long size); extern void MD5_Final(unsigned char *result, MD5_CTX *ctx); #endif
12014orgcomp
trunk/orgaTP2/src/md5.h
C
epl
1,410
#ifndef ERRORS_H_ #define ERRORS_H_ #include <stdlib.h> #include <stdio.h> enum codigoDeError { ERROR_LECTURA_ARCHIVO = 1, ERROR_APERTURA_ARCHIVO = 2, ERROR_CIERRE_ARCHIVO = 3, }; void open_file_error(const char* fileName); void read_file_error(const char* fileName); void close_file_error(const char* fileName); #endif /* ERRORS_H_ */
12014orgcomp
trunk/orgaTP2/src/Errors.h
C
epl
344
#include <getopt.h> #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include "Errors.h" #include "Help.h" #include "Decrypter.h" #define MD5_LENGTH 32 /* Longitud en bytes de una cadena MD5 */ #define MAX_PWD_LENGTH 6 /* Longitud maxima de los passwords que puede manejar el programa */ #define SALT_LENGTH 2 /* Longitud de la salt */ int main(int argc, char** argv) { int next_option; int state = 0; char* inputFilename = NULL; int saltMode = 0; int passwordLength = 1; /* Por defecto tiene longitud 1 */ int paramCounter = 1; /* Puntero de argumentos que recibe el programa */ FILE *input = NULL; unsigned char salt[SALT_LENGTH + 1]; unsigned char md5FromFileBuffer[MD5_LENGTH + 1]; /*En este buffer guardamos el md5 que leemos del archivo*/ memset(md5FromFileBuffer, 0, MD5_LENGTH + 1); memset(salt, 0, SALT_LENGTH + 1); const char* const short_options = "hvls"; const struct option long_options[] = { { "help", 0, NULL, 'h' }, { "version", 0, NULL, 'v' }, { "length", 0, NULL, 'l' }, { "saltMode", 0, NULL, 'l' }, { NULL, 0, NULL, 0 } }; do { next_option = getopt_long(argc, argv, short_options, long_options, NULL); switch (next_option) { case 'h': printHelp(argv[0]); exit(0); case 'v': printVersion(); exit(0); case 'l': paramCounter++; passwordLength = atoi(argv[paramCounter]); break; case 's': paramCounter++; saltMode = 1; break; case '?': exit(1); default: break; } } while (next_option != -1); if ((paramCounter + 1) >= argc - 1) { inputFilename = argv[(paramCounter + 1)]; input = fopen(inputFilename, "r"); if (input == NULL) { /* No se pudo abrir el archivo de entrada */ open_file_error(inputFilename); state = ERROR_APERTURA_ARCHIVO; } else { int firstIteration = 1; /* Se lee el md5 del archivo */ while (!feof(input)) { unsigned char password[MAX_PWD_LENGTH + 1]; /*Si se pudo desencriptar aca va el resultado*/ memset(password, 0, MAX_PWD_LENGTH + 1); if (fgets((char*) md5FromFileBuffer, MD5_LENGTH + 1, input) == NULL) { if (!feof(input)) { read_file_error(inputFilename); state = ERROR_LECTURA_ARCHIVO; } break; } else { fgetc(input); if (firstIteration == 1 && saltMode == 1) { /* Hago primera iteracion para obtener la salt */ bruteForce(md5FromFileBuffer, passwordLength, NULL, 0, password); printf("%s\n", password); int i; for (i = 0; i < SALT_LENGTH; i++) { salt[i] = password[passwordLength - SALT_LENGTH + i]; /* Copio la salt */ } firstIteration = 0; } else { if (bruteForce(md5FromFileBuffer, passwordLength, salt, saltMode, password) == 1) { /* Se logro desencriptar */ printf("%s\n", password); firstIteration = 0; } else { printf("No se logro desencriptar el md5: %s\n", md5FromFileBuffer); } } } } if (fclose(input) < 0) { close_file_error(inputFilename); state = ERROR_CIERRE_ARCHIVO; } } } return state; }
12014orgcomp
trunk/orgaTP2/src/Main.c
C
epl
3,098
#include "Help.h" void printHelp( char* executableName ) { printf (" Modo de uso: \n"); printf (" %s [ OPCION ] \n", executableName); printf (" %s [ FICHERO ] \n", executableName); printf (" Obtiene passwords encriptados en md5 de un archivo. \n"); printf ("\n Opciones: \n"); printf (" -v, --version Imprime la version del programa y termina.\n"); printf (" -h, --help Muestra este mensaje de ayuda y termina.\n"); printf (" -l, --length Especifica la longitud (en bytes) de los passwords a obtener.\n"); printf (" -s, --salMode Especifica si se usara el modo sal.\n"); printf ("\n Ejemplo de uso: \n"); printf (" %s -l 2 passwords.dat\n", executableName); } void printVersion() { printf (" Version 1.0 \n"); } void printNeedOption ( char* executableName ) { printf (" Se requiere alguna opcion para correr el programa. \n Ejecute %s -h para ver las opciones validas. \n", executableName); }
12014orgcomp
trunk/orgaTP2/src/Help.c
C
epl
943
#ifndef DECRYPTER_H_ #define DECRYPTER_H_ #include <stdlib.h> #include <string.h> #include <stdio.h> #include "md5.h" #define MD5_LENGTH 32 #define MAX_PWD_LENGTH 6 #define FIRST_PRINTABLE_CHARACTER 32 #define LAST_PRINTABLE_CHARACTER 126 /* Obtiene la el MD5 de la cadena input y lo guarda en output */ void get_md5(unsigned char *input, unsigned char *output); /* Obtiene el password siguiente a probar de actualPassword y lo guarda en el mismo */ void incrementPassword(unsigned char actualPassword[], int passwordLength); /* Obtiene por fuerza bruta el password cuyo md5 coincide con encryptedPassword * * encryptedPassword[]: el md5 a desencriptar * passwordLength : longitud del password que se esta buscando * sal[] : sal si se conoce, los 3 primeros caracteres de las claves a probar * result[] : buffer donde se guarda la pass obtenida */ int bruteForce(unsigned char encryptedPassword[], int passwordLength, unsigned char salt[], int saltMode, unsigned char result[]); #endif /* DECRYPTER_H_ */
12014orgcomp
trunk/orgaTP2/src/Decrypter.h
C
epl
1,019
#!/bin/bash sh compilar.sh ./tp2 -s -l 3 passwd_4 | tee clavesDesencriptadasPasswd_4
12014orgcomp
trunk/orgaTP2/tests/desencriptarPwd4.sh
Shell
epl
87
#!/bin/bash directorio_default="../src(optimizado)/" # cambiar por "../src/" opcionalmente nombre_ejecutable="tp2" # Se puede especificar un subdirectorio opcionalmente # Se usa -pg para compilarlo para profiling gcc -Wall -pg -lm -o $nombre_ejecutable ${1:-$directorio_default}*.c
12014orgcomp
trunk/orgaTP2/tests/compilar.sh
Shell
epl
284
#!/bin/bash sh compilar.sh ./tp2 -l 2 passwd_2 | tee clavesDesencriptadasPasswd_2
12014orgcomp
trunk/orgaTP2/tests/.svn/text-base/desencriptarPwd2.sh.svn-base
Shell
epl
84
#!/bin/bash sh desencriptarPwd1.sh sh desencriptarPwd2.sh sh desencriptarPwd3.sh sh desencriptarPwd4.sh
12014orgcomp
trunk/orgaTP2/tests/.svn/text-base/desencriptarTodos.sh.svn-base
Shell
epl
107
#!/bin/bash sh compilar.sh ./tp2 -l 1 passwd_1 | tee clavesDesencriptadasPasswd_1
12014orgcomp
trunk/orgaTP2/tests/.svn/text-base/desencriptarPwd1.sh.svn-base
Shell
epl
84
#!/bin/bash EJECUTABLE=tp2 PROGRAMA=$1 if [ "$2" = "" ]; then RECOMBINACIONES=0 else RECOMBINACIONES=$2 fi # ejecuto el programa para generar el gmon.out sh $PROGRAMA # renombro el output para recombinarlo luego mv gmon.out gmon.sum # recombino los outputs para mejorar los resultados for (( i=1; i <= "$RECOMBINACIONES"; i++ )) do echo "Recombinación: $i" # ejecuto el programa de nuevo sh $PROGRAMA # mergeo los outputs con el comando -s gprof -s $EJECUTABLE gmon.out gmon.sum done gprof $EJECUTABLE gmon.sum > analisis.txt # analizo el gmon.sum final
12014orgcomp
trunk/orgaTP2/tests/.svn/text-base/runGprof.sh.svn-base
Shell
epl
570
#!/bin/bash directorio_default="../src(optimizado)/" # cambiar por "../src/" opcionalmente nombre_ejecutable="tp2" # Se puede especificar un subdirectorio opcionalmente # Se usa -pg para compilarlo para profiling gcc -Wall -pg -lm -o $nombre_ejecutable ${1:-$directorio_default}*.c
12014orgcomp
trunk/orgaTP2/tests/.svn/text-base/compilar.sh.svn-base
Shell
epl
284
#!/bin/bash sh compilar.sh ./tp2 -s -l 3 passwd_4 | tee clavesDesencriptadasPasswd_4
12014orgcomp
trunk/orgaTP2/tests/.svn/text-base/desencriptarPwd4.sh.svn-base
Shell
epl
87
#!/bin/bash sh compilar.sh ./tp2 -l 3 passwd_3 | tee clavesDesencriptadasPasswd_3
12014orgcomp
trunk/orgaTP2/tests/.svn/text-base/desencriptarPwd3.sh.svn-base
Shell
epl
84
#!/bin/bash sh compilar.sh ./tp2 -l 1 passwd_1 | tee clavesDesencriptadasPasswd_1
12014orgcomp
trunk/orgaTP2/tests/desencriptarPwd1.sh
Shell
epl
84
#!/bin/bash sh desencriptarPwd1.sh sh desencriptarPwd2.sh sh desencriptarPwd3.sh sh desencriptarPwd4.sh
12014orgcomp
trunk/orgaTP2/tests/desencriptarTodos.sh
Shell
epl
107
#!/bin/bash sh compilar.sh ./tp2 -l 3 passwd_3 | tee clavesDesencriptadasPasswd_3
12014orgcomp
trunk/orgaTP2/tests/desencriptarPwd3.sh
Shell
epl
84
#!/bin/bash sh compilar.sh ./tp2 -l 2 passwd_2 | tee clavesDesencriptadasPasswd_2
12014orgcomp
trunk/orgaTP2/tests/desencriptarPwd2.sh
Shell
epl
84
#!/bin/bash EJECUTABLE=tp2 PROGRAMA=$1 if [ "$2" = "" ]; then RECOMBINACIONES=0 else RECOMBINACIONES=$2 fi # ejecuto el programa para generar el gmon.out sh $PROGRAMA # renombro el output para recombinarlo luego mv gmon.out gmon.sum # recombino los outputs para mejorar los resultados for (( i=1; i <= "$RECOMBINACIONES"; i++ )) do echo "Recombinación: $i" # ejecuto el programa de nuevo sh $PROGRAMA # mergeo los outputs con el comando -s gprof -s $EJECUTABLE gmon.out gmon.sum done gprof $EJECUTABLE gmon.sum > analisis.txt # analizo el gmon.sum final
12014orgcomp
trunk/orgaTP2/tests/runGprof.sh
Shell
epl
570
#include "Errors.h" void open_file_error(const char* fileName) { fprintf(stderr, "Error al intentar abrir archivo de entrada: %s\n", fileName); } void read_file_error(const char* fileName) { fprintf(stderr, "Error al leer del archivo de entrada: %s\n", fileName); } void close_file_error(const char* fileName) { fprintf(stderr, "Error al intentar cerrar el archivo de entrada: %s\n", fileName); }
12014orgcomp
trunk/orgaTP2/src(optimizado)/Errors.c
C
epl
403
#ifndef HELP_H_ #define HELP_H_ #include <stdio.h> void printHelp(char*); void printVersion(); void printNeedOption(char*); #endif /* HELP_H_ */
12014orgcomp
trunk/orgaTP2/src(optimizado)/Help.h
C
epl
149
/* * This is an OpenSSL-compatible implementation of the RSA Data Security, Inc. * MD5 Message-Digest Algorithm (RFC 1321). * * Homepage: * http://openwall.info/wiki/people/solar/software/public-domain-source-code/md5 * * Author: * Alexander Peslyak, better known as Solar Designer <solar at openwall.com> * * This software was written by Alexander Peslyak in 2001. No copyright is * claimed, and the software is hereby placed in the public domain. * In case this attempt to disclaim copyright and place the software in the * public domain is deemed null and void, then the software is * Copyright (c) 2001 Alexander Peslyak and it is hereby released to the * general public under the following terms: * * Redistribution and use in source and binary forms, with or without * modification, are permitted. * * There's ABSOLUTELY NO WARRANTY, express or implied. * * (This is a heavily cut-down "BSD license".) * * This differs from Colin Plumb's older public domain implementation in that * no exactly 32-bit integer data type is required (any 32-bit or wider * unsigned integer data type will do), there's no compile-time endianness * configuration, and the function prototypes match OpenSSL's. No code from * Colin Plumb's implementation has been reused; this comment merely compares * the properties of the two independent implementations. * * The primary goals of this implementation are portability and ease of use. * It is meant to be fast, but not as fast as possible. Some known * optimizations are not included to reduce source code size and avoid * compile-time configuration. */ #ifndef HAVE_OPENSSL #include <string.h> #include "md5.h" /* * The basic MD5 functions. * * F and G are optimized compared to their RFC 1321 definitions for * architectures that lack an AND-NOT instruction, just like in Colin Plumb's * implementation. */ #define F(x, y, z) ((z) ^ ((x) & ((y) ^ (z)))) #define G(x, y, z) ((y) ^ ((z) & ((x) ^ (y)))) #define H(x, y, z) (((x) ^ (y)) ^ (z)) #define H2(x, y, z) ((x) ^ ((y) ^ (z))) #define I(x, y, z) ((y) ^ ((x) | ~(z))) /* * The MD5 transformation for all four rounds. */ #define STEP(f, a, b, c, d, x, t, s) \ (a) += f((b), (c), (d)) + (x) + (t); \ (a) = (((a) << (s)) | (((a) & 0xffffffff) >> (32 - (s)))); \ (a) += (b); /* * SET reads 4 input bytes in little-endian byte order and stores them * in a properly aligned word in host byte order. * * The check for little-endian architectures that tolerate unaligned * memory accesses is just an optimization. Nothing will break if it * doesn't work. */ #if defined(__i386__) || defined(__x86_64__) || defined(__vax__) #define SET(n) \ (*(MD5_u32plus *)&ptr[(n) * 4]) #define GET(n) \ SET(n) #else #define SET(n) \ (ctx->block[(n)] = \ (MD5_u32plus)ptr[(n) * 4] | \ ((MD5_u32plus)ptr[(n) * 4 + 1] << 8) | \ ((MD5_u32plus)ptr[(n) * 4 + 2] << 16) | \ ((MD5_u32plus)ptr[(n) * 4 + 3] << 24)) #define GET(n) \ (ctx->block[(n)]) #endif /* * This processes one or more 64-byte data blocks, but does NOT update * the bit counters. There are no alignment requirements. */ inline static const void *body(MD5_CTX *ctx, const void *data, unsigned long size) { const unsigned char *ptr; register MD5_u32plus a, b, c, d; register MD5_u32plus saved_a, saved_b, saved_c, saved_d; ptr = (const unsigned char *)data; a = ctx->a; b = ctx->b; c = ctx->c; d = ctx->d; do { saved_a = a; saved_b = b; saved_c = c; saved_d = d; /* Round 1 */ STEP(F, a, b, c, d, SET(0), 0xd76aa478, 7) STEP(F, d, a, b, c, SET(1), 0xe8c7b756, 12) STEP(F, c, d, a, b, SET(2), 0x242070db, 17) STEP(F, b, c, d, a, SET(3), 0xc1bdceee, 22) STEP(F, a, b, c, d, SET(4), 0xf57c0faf, 7) STEP(F, d, a, b, c, SET(5), 0x4787c62a, 12) STEP(F, c, d, a, b, SET(6), 0xa8304613, 17) STEP(F, b, c, d, a, SET(7), 0xfd469501, 22) STEP(F, a, b, c, d, SET(8), 0x698098d8, 7) STEP(F, d, a, b, c, SET(9), 0x8b44f7af, 12) STEP(F, c, d, a, b, SET(10), 0xffff5bb1, 17) STEP(F, b, c, d, a, SET(11), 0x895cd7be, 22) STEP(F, a, b, c, d, SET(12), 0x6b901122, 7) STEP(F, d, a, b, c, SET(13), 0xfd987193, 12) STEP(F, c, d, a, b, SET(14), 0xa679438e, 17) STEP(F, b, c, d, a, SET(15), 0x49b40821, 22) /* Round 2 */ STEP(G, a, b, c, d, GET(1), 0xf61e2562, 5) STEP(G, d, a, b, c, GET(6), 0xc040b340, 9) STEP(G, c, d, a, b, GET(11), 0x265e5a51, 14) STEP(G, b, c, d, a, GET(0), 0xe9b6c7aa, 20) STEP(G, a, b, c, d, GET(5), 0xd62f105d, 5) STEP(G, d, a, b, c, GET(10), 0x02441453, 9) STEP(G, c, d, a, b, GET(15), 0xd8a1e681, 14) STEP(G, b, c, d, a, GET(4), 0xe7d3fbc8, 20) STEP(G, a, b, c, d, GET(9), 0x21e1cde6, 5) STEP(G, d, a, b, c, GET(14), 0xc33707d6, 9) STEP(G, c, d, a, b, GET(3), 0xf4d50d87, 14) STEP(G, b, c, d, a, GET(8), 0x455a14ed, 20) STEP(G, a, b, c, d, GET(13), 0xa9e3e905, 5) STEP(G, d, a, b, c, GET(2), 0xfcefa3f8, 9) STEP(G, c, d, a, b, GET(7), 0x676f02d9, 14) STEP(G, b, c, d, a, GET(12), 0x8d2a4c8a, 20) /* Round 3 */ STEP(H, a, b, c, d, GET(5), 0xfffa3942, 4) STEP(H2, d, a, b, c, GET(8), 0x8771f681, 11) STEP(H, c, d, a, b, GET(11), 0x6d9d6122, 16) STEP(H2, b, c, d, a, GET(14), 0xfde5380c, 23) STEP(H, a, b, c, d, GET(1), 0xa4beea44, 4) STEP(H2, d, a, b, c, GET(4), 0x4bdecfa9, 11) STEP(H, c, d, a, b, GET(7), 0xf6bb4b60, 16) STEP(H2, b, c, d, a, GET(10), 0xbebfbc70, 23) STEP(H, a, b, c, d, GET(13), 0x289b7ec6, 4) STEP(H2, d, a, b, c, GET(0), 0xeaa127fa, 11) STEP(H, c, d, a, b, GET(3), 0xd4ef3085, 16) STEP(H2, b, c, d, a, GET(6), 0x04881d05, 23) STEP(H, a, b, c, d, GET(9), 0xd9d4d039, 4) STEP(H2, d, a, b, c, GET(12), 0xe6db99e5, 11) STEP(H, c, d, a, b, GET(15), 0x1fa27cf8, 16) STEP(H2, b, c, d, a, GET(2), 0xc4ac5665, 23) /* Round 4 */ STEP(I, a, b, c, d, GET(0), 0xf4292244, 6) STEP(I, d, a, b, c, GET(7), 0x432aff97, 10) STEP(I, c, d, a, b, GET(14), 0xab9423a7, 15) STEP(I, b, c, d, a, GET(5), 0xfc93a039, 21) STEP(I, a, b, c, d, GET(12), 0x655b59c3, 6) STEP(I, d, a, b, c, GET(3), 0x8f0ccc92, 10) STEP(I, c, d, a, b, GET(10), 0xffeff47d, 15) STEP(I, b, c, d, a, GET(1), 0x85845dd1, 21) STEP(I, a, b, c, d, GET(8), 0x6fa87e4f, 6) STEP(I, d, a, b, c, GET(15), 0xfe2ce6e0, 10) STEP(I, c, d, a, b, GET(6), 0xa3014314, 15) STEP(I, b, c, d, a, GET(13), 0x4e0811a1, 21) STEP(I, a, b, c, d, GET(4), 0xf7537e82, 6) STEP(I, d, a, b, c, GET(11), 0xbd3af235, 10) STEP(I, c, d, a, b, GET(2), 0x2ad7d2bb, 15) STEP(I, b, c, d, a, GET(9), 0xeb86d391, 21) a += saved_a; b += saved_b; c += saved_c; d += saved_d; ptr += 64; } while (size -= 64); ctx->a = a; ctx->b = b; ctx->c = c; ctx->d = d; return ptr; } void MD5_Init(MD5_CTX *ctx) { ctx->a = 0x67452301; ctx->b = 0xefcdab89; ctx->c = 0x98badcfe; ctx->d = 0x10325476; ctx->lo = 0; ctx->hi = 0; } void MD5_Update(MD5_CTX *ctx, const void *data, unsigned long size) { MD5_u32plus saved_lo; unsigned long used, available; saved_lo = ctx->lo; if ((ctx->lo = (saved_lo + size) & 0x1fffffff) < saved_lo) ctx->hi++; ctx->hi += size >> 29; used = saved_lo & 0x3f; if (used) { available = 64 - used; if (size < available) { memcpy(&ctx->buffer[used], data, size); return; } memcpy(&ctx->buffer[used], data, available); data = (const unsigned char *)data + available; size -= available; body(ctx, ctx->buffer, 64); } if (size >= 64) { data = body(ctx, data, size & ~(unsigned long)0x3f); size &= 0x3f; } memcpy(ctx->buffer, data, size); } void MD5_Final(unsigned char *result, MD5_CTX *ctx) { register unsigned long used, available; used = ctx->lo & 0x3f; ctx->buffer[used++] = 0x80; available = 64 - used; if (available < 8) { memset(&ctx->buffer[used], 0, available); body(ctx, ctx->buffer, 64); used = 0; available = 64; } memset(&ctx->buffer[used], 0, available - 8); ctx->lo <<= 3; ctx->buffer[56] = ctx->lo; ctx->buffer[57] = ctx->lo >> 8; ctx->buffer[58] = ctx->lo >> 16; ctx->buffer[59] = ctx->lo >> 24; ctx->buffer[60] = ctx->hi; ctx->buffer[61] = ctx->hi >> 8; ctx->buffer[62] = ctx->hi >> 16; ctx->buffer[63] = ctx->hi >> 24; body(ctx, ctx->buffer, 64); result[0] = ctx->a; result[1] = ctx->a >> 8; result[2] = ctx->a >> 16; result[3] = ctx->a >> 24; result[4] = ctx->b; result[5] = ctx->b >> 8; result[6] = ctx->b >> 16; result[7] = ctx->b >> 24; result[8] = ctx->c; result[9] = ctx->c >> 8; result[10] = ctx->c >> 16; result[11] = ctx->c >> 24; result[12] = ctx->d; result[13] = ctx->d >> 8; result[14] = ctx->d >> 16; result[15] = ctx->d >> 24; memset(ctx, 0, sizeof(*ctx)); } #endif
12014orgcomp
trunk/orgaTP2/src(optimizado)/md5.c
C
epl
8,621
#include "Decrypter.h" inline void get_md5(unsigned char *input, unsigned char *output) { int i; MD5_CTX contexto; unsigned char *buffer = (unsigned char *) malloc(17); MD5_Init(&contexto); MD5_Update(&contexto, input, strlen((char*) input)); MD5_Final(buffer, &contexto); *output = 0; for (i = 0; i < 16; i+=4) { sprintf((char*) output, "%s%02x", (char*) output, buffer[i]); sprintf((char*) output, "%s%02x", (char*) output, buffer[i+1]); sprintf((char*) output, "%s%02x", (char*) output, buffer[i+2]); sprintf((char*) output, "%s%02x", (char*) output, buffer[i+3]); } } inline void incrementPassword(unsigned char actualPassword[], int passwordLength) { actualPassword[0] = actualPassword[0] + 1; int i; /* Se consideran solo caracteres imprimibles */ for (i = 0; i < passwordLength - 1; i++) { if (actualPassword[i] > 126) { actualPassword[i] = 32; actualPassword[i + 1] = actualPassword[i + 1] + 1; } } } int bruteForce(unsigned char encryptedPassword[], int passwordLength, unsigned char salt[], int saltMode, unsigned char result[]) { int passwordFound = 0; /* Se pone en 1 cuando se logro matchear una pass */ unsigned char actualPassword[MAX_PWD_LENGTH+1]; /*Aca vamos a ir probando las pass, suponemos un maximo de passwds de 32 bytes*/ unsigned char md5Buffer[MD5_LENGTH+1]; memset(md5Buffer, 0, MD5_LENGTH+1); int j; /* Inicializo en el primer caracter imprimible */ for (j = 0; j < passwordLength; j++) { actualPassword[j] = FIRST_PRINTABLE_CHARACTER; } actualPassword[passwordLength] = 0; if (saltMode == 1) { int saltLength = strlen((char*) salt); /* ultimos 2 bytes son fijos : la salt */ actualPassword[passwordLength - 2] = salt[0]; actualPassword[passwordLength - 1] = salt[1]; passwordLength -= saltLength; /* Despues lo trato como una de los (salt-length) caracteres restantes */ } while (passwordFound == 0) { get_md5(actualPassword, md5Buffer); passwordFound = (strcmp((char*) md5Buffer, (char*) encryptedPassword) == 0); if (passwordFound == 1) { strcpy((char*) result, (char*) actualPassword); break; } else { incrementPassword(actualPassword, passwordLength); if (actualPassword[passwordLength - 1] > LAST_PRINTABLE_CHARACTER) { break; } } } return passwordFound; /* Devuelve 0 si no logro desencriptar */ }
12014orgcomp
trunk/orgaTP2/src(optimizado)/Decrypter.c
C
epl
2,332
/* * This is an OpenSSL-compatible implementation of the RSA Data Security, Inc. * MD5 Message-Digest Algorithm (RFC 1321). * * Homepage: * http://openwall.info/wiki/people/solar/software/public-domain-source-code/md5 * * Author: * Alexander Peslyak, better known as Solar Designer <solar at openwall.com> * * This software was written by Alexander Peslyak in 2001. No copyright is * claimed, and the software is hereby placed in the public domain. * In case this attempt to disclaim copyright and place the software in the * public domain is deemed null and void, then the software is * Copyright (c) 2001 Alexander Peslyak and it is hereby released to the * general public under the following terms: * * Redistribution and use in source and binary forms, with or without * modification, are permitted. * * There's ABSOLUTELY NO WARRANTY, express or implied. * * See md5.c for more information. */ #ifdef HAVE_OPENSSL #include <openssl/md5.h> #elif !defined(_MD5_H) #define _MD5_H /* Any 32-bit or wider unsigned integer data type will do */ typedef unsigned int MD5_u32plus; typedef struct { MD5_u32plus lo, hi; MD5_u32plus a, b, c, d; unsigned char buffer[64]; MD5_u32plus block[16]; } MD5_CTX; extern void MD5_Init(MD5_CTX *ctx); extern void MD5_Update(MD5_CTX *ctx, const void *data, unsigned long size); extern void MD5_Final(unsigned char *result, MD5_CTX *ctx); #endif
12014orgcomp
trunk/orgaTP2/src(optimizado)/md5.h
C
epl
1,410
#ifndef ERRORS_H_ #define ERRORS_H_ #include <stdlib.h> #include <stdio.h> enum codigoDeError { ERROR_LECTURA_ARCHIVO = 1, ERROR_APERTURA_ARCHIVO = 2, ERROR_CIERRE_ARCHIVO = 3, }; void open_file_error(const char* fileName); void read_file_error(const char* fileName); void close_file_error(const char* fileName); #endif /* ERRORS_H_ */
12014orgcomp
trunk/orgaTP2/src(optimizado)/Errors.h
C
epl
344
#include <getopt.h> #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include "Errors.h" #include "Help.h" #include "Decrypter.h" #define MD5_LENGTH 32 /* Longitud en bytes de una cadena MD5 */ #define MAX_PWD_LENGTH 6 /* Longitud maxima de los passwords que puede manejar el programa */ #define SALT_LENGTH 2 /* Longitud de la salt */ int main(int argc, char** argv) { int next_option; int state = 0; char* inputFilename = NULL; int saltMode = 0; int passwordLength = 1; /* Por defecto tiene longitud 1 */ int paramCounter = 1; /* Puntero de argumentos que recibe el programa */ FILE *input = NULL; unsigned char salt[SALT_LENGTH + 1]; unsigned char md5FromFileBuffer[MD5_LENGTH + 1]; /*En este buffer guardamos el md5 que leemos del archivo*/ memset(md5FromFileBuffer, 0, MD5_LENGTH + 1); memset(salt, 0, SALT_LENGTH + 1); const char* const short_options = "hvls"; const struct option long_options[] = { { "help", 0, NULL, 'h' }, { "version", 0, NULL, 'v' }, { "length", 0, NULL, 'l' }, { "saltMode", 0, NULL, 'l' }, { NULL, 0, NULL, 0 } }; do { next_option = getopt_long(argc, argv, short_options, long_options, NULL); switch (next_option) { case 'h': printHelp(argv[0]); exit(0); case 'v': printVersion(); exit(0); case 'l': paramCounter++; passwordLength = atoi(argv[paramCounter]); break; case 's': paramCounter++; saltMode = 1; break; case '?': exit(1); default: break; } } while (next_option != -1); if ((paramCounter + 1) >= argc - 1) { inputFilename = argv[(paramCounter + 1)]; input = fopen(inputFilename, "r"); if (input == NULL) { /* No se pudo abrir el archivo de entrada */ open_file_error(inputFilename); state = ERROR_APERTURA_ARCHIVO; } else { int firstIteration = 1; /* Se lee el md5 del archivo */ while (!feof(input)) { unsigned char password[MAX_PWD_LENGTH + 1]; /*Si se pudo desencriptar aca va el resultado*/ memset(password, 0, MAX_PWD_LENGTH + 1); if (fgets((char*) md5FromFileBuffer, MD5_LENGTH + 1, input) == NULL) { if (!feof(input)) { read_file_error(inputFilename); state = ERROR_LECTURA_ARCHIVO; } break; } else { fgetc(input); if (firstIteration == 1 && saltMode == 1) { /* Hago primera iteracion para obtener la salt */ bruteForce(md5FromFileBuffer, passwordLength, NULL, 0, password); printf("%s\n", password); int i; for (i = 0; i < SALT_LENGTH; i++) { salt[i] = password[passwordLength - SALT_LENGTH + i]; /* Copio la salt */ } firstIteration = 0; } else { if (bruteForce(md5FromFileBuffer, passwordLength, salt, saltMode, password) == 1) { /* Se logro desencriptar */ printf("%s\n", password); firstIteration = 0; } else { printf("No se logro desencriptar el md5: %s\n", md5FromFileBuffer); } } } } if (fclose(input) < 0) { close_file_error(inputFilename); state = ERROR_CIERRE_ARCHIVO; } } } return state; }
12014orgcomp
trunk/orgaTP2/src(optimizado)/Main.c
C
epl
3,098
#include "Help.h" void printHelp( char* executableName ) { printf (" Modo de uso: \n"); printf (" %s [ OPCION ] \n", executableName); printf (" %s [ FICHERO ] \n", executableName); printf (" Obtiene passwords encriptados en md5 de un archivo. \n"); printf ("\n Opciones: \n"); printf (" -v, --version Imprime la version del programa y termina.\n"); printf (" -h, --help Muestra este mensaje de ayuda y termina.\n"); printf (" -l, --length Especifica la longitud (en bytes) de los passwords a obtener.\n"); printf (" -s, --salMode Especifica si se usara el modo sal.\n"); printf ("\n Ejemplo de uso: \n"); printf (" %s -l 2 passwords.dat\n", executableName); } void printVersion() { printf (" Version 1.0 \n"); } void printNeedOption ( char* executableName ) { printf (" Se requiere alguna opcion para correr el programa. \n Ejecute %s -h para ver las opciones validas. \n", executableName); }
12014orgcomp
trunk/orgaTP2/src(optimizado)/Help.c
C
epl
943
#ifndef DECRYPTER_H_ #define DECRYPTER_H_ #include <stdlib.h> #include <string.h> #include <stdio.h> #include "md5.h" #define MD5_LENGTH 32 #define MAX_PWD_LENGTH 6 #define FIRST_PRINTABLE_CHARACTER 32 #define LAST_PRINTABLE_CHARACTER 126 /* Obtiene la el MD5 de la cadena input y lo guarda en output */ void get_md5(unsigned char *input, unsigned char *output); /* Obtiene el password siguiente a probar de actualPassword y lo guarda en el mismo */ void incrementPassword(unsigned char actualPassword[], int passwordLength); /* Obtiene por fuerza bruta el password cuyo md5 coincide con encryptedPassword * * encryptedPassword[]: el md5 a desencriptar * passwordLength : longitud del password que se esta buscando * sal[] : sal si se conoce, los 3 primeros caracteres de las claves a probar * result[] : buffer donde se guarda la pass obtenida */ int bruteForce(unsigned char encryptedPassword[], int passwordLength, unsigned char salt[], int saltMode, unsigned char result[]); #endif /* DECRYPTER_H_ */
12014orgcomp
trunk/orgaTP2/src(optimizado)/Decrypter.h
C
epl
1,019
/* NFCard 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. NFCard 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 Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.tech; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import android.nfc.tech.NfcF; import com.sinpo.xnfc.Util; public class FeliCa { public static final byte[] EMPTY = {}; protected byte[] data; protected FeliCa() { } protected FeliCa(byte[] bytes) { data = (bytes == null) ? FeliCa.EMPTY : bytes; } public int size() { return data.length; } public byte[] getBytes() { return data; } @Override public String toString() { return Util.toHexString(data, 0, data.length); } public final static class IDm extends FeliCa { public static final byte[] EMPTY = { 0, 0, 0, 0, 0, 0, 0, 0, }; public IDm(byte[] bytes) { super((bytes == null || bytes.length < 8) ? IDm.EMPTY : bytes); } public final String getManufactureCode() { return Util.toHexString(data, 0, 2); } public final String getCardIdentification() { return Util.toHexString(data, 2, 6); } public boolean isEmpty() { final byte[] d = data; for (final byte v : d) { if (v != 0) return false; } return true; } } public final static class PMm extends FeliCa { public static final byte[] EMPTY = { 0, 0, 0, 0, 0, 0, 0, 0, }; public PMm(byte[] bytes) { super((bytes == null || bytes.length < 8) ? PMm.EMPTY : bytes); } public final String getIcCode() { return Util.toHexString(data, 0, 2); } public final String getMaximumResponseTime() { return Util.toHexString(data, 2, 6); } } public final static class SystemCode extends FeliCa { public static final byte[] EMPTY = { 0, 0, }; public SystemCode(byte[] sc) { super((sc == null || sc.length < 2) ? SystemCode.EMPTY : sc); } public int toInt() { return toInt(data); } public static int toInt(byte[] data) { return 0x0000FFFF & ((data[0] << 8) | (0x000000FF & data[1])); } } public final static class ServiceCode extends FeliCa { public static final byte[] EMPTY = { 0, 0, }; public static final int T_UNKNOWN = 0; public static final int T_RANDOM = 1; public static final int T_CYCLIC = 2; public static final int T_PURSE = 3; public ServiceCode(byte[] sc) { super((sc == null || sc.length < 2) ? ServiceCode.EMPTY : sc); } public ServiceCode(int code) { this(new byte[] { (byte) (code & 0xFF), (byte) (code >> 8) }); } public boolean isEncrypt() { return (data[0] & 0x1) == 0; } public boolean isWritable() { final int f = data[0] & 0x3F; return (f & 0x2) == 0 || f == 0x13 || f == 0x12; } public int getAccessAttr() { return data[0] & 0x3F; } public int getDataType() { final int f = data[0] & 0x3F; if ((f & 0x10) == 0) return T_PURSE; return ((f & 0x04) == 0) ? T_RANDOM : T_CYCLIC; } } public final static class Block extends FeliCa { public Block() { data = new byte[16]; } public Block(byte[] bytes) { super((bytes == null || bytes.length < 16) ? new byte[16] : bytes); } } public final static class BlockListElement extends FeliCa { private static final byte LENGTH_2_BYTE = (byte) 0x80; private static final byte LENGTH_3_BYTE = (byte) 0x00; // private static final byte ACCESSMODE_DECREMENT = (byte) 0x00; // private static final byte ACCESSMODE_CACHEBACK = (byte) 0x01; private final byte lengthAndaccessMode; private final byte serviceCodeListOrder; public BlockListElement(byte mode, byte order, byte... blockNumber) { if (blockNumber.length > 1) { lengthAndaccessMode = (byte) (mode | LENGTH_2_BYTE & 0xFF); } else { lengthAndaccessMode = (byte) (mode | LENGTH_3_BYTE & 0xFF); } serviceCodeListOrder = (byte) (order & 0x0F); data = (blockNumber == null) ? FeliCa.EMPTY : blockNumber; } @Override public byte[] getBytes() { if ((this.lengthAndaccessMode & LENGTH_2_BYTE) == 1) { ByteBuffer buff = ByteBuffer.allocate(2); buff.put( (byte) ((this.lengthAndaccessMode | this.serviceCodeListOrder) & 0xFF)) .put(data[0]); return buff.array(); } else { ByteBuffer buff = ByteBuffer.allocate(3); buff.put( (byte) ((this.lengthAndaccessMode | this.serviceCodeListOrder) & 0xFF)) .put(data[1]).put(data[0]); return buff.array(); } } } public final static class MemoryConfigurationBlock extends FeliCa { public MemoryConfigurationBlock(byte[] bytes) { super((bytes == null || bytes.length < 4) ? new byte[4] : bytes); } public boolean isNdefSupport() { return (data == null) ? false : (data[3] & (byte) 0xff) == 1; } public void setNdefSupport(boolean ndefSupport) { data[3] = (byte) (ndefSupport ? 1 : 0); } public boolean isWritable(int... addrs) { if (data == null) return false; boolean result = true; for (int a : addrs) { byte b = (byte) ((a & 0xff) + 1); if (a < 8) { result &= (data[0] & b) == b; continue; } else if (a < 16) { result &= (data[1] & b) == b; continue; } else result &= (data[2] & b) == b; } return result; } } public final static class Service extends FeliCa { private final ServiceCode[] serviceCodes; private final BlockListElement[] blockListElements; public Service(ServiceCode[] codes, BlockListElement... blocks) { serviceCodes = (codes == null) ? new ServiceCode[0] : codes; blockListElements = (blocks == null) ? new BlockListElement[0] : blocks; } @Override public byte[] getBytes() { int length = 0; for (ServiceCode s : this.serviceCodes) { length += s.getBytes().length; } for (BlockListElement b : blockListElements) { length += b.getBytes().length; } ByteBuffer buff = ByteBuffer.allocate(length); for (ServiceCode s : this.serviceCodes) { buff.put(s.getBytes()); } for (BlockListElement b : blockListElements) { buff.put(b.getBytes()); } return buff.array(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); for (ServiceCode s : serviceCodes) { sb.append(s.toString()); } for (BlockListElement b : blockListElements) { sb.append(b.toString()); } return sb.toString(); } } public final static class Command extends FeliCa { private final int length; private final byte code; private final IDm idm; public Command(final byte[] bytes) { this(bytes[0], Arrays.copyOfRange(bytes, 1, bytes.length)); } public Command(byte code, final byte... bytes) { this.code = code; if (bytes.length >= 8) { idm = new IDm(Arrays.copyOfRange(bytes, 0, 8)); data = Arrays.copyOfRange(bytes, 8, bytes.length); } else { idm = null; data = bytes; } length = bytes.length + 2; } public Command(byte code, IDm idm, final byte... bytes) { this.code = code; this.idm = idm; this.data = bytes; this.length = idm.getBytes().length + data.length + 2; } public Command(byte code, byte[] idm, final byte... bytes) { this.code = code; this.idm = new IDm(idm); this.data = bytes; this.length = idm.length + data.length + 2; } @Override public byte[] getBytes() { ByteBuffer buff = ByteBuffer.allocate(length); byte length = (byte) this.length; if (idm != null) { buff.put(length).put(code).put(idm.getBytes()).put(data); } else { buff.put(length).put(code).put(data); } return buff.array(); } } public static class Response extends FeliCa { protected final int length; protected final byte code; protected final IDm idm; public Response(byte[] bytes) { if (bytes != null && bytes.length >= 10) { length = bytes[0] & 0xff; code = bytes[1]; idm = new IDm(Arrays.copyOfRange(bytes, 2, 10)); data = bytes; } else { length = 0; code = 0; idm = new IDm(null); data = FeliCa.EMPTY; } } public IDm getIDm() { return idm; } } public final static class PollingResponse extends Response { private final PMm pmm; public PollingResponse(byte[] bytes) { super(bytes); if (size() >= 18) { pmm = new PMm(Arrays.copyOfRange(data, 10, 18)); } else { pmm = new PMm(null); } } public PMm getPMm() { return pmm; } } public final static class ReadResponse extends Response { public static final byte[] EMPTY = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (byte) 0xFF, (byte) 0xFF }; private final byte[] blockData; public ReadResponse(byte[] rsp) { super((rsp == null || rsp.length < 12) ? ReadResponse.EMPTY : rsp); if (getStatusFlag1() == STA1_NORMAL && getBlockCount() > 0) { blockData = Arrays.copyOfRange(data, 13, data.length); } else { blockData = FeliCa.EMPTY; } } public int getStatusFlag1() { return data[10]; } public int getStatusFlag2() { return data[11]; } public int getBlockCount() { return (data.length > 12) ? (0xFF & data[12]) : 0; } public byte[] getBlockData() { return blockData; } public boolean isOkey() { return getStatusFlag1() == STA1_NORMAL; } } public final static class WriteResponse extends Response { public WriteResponse(byte[] rsp) { super((rsp == null || rsp.length < 12) ? ReadResponse.EMPTY : rsp); } public int getStatusFlag1() { return data[0]; } public int getStatusFlag2() { return data[1]; } public boolean isOkey() { return getStatusFlag1() == STA1_NORMAL; } } public final static class Tag { private final NfcF nfcTag; private boolean isFeliCaLite; private int sys; private IDm idm; private PMm pmm; public Tag(NfcF tag) { nfcTag = tag; sys = SystemCode.toInt(tag.getSystemCode()); idm = new IDm(tag.getTag().getId()); pmm = new PMm(tag.getManufacturer()); } public int getSystemCode() { return sys; } public IDm getIDm() { return idm; } public PMm getPMm() { return pmm; } public boolean checkFeliCaLite() { isFeliCaLite = !polling(SYS_FELICA_LITE).getIDm().isEmpty(); return isFeliCaLite; } public boolean isFeliCaLite() { return isFeliCaLite; } public PollingResponse polling(int systemCode) { Command cmd = new Command(CMD_POLLING, new byte[] { (byte) (systemCode >> 8), (byte) (systemCode & 0xff), (byte) 0x01, (byte) 0x00 }); PollingResponse r = new PollingResponse(transceive(cmd)); idm = r.getIDm(); pmm = r.getPMm(); return r; } public PollingResponse polling() { Command cmd = new Command(CMD_POLLING, new byte[] { (byte) (SYS_FELICA_LITE >> 8), (byte) (SYS_FELICA_LITE & 0xff), (byte) 0x01, (byte) 0x00 }); PollingResponse r = new PollingResponse(transceive(cmd)); idm = r.getIDm(); pmm = r.getPMm(); return r; } public final SystemCode[] getSystemCodeList() { final Command cmd = new Command(CMD_REQUEST_SYSTEMCODE, idm); final byte[] bytes = transceive(cmd); final int num = (int) bytes[10]; final SystemCode ret[] = new SystemCode[num]; for (int i = 0; i < num; ++i) { ret[i] = new SystemCode(Arrays.copyOfRange(bytes, 11 + i * 2, 13 + i * 2)); } return ret; } public ServiceCode[] getServiceCodeList() { ArrayList<ServiceCode> ret = new ArrayList<ServiceCode>(); int index = 1; while (true) { byte[] bytes = searchServiceCode(index); if (bytes.length != 2 && bytes.length != 4) break; if (bytes.length == 2) { if (bytes[0] == (byte) 0xff && bytes[1] == (byte) 0xff) break; ret.add(new ServiceCode(bytes)); } ++index; } return ret.toArray(new ServiceCode[ret.size()]); } private byte[] searchServiceCode(int index) { Command cmd = new Command(CMD_SEARCH_SERVICECODE, idm, new byte[] { (byte) (index & 0xff), (byte) (index >> 8) }); byte[] bytes = transceive(cmd); if (bytes == null || bytes.length < 12 || bytes[1] != (byte) 0x0b) { return FeliCa.EMPTY; } return Arrays.copyOfRange(bytes, 10, bytes.length); } public ReadResponse readWithoutEncryption(ServiceCode code, byte addr) { byte[] bytes = code.getBytes(); Command cmd = new Command(CMD_READ_WO_ENCRYPTION, idm, new byte[] { (byte) 0x01, (byte) bytes[0], (byte) bytes[1], (byte) 0x01, (byte) 0x80, addr }); return new ReadResponse(transceive(cmd)); } public ReadResponse readWithoutEncryption(byte addr) { Command cmd = new Command(CMD_READ_WO_ENCRYPTION, idm, new byte[] { (byte) 0x01, (byte) (SRV_FELICA_LITE_READONLY >> 8), (byte) (SRV_FELICA_LITE_READONLY & 0xff), (byte) 0x01, (byte) 0x80, addr }); return new ReadResponse(transceive(cmd)); } public WriteResponse writeWithoutEncryption(ServiceCode code, byte addr, byte[] buff) { byte[] bytes = code.getBytes(); ByteBuffer b = ByteBuffer.allocate(22); b.put(new byte[] { (byte) 0x01, (byte) bytes[0], (byte) bytes[1], (byte) 0x01, (byte) 0x80, (byte) addr }); b.put(buff, 0, buff.length > 16 ? 16 : buff.length); Command cmd = new Command(CMD_WRITE_WO_ENCRYPTION, idm, b.array()); return new WriteResponse(transceive(cmd)); } public WriteResponse writeWithoutEncryption(byte addr, byte[] buff) { ByteBuffer b = ByteBuffer.allocate(22); b.put(new byte[] { (byte) 0x01, (byte) (SRV_FELICA_LITE_READWRITE >> 8), (byte) (SRV_FELICA_LITE_READWRITE & 0xff), (byte) 0x01, (byte) 0x80, addr }); b.put(buff, 0, buff.length > 16 ? 16 : buff.length); Command cmd = new Command(CMD_WRITE_WO_ENCRYPTION, idm, b.array()); return new WriteResponse(transceive(cmd)); } public MemoryConfigurationBlock getMemoryConfigBlock() { ReadResponse r = readWithoutEncryption((byte) 0x88); return (r != null) ? new MemoryConfigurationBlock(r.getBlockData()) : null; } @Override public String toString() { StringBuilder sb = new StringBuilder(); if (idm != null) { sb.append(idm.toString()); if (pmm != null) sb.append(pmm.toString()); } return sb.toString(); } public void connect() { try { nfcTag.connect(); } catch (Exception e) { } } public void close() { try { nfcTag.close(); } catch (Exception e) { } } public byte[] transceive(Command cmd) { try { return nfcTag.transceive(cmd.getBytes()); } catch (Exception e) { return Response.EMPTY; } } } // polling public static final byte CMD_POLLING = 0x00; public static final byte RSP_POLLING = 0x01; // request service public static final byte CMD_REQUEST_SERVICE = 0x02; public static final byte RSP_REQUEST_SERVICE = 0x03; // request RESPONSE public static final byte CMD_REQUEST_RESPONSE = 0x04; public static final byte RSP_REQUEST_RESPONSE = 0x05; // read without encryption public static final byte CMD_READ_WO_ENCRYPTION = 0x06; public static final byte RSP_READ_WO_ENCRYPTION = 0x07; // write without encryption public static final byte CMD_WRITE_WO_ENCRYPTION = 0x08; public static final byte RSP_WRITE_WO_ENCRYPTION = 0x09; // search service code public static final byte CMD_SEARCH_SERVICECODE = 0x0a; public static final byte RSP_SEARCH_SERVICECODE = 0x0b; // request system code public static final byte CMD_REQUEST_SYSTEMCODE = 0x0c; public static final byte RSP_REQUEST_SYSTEMCODE = 0x0d; // authentication 1 public static final byte CMD_AUTHENTICATION1 = 0x10; public static final byte RSP_AUTHENTICATION1 = 0x11; // authentication 2 public static final byte CMD_AUTHENTICATION2 = 0x12; public static final byte RSP_AUTHENTICATION2 = 0x13; // read public static final byte CMD_READ = 0x14; public static final byte RSP_READ = 0x15; // write public static final byte CMD_WRITE = 0x16; public static final byte RSP_WRITE = 0x17; public static final int SYS_ANY = 0xffff; public static final int SYS_FELICA_LITE = 0x88b4; public static final int SYS_COMMON = 0xfe00; public static final int SRV_FELICA_LITE_READONLY = 0x0b00; public static final int SRV_FELICA_LITE_READWRITE = 0x0900; public static final int STA1_NORMAL = 0x00; public static final int STA1_ERROR = 0xff; public static final int STA2_NORMAL = 0x00; public static final int STA2_ERROR_LENGTH = 0x01; public static final int STA2_ERROR_FLOWN = 0x02; public static final int STA2_ERROR_MEMORY = 0x70; public static final int STA2_ERROR_WRITELIMIT = 0x71; }
1034023415-test
src/com/sinpo/xnfc/tech/FeliCa.java
Java
gpl3
17,542
/* NFCard 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. NFCard 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 Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.tech; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import android.nfc.tech.IsoDep; import com.sinpo.xnfc.Util; public class Iso7816 { public static final byte[] EMPTY = { 0 }; protected byte[] data; protected Iso7816() { data = Iso7816.EMPTY; } protected Iso7816(byte[] bytes) { data = (bytes == null) ? Iso7816.EMPTY : bytes; } public boolean match(byte[] bytes) { return match(bytes, 0); } public boolean match(byte[] bytes, int start) { final byte[] data = this.data; if (data.length <= bytes.length - start) { for (final byte v : data) { if (v != bytes[start++]) return false; } } return true; } public boolean match(byte tag) { return (data.length == 1 && data[0] == tag); } public boolean match(short tag) { final byte[] data = this.data; if (data.length == 2) { final byte d0 = (byte) (0x000000FF & tag); final byte d1 = (byte) (0x000000FF & (tag >> 8)); return (data[0] == d0 && data[1] == d1); } return false; } public int size() { return data.length; } public byte[] getBytes() { return data; } @Override public String toString() { return Util.toHexString(data, 0, data.length); } public final static class ID extends Iso7816 { public ID(byte[] bytes) { super(bytes); } } public final static class Response extends Iso7816 { public static final byte[] EMPTY = {}; public static final byte[] ERROR = { 0x6F, 0x00 }; // SW_UNKNOWN public Response(byte[] bytes) { super((bytes == null || bytes.length < 2) ? Response.ERROR : bytes); } public byte getSw1() { return data[data.length - 2]; } public byte getSw2() { return data[data.length - 1]; } public short getSw12() { final byte[] d = this.data; int n = d.length; return (short) ((d[n - 2] << 8) | (0xFF & d[n - 1])); } public boolean isOkey() { return equalsSw12(SW_NO_ERROR); } public boolean equalsSw12(short val) { return getSw12() == val; } public int size() { return data.length - 2; } public byte[] getBytes() { return isOkey() ? Arrays.copyOfRange(data, 0, size()) : Response.EMPTY; } } public final static class BerT extends Iso7816 { // tag template public static final byte TMPL_FCP = 0x62; // File Control Parameters public static final byte TMPL_FMD = 0x64; // File Management Data public static final byte TMPL_FCI = 0x6F; // FCP and FMD // proprietary information public final static BerT CLASS_PRI = new BerT((byte) 0xA5); // short EF identifier public final static BerT CLASS_SFI = new BerT((byte) 0x88); // dedicated file name public final static BerT CLASS_DFN = new BerT((byte) 0x84); // application data object public final static BerT CLASS_ADO = new BerT((byte) 0x61); // application id public final static BerT CLASS_AID = new BerT((byte) 0x4F); public static int test(byte[] bytes, int start) { int len = 1; if ((bytes[start] & 0x1F) == 0x1F) { while ((bytes[start + len] & 0x80) == 0x80) ++len; ++len; } return len; } public static BerT read(byte[] bytes, int start) { return new BerT(Arrays.copyOfRange(bytes, start, start + test(bytes, start))); } public BerT(byte tag) { this(new byte[] { tag }); } public BerT(short tag) { this(new byte[] { (byte) (0x000000FF & (tag >> 8)), (byte) (0x000000FF & tag) }); } public BerT(byte[] bytes) { super(bytes); } public boolean hasChild() { return ((data[0] & 0x20) == 0x20); } } public final static class BerL extends Iso7816 { private final int val; public static int test(byte[] bytes, int start) { int len = 1; if ((bytes[start] & 0x80) == 0x80) { len += bytes[start] & 0x07; } return len; } public static int calc(byte[] bytes, int start) { if ((bytes[start] & 0x80) == 0x80) { int v = 0; int e = start + bytes[start] & 0x07; while (++start <= e) { v <<= 8; v |= bytes[start] & 0xFF; } return v; } return bytes[start]; } public static BerL read(byte[] bytes, int start) { return new BerL(Arrays.copyOfRange(bytes, start, start + test(bytes, start))); } public BerL(byte[] bytes) { super(bytes); val = calc(bytes, 0); } public int toInt() { return val; } } public final static class BerV extends Iso7816 { public static BerV read(byte[] bytes, int start, int len) { return new BerV(Arrays.copyOfRange(bytes, start, start + len)); } public BerV(byte[] bytes) { super(bytes); } } public final static class BerTLV extends Iso7816 { public static int test(byte[] bytes, int start) { final int lt = BerT.test(bytes, start); final int ll = BerL.test(bytes, start + lt); final int lv = BerL.calc(bytes, start + lt); return lt + ll + lv; } public static BerTLV read(Iso7816 obj) { return read(obj.getBytes(), 0); } public static BerTLV read(byte[] bytes, int start) { int s = start; final BerT t = BerT.read(bytes, s); s += t.size(); final BerL l = BerL.read(bytes, s); s += l.size(); final BerV v = BerV.read(bytes, s, l.toInt()); s += v.size(); final BerTLV tlv = new BerTLV(t, l, v); tlv.data = Arrays.copyOfRange(bytes, start, s); return tlv; } public static ArrayList<BerTLV> readList(Iso7816 obj) { return readList(obj.getBytes()); } public static ArrayList<BerTLV> readList(final byte[] data) { final ArrayList<BerTLV> ret = new ArrayList<BerTLV>(); int start = 0; int end = data.length - 3; while (start < end) { final BerTLV tlv = read(data, start); ret.add(tlv); start += tlv.size(); } return ret; } public final BerT t; public final BerL l; public final BerV v; public BerTLV(BerT t, BerL l, BerV v) { this.t = t; this.l = l; this.v = v; } public BerTLV getChildByTag(BerT tag) { if (t.hasChild()) { final byte[] raw = v.getBytes(); int start = 0; int end = raw.length; while (start < end) { if (tag.match(raw, start)) return read(raw, start); start += test(raw, start); } } return null; } public BerTLV getChild(int index) { if (t.hasChild()) { final byte[] raw = v.getBytes(); int start = 0; int end = raw.length; int i = 0; while (start < end) { if (i++ == index) return read(raw, start); start += test(raw, start); } } return null; } } public final static class Tag { private final IsoDep nfcTag; private ID id; public Tag(IsoDep tag) { nfcTag = tag; id = new ID(tag.getTag().getId()); } public ID getID() { return id; } public Response verify() { final byte[] cmd = { (byte) 0x00, // CLA Class (byte) 0x20, // INS Instruction (byte) 0x00, // P1 Parameter 1 (byte) 0x00, // P2 Parameter 2 (byte) 0x02, // Lc (byte) 0x12, (byte) 0x34, }; return new Response(transceive(cmd)); } public Response initPurchase(boolean isEP) { final byte[] cmd = { (byte) 0x80, // CLA Class (byte) 0x50, // INS Instruction (byte) 0x01, // P1 Parameter 1 (byte) (isEP ? 2 : 1), // P2 Parameter 2 (byte) 0x0B, // Lc (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x11, (byte) 0x22, (byte) 0x33, (byte) 0x44, (byte) 0x55, (byte) 0x66, (byte) 0x0F, // Le }; return new Response(transceive(cmd)); } public Response getBalance(boolean isEP) { final byte[] cmd = { (byte) 0x80, // CLA Class (byte) 0x5C, // INS Instruction (byte) 0x00, // P1 Parameter 1 (byte) (isEP ? 2 : 1), // P2 Parameter 2 (byte) 0x04, // Le }; return new Response(transceive(cmd)); } public Response readRecord(int sfi, int index) { final byte[] cmd = { (byte) 0x00, // CLA Class (byte) 0xB2, // INS Instruction (byte) index, // P1 Parameter 1 (byte) ((sfi << 3) | 0x04), // P2 Parameter 2 (byte) 0x00, // Le }; return new Response(transceive(cmd)); } public Response readRecord(int sfi) { final byte[] cmd = { (byte) 0x00, // CLA Class (byte) 0xB2, // INS Instruction (byte) 0x01, // P1 Parameter 1 (byte) ((sfi << 3) | 0x05), // P2 Parameter 2 (byte) 0x00, // Le }; return new Response(transceive(cmd)); } public Response readBinary(int sfi) { final byte[] cmd = { (byte) 0x00, // CLA Class (byte) 0xB0, // INS Instruction (byte) (0x00000080 | (sfi & 0x1F)), // P1 Parameter 1 (byte) 0x00, // P2 Parameter 2 (byte) 0x00, // Le }; return new Response(transceive(cmd)); } public Response readData(int sfi) { final byte[] cmd = { (byte) 0x80, // CLA Class (byte) 0xCA, // INS Instruction (byte) 0x00, // P1 Parameter 1 (byte) (sfi & 0x1F), // P2 Parameter 2 (byte) 0x00, // Le }; return new Response(transceive(cmd)); } public Response selectByID(byte... name) { ByteBuffer buff = ByteBuffer.allocate(name.length + 6); buff.put((byte) 0x00) // CLA Class .put((byte) 0xA4) // INS Instruction .put((byte) 0x00) // P1 Parameter 1 .put((byte) 0x00) // P2 Parameter 2 .put((byte) name.length) // Lc .put(name).put((byte) 0x00); // Le return new Response(transceive(buff.array())); } public Response selectByName(byte... name) { ByteBuffer buff = ByteBuffer.allocate(name.length + 6); buff.put((byte) 0x00) // CLA Class .put((byte) 0xA4) // INS Instruction .put((byte) 0x04) // P1 Parameter 1 .put((byte) 0x00) // P2 Parameter 2 .put((byte) name.length) // Lc .put(name).put((byte) 0x00); // Le return new Response(transceive(buff.array())); } public void connect() { try { nfcTag.connect(); } catch (Exception e) { } } public void close() { try { nfcTag.close(); } catch (Exception e) { } } public byte[] transceive(final byte[] cmd) { try { return nfcTag.transceive(cmd); } catch (Exception e) { return Response.ERROR; } } } public static final short SW_NO_ERROR = (short) 0x9000; public static final short SW_BYTES_REMAINING_00 = 0x6100; public static final short SW_WRONG_LENGTH = 0x6700; public static final short SW_SECURITY_STATUS_NOT_SATISFIED = 0x6982; public static final short SW_FILE_INVALID = 0x6983; public static final short SW_DATA_INVALID = 0x6984; public static final short SW_CONDITIONS_NOT_SATISFIED = 0x6985; public static final short SW_COMMAND_NOT_ALLOWED = 0x6986; public static final short SW_APPLET_SELECT_FAILED = 0x6999; public static final short SW_WRONG_DATA = 0x6A80; public static final short SW_FUNC_NOT_SUPPORTED = 0x6A81; public static final short SW_FILE_NOT_FOUND = 0x6A82; public static final short SW_RECORD_NOT_FOUND = 0x6A83; public static final short SW_INCORRECT_P1P2 = 0x6A86; public static final short SW_WRONG_P1P2 = 0x6B00; public static final short SW_CORRECT_LENGTH_00 = 0x6C00; public static final short SW_INS_NOT_SUPPORTED = 0x6D00; public static final short SW_CLA_NOT_SUPPORTED = 0x6E00; public static final short SW_UNKNOWN = 0x6F00; public static final short SW_FILE_FULL = 0x6A84; }
1034023415-test
src/com/sinpo/xnfc/tech/Iso7816.java
Java
gpl3
11,867
/* NFCard 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. NFCard 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 Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc; public final class Util { private final static char[] HEX = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; private Util() { } public static byte[] toBytes(int a) { return new byte[] { (byte) (0x000000ff & (a >>> 24)), (byte) (0x000000ff & (a >>> 16)), (byte) (0x000000ff & (a >>> 8)), (byte) (0x000000ff & (a)) }; } public static int toInt(byte[] b, int s, int n) { int ret = 0; final int e = s + n; for (int i = s; i < e; ++i) { ret <<= 8; ret |= b[i] & 0xFF; } return ret; } public static int toIntR(byte[] b, int s, int n) { int ret = 0; for (int i = s; (i >= 0 && n > 0); --i, --n) { ret <<= 8; ret |= b[i] & 0xFF; } return ret; } public static int toInt(byte... b) { int ret = 0; for (final byte a : b) { ret <<= 8; ret |= a & 0xFF; } return ret; } public static String toHexString(byte[] d, int s, int n) { final char[] ret = new char[n * 2]; final int e = s + n; int x = 0; for (int i = s; i < e; ++i) { final byte v = d[i]; ret[x++] = HEX[0x0F & (v >> 4)]; ret[x++] = HEX[0x0F & v]; } return new String(ret); } public static String toHexStringR(byte[] d, int s, int n) { final char[] ret = new char[n * 2]; int x = 0; for (int i = s + n - 1; i >= s; --i) { final byte v = d[i]; ret[x++] = HEX[0x0F & (v >> 4)]; ret[x++] = HEX[0x0F & v]; } return new String(ret); } public static int parseInt(String txt, int radix, int def) { int ret; try { ret = Integer.valueOf(txt, radix); } catch (Exception e) { ret = def; } return ret; } public static String toAmountString(float value) { return String.format("%.2f", value); } }
1034023415-test
src/com/sinpo/xnfc/Util.java
Java
gpl3
2,494
/* NFCard 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. NFCard 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 Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.card; import android.content.res.Resources; import android.nfc.tech.NfcV; import com.sinpo.xnfc.R; import com.sinpo.xnfc.Util; final class VicinityCard { private static final int SYS_UNKNOWN = 0x00000000; private static final int SYS_SZLIB = 0x00010000; private static final int DEP_SZLIB_CENTER = 0x0100; private static final int DEP_SZLIB_NANSHAN = 0x0200; private static final int SRV_USER = 0x0001; private static final int SRV_BOOK = 0x0002; public static final int SW1_OK = 0x00; static String load(NfcV tech, Resources res) { String data = null; try { tech.connect(); int pos, BLKSIZE, BLKCNT; byte cmd[], rsp[], ID[], RAW[], STA[], flag, DSFID; ID = tech.getTag().getId(); if (ID == null || ID.length != 8) throw new Exception(); /*--------------------------------------------------------------*/ // get system information /*--------------------------------------------------------------*/ cmd = new byte[10]; cmd[0] = (byte) 0x22; // flag cmd[1] = (byte) 0x2B; // command System.arraycopy(ID, 0, cmd, 2, ID.length); // UID rsp = tech.transceive(cmd); if (rsp[0] != SW1_OK) throw new Exception(); pos = 10; flag = rsp[1]; DSFID = ((flag & 0x01) == 0x01) ? rsp[pos++] : 0; if ((flag & 0x02) == 0x02) pos++; if ((flag & 0x04) == 0x04) { BLKCNT = rsp[pos++] + 1; BLKSIZE = (rsp[pos++] & 0xF) + 1; } else { BLKCNT = BLKSIZE = 0; } /*--------------------------------------------------------------*/ // read first 8 block /*--------------------------------------------------------------*/ cmd = new byte[12]; cmd[0] = (byte) 0x22; // flag cmd[1] = (byte) 0x23; // command System.arraycopy(ID, 0, cmd, 2, ID.length); // UID cmd[10] = (byte) 0x00; // index of first block to get cmd[11] = (byte) 0x07; // block count, one less! (see ISO15693-3) rsp = tech.transceive(cmd); if (rsp[0] != SW1_OK) throw new Exception(); RAW = rsp; /*--------------------------------------------------------------*/ // read last block /*--------------------------------------------------------------*/ cmd[10] = (byte) (BLKCNT - 1); // index of first block to get cmd[11] = (byte) 0x00; // block count, one less! (see ISO15693-3) rsp = tech.transceive(cmd); if (rsp[0] != SW1_OK) throw new Exception(); STA = rsp; data = Util.toHexString(rsp, 0, rsp.length); /*--------------------------------------------------------------*/ // build result string /*--------------------------------------------------------------*/ final int type = parseType(DSFID, RAW, BLKSIZE); final String name = parseName(type, res); final String info = parseInfo(ID, res); final String extra = parseData(type, RAW, STA, BLKSIZE, res); data = CardManager.buildResult(name, info, extra, null); } catch (Exception e) { data = null; // data = e.getMessage(); } try { tech.close(); } catch (Exception e) { } return data; } private static int parseType(byte dsfid, byte[] raw, int blkSize) { int ret = SYS_UNKNOWN; if (blkSize == 4 && (raw[4] & 0x10) == 0x10 && (raw[14] & 0xAB) == 0xAB && (raw[13] & 0xE0) == 0xE0) { ret = SYS_SZLIB; if ((raw[13] & 0x0F) == 0x05) ret |= DEP_SZLIB_CENTER; else ret |= DEP_SZLIB_NANSHAN; if (raw[4] == 0x12) ret |= SRV_USER; else ret |= SRV_BOOK; } return ret; } private static String parseName(int type, Resources res) { if ((type & SYS_SZLIB) == SYS_SZLIB) { final String dep; if ((type & DEP_SZLIB_CENTER) == DEP_SZLIB_CENTER) dep = res.getString(R.string.name_szlib_center); else if ((type & DEP_SZLIB_NANSHAN) == DEP_SZLIB_NANSHAN) dep = res.getString(R.string.name_szlib_nanshan); else dep = null; final String srv; if ((type & SRV_BOOK) == SRV_BOOK) srv = res.getString(R.string.name_lib_booktag); else if ((type & SRV_USER) == SRV_USER) srv = res.getString(R.string.name_lib_readercard); else srv = null; if (dep != null && srv != null) return dep + " " + srv; } return res.getString(R.string.name_unknowntag); } private static String parseInfo(byte[] id, Resources res) { final StringBuilder r = new StringBuilder(); final String i = res.getString(R.string.lab_id); r.append("<b>").append(i).append("</b> ") .append(Util.toHexStringR(id, 0, id.length)); return r.toString(); } private static String parseData(int type, byte[] raw, byte[] sta, int blkSize, Resources res) { if ((type & SYS_SZLIB) == SYS_SZLIB) { return parseSzlibData(type, raw, sta, blkSize, res); } return null; } private static String parseSzlibData(int type, byte[] raw, byte[] sta, int blkSize, Resources res) { long id = 0; for (int i = 3; i > 0; --i) id = (id <<= 8) | (0x000000FF & raw[i]); for (int i = 8; i > 4; --i) id = (id <<= 8) | (0x000000FF & raw[i]); final String sid; if ((type & SRV_USER) == SRV_USER) sid = res.getString(R.string.lab_user_id); else sid = res.getString(R.string.lab_bktg_sn); final StringBuilder r = new StringBuilder(); r.append("<b>").append(sid).append(" <font color=\"teal\">"); r.append(String.format("%013d", id)).append("</font></b><br />"); final String scat; if ((type & SRV_BOOK) == SRV_BOOK) { final byte cat = raw[12]; if ((type & DEP_SZLIB_NANSHAN) == DEP_SZLIB_NANSHAN) { if (cat == 0x10) scat = res.getString(R.string.name_bkcat_soc); else if (cat == 0x20) { if (raw[11] == (byte) 0x84) scat = res.getString(R.string.name_bkcat_ltr); else scat = res.getString(R.string.name_bkcat_sci); } else scat = null; } else { scat = null; } if (scat != null) { final String scl = res.getString(R.string.lab_bkcat); r.append("<b>").append(scl).append("</b> ").append(scat) .append("<br />"); } } // final int len = raw.length; // for (int i = 1, n = 0; i < len; i += blkSize) { // final String blk = Util.toHexString(raw, i, blkSize); // r.append("<br />").append(n++).append(": ").append(blk); // } // final String blk = Util.toHexString(sta, 0, blkSize); // r.append("<br />S: ").append(blk); return r.toString(); } }
1034023415-test
src/com/sinpo/xnfc/card/VicinityCard.java
Java
gpl3
6,929
/* NFCard 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. NFCard 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 Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.card; import com.sinpo.xnfc.card.pboc.PbocCard; import android.content.IntentFilter; import android.content.res.Resources; import android.nfc.NfcAdapter; import android.nfc.Tag; import android.nfc.tech.IsoDep; import android.nfc.tech.NfcF; import android.nfc.tech.NfcV; import android.os.Parcelable; public final class CardManager { private static final String SP = "<br/><img src=\"spliter\"/><br/>"; public static String[][] TECHLISTS; public static IntentFilter[] FILTERS; static { try { TECHLISTS = new String[][] { { IsoDep.class.getName() }, { NfcV.class.getName() }, { NfcF.class.getName() }, }; FILTERS = new IntentFilter[] { new IntentFilter( NfcAdapter.ACTION_TECH_DISCOVERED, "*/*") }; } catch (Exception e) { } } public static String buildResult(String n, String i, String d, String x) { if (n == null) return null; final StringBuilder s = new StringBuilder(); s.append("<br/><b>").append(n).append("</b>"); if (i != null) s.append(SP).append(i); if (d != null) s.append(SP).append(d); if (x != null) s.append(SP).append(x); return s.append("<br/><br/>").toString(); } public static String load(Parcelable parcelable, Resources res) { final Tag tag = (Tag) parcelable; final IsoDep isodep = IsoDep.get(tag); if (isodep != null) { return PbocCard.load(isodep, res); } final NfcV nfcv = NfcV.get(tag); if (nfcv != null) { return VicinityCard.load(nfcv, res); } final NfcF nfcf = NfcF.get(tag); if (nfcf != null) { return OctopusCard.load(nfcf, res); } return null; } }
1034023415-test
src/com/sinpo/xnfc/card/CardManager.java
Java
gpl3
2,264