Java - Problemas descifrar fichero Algoritmo DES

 
Vista:

Problemas descifrar fichero Algoritmo DES

Publicado por Antonio (9 intervenciones) el 07/02/2007 09:30:17
Buenas,

Tengo un pequeño problema que no se como resolver. El problema en cuestión es que cifro un fichero xml con el algoritmo DES, guardando el fichero cifrado. Luego cuando intento descifrar el fichero cifrado, resulta que me lo descifra pero me mete un montón de basura (caracteres raros), que no aparece en el original.

Alguien sabe porque puede ocurrir esto.

Un ejemplo de lo que me aparece.

<num__hijo>2</num__hijo>
?3p??}B</apell1>
<apell2>B</ap???*?M?y <nombre>B</nombre>??P]??`? <sexo>V</sexo>
<fec__nacimiento>02/02/2KVicy?__nacimiento>
<fec__nacimiento__(????>N</fec__nacimiento__ficticia>
<lugar__nacimiento></lugar__nacimiento>
<lugar__residencia></lugar__residencia>
</lista__hijos>
<lista__hijos/>
</hijos>
<panel>
<observaciones__paises__transito>
<str?MkO??FRANCIA</string>??P]??`?Yu8@=??>OBS UK</string>
</observaciones__paises__transito>

Aqui un ejemplo del codigo que utilizo para cifrar y para descifrar sería igual pero descifrando.

Security.addProvider (new BouncyCastleProvider ()); // Usa provider BC
//
/* PASO 1: Crear e inicializar clave */
String textoPlano = "";

/*KeyGenerator keyGen = KeyGenerator.getInstance("DES");
keyGen.init(128);
Key clave = keyGen.generateKey();*/
//Key clave = KeyDES.ObtenerKey();

SecretKeySpec key = new SecretKeySpec (clave_simetrica, "DES");

/* PASO 2: Crear cifrador */
Cipher cifrador= Cipher.getInstance ("DES/ECB/PKCS7Padding","BC");

// Algoritmo DES
// Modo : ECB (Electronic Code Book)
//
/* PASO 3a: Inicializar cifrador en modo CIFRADO */
cifrador.init (Cipher.ENCRYPT_MODE, key);

File fichero_cifrado = new File ("C://Antonio//fichero_cifrado.xml");
System.out.println ("fichero_cifrado "+fichero_cifrado);
FileOutputStream fout = new FileOutputStream (fichero_cifrado);
BufferedOutputStream bout = new BufferedOutputStream (fout);

File fichero = new File ("C://Antonio//01022007_113154.xml");
byte[] bufferPlano = new byte[Integer.parseInt (String.valueOf (fichero.length ()))];
FileInputStream fin = new FileInputStream (fichero);
BufferedInputStream bin = new BufferedInputStream(fin);
int total = 0;
int bytesLeidos = bin.read (bufferPlano);
//int bytesLeidos = fin.read (bufferPlano);
//while(bytesLeidos != -1)
//{ // Mientras no se llegue al final del fichero
total = total + bytesLeidos;
System.out.println ("total "+total);
textoPlano = textoPlano + new String (bufferPlano);
//bytesLeidos = bin.read (bufferPlano,0, 1024);
//bytesLeidos = in.read (bufferPlano,0, 1024);
System.out.println ("bytesleidos "+bytesLeidos);
//}
bin.close ();
fin.close ();

byte[] textofinal = textoPlano.getBytes ();

/* Leer fichero de 1k en 1k y pasar fragmentos leidos al cifrador */
byte[] cipherText = cifrador.doFinal (textofinal,0,total);
System.out.println ("cipherText "+cipherText);
bout.write (cipherText);
//fout.write (cipherText);
System.out.println ("resultado "+new String (cipherText,"UTF-8"));
bout.close ();
fout.close ();

File fich_descif = AlgoritmoDES.Descifrador (clave_simetrica,fichero_cifrado);

return fichero_cifrado;

Gracias por vuestro tiempo.
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder

RE:Problemas descifrar fichero Algoritmo DES

Publicado por Angel (537 intervenciones) el 07/02/2007 09:50:09
Solo puedo dejarte esta dirección donde tiens ejemplos de encriptacion simetrica y asimetrica......
http://www.phptr.com/articles/article.asp?p=170967&seqNum=4&rl=1

Espero que te pueda ayudar,,,,un saludo.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

RE:Problemas descifrar fichero Algoritmo DES

Publicado por antonio (9 intervenciones) el 07/02/2007 10:18:32
Gracias las probaré ahora mismo.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

RE:Problemas descifrar fichero Algoritmo DES

Publicado por Angel (537 intervenciones) el 07/02/2007 10:31:37
Que he estado mirando el tema, por que tambien m interesa y he visto esta página,,,,

http://www3.uji.es/~vcholvi/teaching/java/cap.12.1/Cap.12.1.html

Parece k viene bien explicado..con varios ejemplos y demas

Un saludo.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

RE:Problemas descifrar fichero Algoritmo DES

Publicado por antonio (9 intervenciones) el 07/02/2007 10:32:36
Bueno el problema, me parece que no va a estar en el cifrado.

El problema me da que es a lo hora de leer en el fichero y de escribir en el fichero. He probado a cifrar y descifrar el chorro de bytes directamente sin guardarlo en fichero y me ha encriptado y desencriptado correctamente.

El problema es que cuando cifro el chorro de bytes, lo guardo en un fichero. Luego al leer el fichero cifrado leo el chorro de bytes y me da el xml corrupto.

Creo que el problema debe de estar ahí. Es que lo estoy leyendo o escribiendo mal?

EJEMPLOS:

public static File Cifrador (byte[] clave_simetrica) throws Exception
{

/* Cargar "provider" (sólo si no se usa el que viene por defecto) */
Security.addProvider (new BouncyCastleProvider ()); // Usa provider BC
//
/* PASO 1: Crear e inicializar clave */

String textoPlano = "";
SecretKeySpec key = new SecretKeySpec (clave_simetrica, "DES");

Cipher cifrador= Cipher.getInstance ("DES/ECB/PKCS7Padding","BC");

/* PASO 3a: Inicializar cifrador en modo CIFRADO */
cifrador.init (Cipher.ENCRYPT_MODE, key);
System.out.println ("Cifrador en modo cifrado 2");

File fichero_cifrado = new File ("C://Antonio//fichero_cifrado.xml");
//byte[] bufferPlano = new byte[1024];
FileOutputStream fout = new FileOutputStream (fichero_cifrado);
BufferedOutputStream bout = new BufferedOutputStream (fout);

File fichero = new File ("C://Antonio//01022007_113154.xml");
byte[] bufferPlano = new byte[Integer.parseInt (String.valueOf (fichero.length ()))];
FileInputStream fin = new FileInputStream (fichero);
BufferedInputStream bin = new BufferedInputStream(fin);
int total = 0;
int bytesLeidos = bin.read (bufferPlano);
total = total + bytesLeidos;
System.out.println ("total "+total);
textoPlano = textoPlano + new String (bufferPlano);
bin.close ();
fin.close ();

byte[] textofinal = textoPlano.getBytes ();

byte[] cipherText = cifrador.doFinal (textofinal,0,total);
bout.write (cipherText);
//fout.write (cipherText);
System.out.println ("resultado "+new String (cipherText,"UTF-8"));
bout.close ();
fout.close ();

File fich_descif = AlgoritmoDES.Descifrador (clave_simetrica,fichero_cifrado);

return fichero_cifrado;
}

public static File Descifrador (byte[] clave_simetrica, File fich_cif) throws Exception
{
Security.addProvider (new BouncyCastleProvider ()); // Usa provider BC
//
// PASO 1: Crear e inicializar clave
String texto = "";
System.out.println ("fich_cif.length "+fich_cif.length ());
byte[] bufferCifrado = new byte[Integer.parseInt (String.valueOf (fich_cif.length ()))];
System.out.println ("El fichero que le pasamos es "+fich_cif.getAbsolutePath ());
FileInputStream fin = new FileInputStream (fich_cif);
BufferedInputStream bin = new BufferedInputStream (fin);
File fichero_des = new File ("C://Antonio//fichero_descifrado.xml");
System.out.println ("fichero_des "+fichero_des);
FileOutputStream fout = new FileOutputStream (fichero_des);
BufferedOutputStream bout = new BufferedOutputStream (fout);

SecretKeySpec key = new SecretKeySpec (clave_simetrica, "DES");

// PASO 2: Crear cifrador
Cipher cifrador= Cipher.getInstance ("DES/ECB/PKCS7Padding","BC");
int total = 0;
cifrador.init (Cipher.DECRYPT_MODE, key);
int bytesLeidos = bin.read (bufferCifrado);
total = total + bytesLeidos;
System.out.println ("total "+total);
texto = texto + new String (bufferCifrado);
System.out.println ("bytesleidos "+bytesLeidos);
bin.close ();
fin.close ();

byte[] newPlainText = cifrador.doFinal (texto.getBytes ());

System.out.println ("resultado2 \n"+new String (newPlainText,"UTF-8"));

bout.write (newPlainText);
//fout.write (newPlainText);
System.out.println ("resultado "+new String (newPlainText,"UTF-8"));
bout.close ();
fout.close ();

return fichero_des;
}

¿Alguna idea?
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

RE:Problemas descifrar fichero Algoritmo DES

Publicado por Angel (537 intervenciones) el 07/02/2007 11:03:30
Prueba de esta forma

//leer fichero.
File fichero = new File ("D:/entrada.log");
StringBuffer stb = new StringBuffer();
InputStream fin = new FileInputStream (fichero);
int i ;
byte[] buffer=new byte[1000];
while( (i=(fin.read(buffer)))!=-1)
{
stb.append(new String(buffer,0,i));

}
fin.close();

//Aqui guardas los bytes leido y haces con ellos lo que quieras
byte[] byteDatos = new String(stb).getBytes();

//Escribir en fichero
File fichero2 = new File("D:/entradaCopia.log");
OutputStream out = new FileOutputStream(fichero2);
out.write(byteDatos);
out.close();

Suerte y un saludo
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

RE:Problemas descifrar fichero Algoritmo DES

Publicado por antonio (9 intervenciones) el 07/02/2007 12:04:25
Nada chico, esto sigue funcionando mal y casi estoy seguro que es a la hora de leer y escribir en los ficheros, ya que como te dije si lo hago directamente con el chorro de bytes me lo hace bien. Pero al meter el chorro de bytes en fichero, me genera mal el xml.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

RE:Problemas descifrar fichero Algoritmo DES

Publicado por Angel (537 intervenciones) el 07/02/2007 12:16:31
Kizas te den problemas los caracteres tipo < >....prueba con un fichero sin caracteres raros.....solo letras y numeros.........aver k pasa...

Un saludo
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

RE:Problemas descifrar fichero Algoritmo DES

Publicado por Antonio (9 intervenciones) el 08/02/2007 15:53:48
Buenas Angel,

Por fin he solucionado el asunto del cifrado con ficheros. El problema era que a la hora de leer o escribir en los ficheros, transformaba un string en array de bytes, con el método getBytes(), craso error, porque este metodo te obtiene una cadena de bytes, pero de la plataforma que estés usando, que no tienen porque ser los mismos que los que estás utilizando. Por ejemplo UTF-8 y ISOxxxxx. En fin un caos

Al final he dejado de utilizar ese método y lo he hecho de otra forma y asunto arreglado.

Gracias por todo.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

RE:Problemas descifrar fichero Algoritmo DES

Publicado por antonio (9 intervenciones) el 07/02/2007 13:03:44
Nada, con un fichero normal de texto, también mete caracteres extraños entre el texto.

Ya no se que puede ser.

Voy a probar con otro tipo de algoritmo simétrico.

Ya te comentaré.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar