Foro de elhacker.net

Programación => .NET (C#, VB.NET, ASP) => Mensaje iniciado por: junxcosio en 14 Enero 2010, 00:52 am



Título: Cifrando y Descifrando C#
Publicado por: junxcosio en 14 Enero 2010, 00:52 am
Pues eso estoy realizando un par de funciones en C# y al cifrar va todo de cine, el problema es que al descifrar me da un error que dice "Datos incorrectos". En esta linea= datades=sec.Decrypt(data, false);

el codigo del programa es:
Código
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Security.Cryptography;
  6.  
  7. namespace encriptarstring
  8. {
  9.  
  10.    class Program
  11.    {
  12.        static string Cifrar(string texto)
  13.        {
  14.            byte[] dato;
  15.            byte[] dato_cifrado;
  16.  
  17.            RSACryptoServiceProvider sec = new RSACryptoServiceProvider();
  18.            dato=UTF8Encoding.UTF8.GetBytes(texto);
  19.            dato_cifrado=sec.Encrypt(dato,false);
  20.  
  21.            return Convert.ToBase64String(dato_cifrado, 0, dato_cifrado.Length);
  22.                      }
  23.        static string DesCifrar(string textocifrado)
  24.        {
  25.            RSACryptoServiceProvider sec = new RSACryptoServiceProvider();
  26.            byte[] data, datades;
  27.            data = Convert.FromBase64String(textocifrado);
  28.  
  29.            datades=sec.Decrypt(data, false); //<------AQUI DA EL ERROR
  30.  
  31.            return UTF8Encoding.UTF8.GetString(datades);
  32.  
  33.        }
  34.        static void Main(string[] args)
  35.        {
  36.            string texto = "Texto que quiero cifrar";
  37.            string Texto_Codificado;
  38.            Texto_Codificado = Cifrar(texto);
  39.  
  40.            Console.WriteLine("Texto tal cual: {0}", texto);
  41.            Console.WriteLine("Texto cifrado: {0}",Texto_Codificado);
  42.  
  43.            Console.WriteLine("Texto descifrado: {0}", DesCifrar(Texto_Codificado));
  44.  
  45.  
  46.            Console.ReadKey();
  47.  
  48.  
  49.        }
  50.    }
  51. }
  52.  
  53.  

A ver si hay suerte y alguno sabeis que es lo hago mal...

Un saludo.


Título: Re: Cifrando y Descifrando C#
Publicado por: raul338 en 14 Enero 2010, 01:22 am
Código
  1. void Main()
  2. {
  3.            string xD = ""; // Aca iria la llave
  4.  
  5.            Console.Write("Escriba texto a cifrar por RSA: ");
  6.            string s = Console.ReadLine();
  7.            byte[] matrix = Encoding.ASCII.GetBytes(s);
  8.  
  9.            Console.Write("Bytes de lo escrito: ");
  10.            foreach (byte i in matrix)
  11.                Console.Write(i.ToString() + "-");
  12.  
  13.            Console.WriteLine();
  14.            Console.WriteLine();
  15.  
  16.            RSACryptoServiceProvider rcsp = new RSACryptoServiceProvider();
  17.  
  18.            byte[] result = rcsp.Encrypt(matrix, true);
  19.            xD = rcsp.ToXmlString(true); // Guardamos las llave
  20.            Console.WriteLine(xD);
  21.  
  22.            Console.WriteLine("Texto cifrado: ");
  23.            Console.WriteLine(Encoding.ASCII.GetString(result));
  24.            Console.WriteLine();
  25.  
  26.            // Mostramos los bytes cifrados
  27.            foreach (byte i in result)
  28.                Console.Write(i.ToString() + "-");
  29.  
  30.            Console.WriteLine();
  31.            Console.WriteLine();
  32.  
  33.            RSACryptoServiceProvider rcsp2 = new RSACryptoServiceProvider();
  34.            //rcsp2.CspKeyContainerInfo = rcsp.CspKeyContainerInfo;
  35.            rcsp2.FromXmlString(xD); // Aca retomamos la llave
  36.            matrix = rcsp2.Decrypt(result, true);
  37.            Console.WriteLine("Texto descifrado: " + Encoding.ASCII.GetString(matrix));
  38.  
  39.  
  40.            Console.ReadLine();
  41. }
  42.  

Ese es mi codigo de prueba que hice hace unos dias, el RSA es asimetrico y genera una llave cuando encriptas, que la tienes que guardar y pasarsela cuando desencriptas, sino es imposible :P


Título: Re: Cifrando y Descifrando C#
Publicado por: b10s_0v3rr1d3 en 14 Enero 2010, 01:32 am

[se adelantaron xD]
con la exception que tira el error, en el msdn de win$ te lleva aqui:

http://support.microsoft.com/kb/842791/es

comenta que tienes que usar el mismo vector de inicializacion que usaste a la hora de cifrar los datos [en este caso seria 'sec', con una variable global ya funciona bien:]

Código
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Security.Cryptography;
  6.  
  7. namespace encriptarstring
  8. {
  9.  
  10.    class Program
  11.    {
  12.        public static RSACryptoServiceProvider sec = new RSACryptoServiceProvider();
  13.        static string Cifrar(string texto)
  14.        {
  15.            byte[] dato;
  16.            byte[] dato_cifrado;
  17.  
  18.            //RSACryptoServiceProvider sec = new RSACryptoServiceProvider();
  19.            dato = UTF8Encoding.UTF8.GetBytes(texto);
  20.            dato_cifrado = sec.Encrypt(dato, false);
  21.  
  22.            return Convert.ToBase64String(dato_cifrado, 0, dato_cifrado.Length);
  23.        }
  24.        static string DesCifrar(string textocifrado)
  25.        {
  26.            //RSACryptoServiceProvider sec = new RSACryptoServiceProvider();
  27.            byte[] data, datades;
  28.            data = Convert.FromBase64String(textocifrado);
  29.  
  30.            datades = sec.Decrypt(data, false); //<------AQUI DA EL ERROR
  31.  
  32.            return UTF8Encoding.UTF8.GetString(datades);
  33.  
  34.        }
  35.        static void Main(string[] args)
  36.        {
  37.            string texto = "Texto que quiero cifrar";
  38.            string Texto_Codificado;
  39.            Texto_Codificado = Cifrar(texto);
  40.  
  41.            Console.WriteLine("Texto tal cual: {0}", texto);
  42.            Console.WriteLine("Texto cifrado: {0}", Texto_Codificado);
  43.  
  44.            Console.WriteLine("Texto descifrado: {0}", DesCifrar(Texto_Codificado));
  45.  
  46.  
  47.            Console.ReadKey();
  48.  
  49.  
  50.        }
  51.    }
  52. }


Título: Re: Cifrando y Descifrando C#
Publicado por: raul338 en 14 Enero 2010, 14:02 pm
Claro, asi funciona, pero ahora con eso tienes un problema, intenta guardar el texto cifrado, cierra el programa, abrelo e intenta desifrarlo, como veras (o supondras) tira error, tienes que guardar el texto cifrado, y el XML de los parametros que te genera para desifrarlo. Suerte ;)


Título: Re: Cifrando y Descifrando C#
Publicado por: junxcosio en 14 Enero 2010, 15:22 pm
Perfecto he realizado los cambios segun me habeis dicho y efectivamente todo funciona y me ha quedado asi:

Código
  1. class Program
  2.    {
  3.        static string Cifrar(string texto)
  4.        {
  5.            byte[] dato;
  6.            byte[] dato_cifrado;
  7.  
  8.            RSACryptoServiceProvider sec = new RSACryptoServiceProvider();
  9.            dato=UTF8Encoding.UTF8.GetBytes(texto);
  10.            dato_cifrado=sec.Encrypt(dato,false);
  11.            Guardarllave(sec.ToXmlString(true));
  12.  
  13.            return Convert.ToBase64String(dato_cifrado, 0, dato_cifrado.Length);
  14.        }
  15.        static string DesCifrar(string textocifrado)
  16.        {
  17.            RSACryptoServiceProvider sec = new RSACryptoServiceProvider();
  18.            byte[] data, datades;
  19.            data = Convert.FromBase64String(textocifrado);
  20.            sec.FromXmlString(Leerllave());
  21.            datades=sec.Decrypt(data, false);
  22.  
  23.            return UTF8Encoding.UTF8.GetString(datades);
  24.  
  25.        }
  26.        static void Guardarllave(string llave)
  27.        {
  28.            XmlWriter w = XmlWriter.Create("llave.xml");
  29.            w.WriteComment("Fichero que guarda la llave de encriptacion, by JunXCosio");
  30.            w.WriteStartElement("Llave");
  31.            w.WriteElementString("key1",llave);
  32.            w.WriteEndElement();
  33.            w.Close();
  34.        }
  35.        static string Leerllave()
  36.        {
  37.            XmlReader r = XmlReader.Create("llave.xml");
  38.            r.ReadStartElement("Llave");
  39.            string KEY = r.ReadElementContentAsString();
  40.            r.Close();
  41.            return KEY;
  42.        }
  43.        static void Main(string[] args)
  44.        {
  45.            string texto = "Texto que quiero cifrar";
  46.            string Texto_Codificado;
  47.            Texto_Codificado = Cifrar(texto);
  48.  
  49.            Console.WriteLine("Texto tal cual: {0}", texto);
  50.            Console.WriteLine("Texto cifrado: {0}",Texto_Codificado);
  51.  
  52.            Console.WriteLine("Texto descifrado: {0}", DesCifrar(Texto_Codificado));
  53.  
  54.  
  55.            Console.ReadKey();
  56.  
  57.  
  58.        }
  59.    }
  60.  

Pero entonces tengo una duda, para poder descifrar siempre hay que tener el fichero xml??? por lo tanto siempre que se teng ese fichero se podra leer el texto cifrado...y si alguien obtiene dicho ficheroy tiene unos minimos conocimientos de .Net lo podra leer...curioso...

Voy a mirar otra cosa ya que esto no me vale...

Muchisimas gracias...


Título: Re: Cifrando y Descifrando C#
Publicado por: raul338 en 14 Enero 2010, 15:46 pm
Pero entonces tengo una duda, para poder descifrar siempre hay que tener el fichero xml??? por lo tanto siempre que se teng ese fichero se podra leer el texto cifrado...y si alguien obtiene dicho ficheroy tiene unos minimos conocimientos de .Net lo podra leer...curioso...

Bueno si, pero no creas que el .net te tiene que dar todo, tu mismo puedes re-cifrar ese XML, juntar varias capas de encriptacion, para asi tener algo sumamente cifrado. Puedes crear algun algoritmo que mezcle lo cifrado con el XML y punto. Usa tu imaginacion ;)


Título: Re: Cifrando y Descifrando C#
Publicado por: junxcosio en 15 Enero 2010, 10:41 am
ok, estoy ahora haciendo unas pruebas con el cifrado 3DES... cuando lo termine lo pongo por si le vale a alguien...porque lo que estoy haciendo es que la llave la cifro con el 3DES...

un saludo.