13 mar 2012

[WinForm] – Encriptación y Desencriptación de archivos de Texto

 

Buen día! En esta oportunidad mostraremos cómo encriptar y desencriptar archivos de texto como por ejemplo un *.sql, y *.txt, que nos permite ocultar información privada que no queremos sea leída por algún extraño o cuando el archivo es netamente confidencial de una empresa. La clase con la que se va a trabajar es el System.Security.Cryptography. Empezaremos por crear una clase llamada CCryptorEngine :

   1: using System;
   2: using System.Collections.Generic;
   3: using System.Linq;
   4: using System.Text;
   5: using System.Security.Cryptography;
   6: using System.IO;
   7:  
   8: namespace WindowsFormsApplication1
   9: {
  10:     class CCryptorEngine
  11:     {
  12:         private string key;
  13:         //constructor
  14:         public CCryptorEngine()
  15:         {
  16:             /* Establecer una clave. La misma clave
  17:              debe ser utilizada para descifrar
  18:              los datos que son cifrados con esta clave.
  19:              pueden ser los caracteres que uno desee*/
  20:             key = "http://ejemplosdotnet.blogspot.com/";
  21:         }
  22:  
  23:  
  24:         public string Encriptar(string texto)
  25:         {
  26:  
  27:             //arreglo de bytes donde guardaremos la llave
  28:             byte[] keyArray;
  29:             //arreglo de bytes donde guardaremos el texto
  30:             //que vamos a encriptar
  31:             byte[] Arreglo_a_Cifrar = UTF8Encoding.UTF8.GetBytes(texto);
  32:  
  33:             //se utilizan las clases de encriptación
  34:             //provistas por el Framework
  35:             //Algoritmo MD5
  36:             MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
  37:             //se guarda la llave para que se le realice
  38:             //hashing
  39:             keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
  40:  
  41:             hashmd5.Clear();
  42:  
  43:             //Algoritmo 3DAS
  44:             TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
  45:  
  46:             tdes.Key = keyArray;
  47:             tdes.Mode = CipherMode.ECB;
  48:             tdes.Padding = PaddingMode.PKCS7;
  49:  
  50:             //se empieza con la transformación de la cadena
  51:             ICryptoTransform cTransform = tdes.CreateEncryptor();
  52:  
  53:             //arreglo de bytes donde se guarda la
  54:             //cadena cifrada
  55:             byte[] ArrayResultado = cTransform.TransformFinalBlock(Arreglo_a_Cifrar, 0, Arreglo_a_Cifrar.Length);
  56:  
  57:             tdes.Clear();
  58:  
  59:             //se regresa el resultado en forma de una cadena
  60:             return Convert.ToBase64String(ArrayResultado, 0, ArrayResultado.Length);
  61:         }
  62:  
  63:  
  64:         public string Desencriptar(string textoEncriptado)
  65:         {
  66:             byte[] keyArray;
  67:             //convierte el texto en una secuencia de bytes
  68:             byte[] Array_a_Descifrar = Convert.FromBase64String(textoEncriptado);
  69:  
  70:             //se llama a las clases que tienen los algoritmos
  71:             //de encriptación se le aplica hashing
  72:             //algoritmo MD5
  73:             MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
  74:  
  75:             keyArray = hashmd5.ComputeHash(
  76:             UTF8Encoding.UTF8.GetBytes(key));
  77:  
  78:             hashmd5.Clear();
  79:  
  80:             TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
  81:  
  82:             tdes.Key = keyArray;
  83:             tdes.Mode = CipherMode.ECB;
  84:             tdes.Padding = PaddingMode.PKCS7;
  85:  
  86:             ICryptoTransform cTransform = tdes.CreateDecryptor();
  87:  
  88:             byte[] resultArray =
  89:             cTransform.TransformFinalBlock(Array_a_Descifrar, 0, Array_a_Descifrar.Length);
  90:  
  91:             tdes.Clear();
  92:             //se regresa en forma de cadena
  93:             return UTF8Encoding.UTF8.GetString(resultArray);
  94:         }
  95:     }
  96: }

Recuerden esto que si por algún motivo encriptan un archivo de texto  con un KEY y luego modifican el KEY y quieren desencriptar con el KEY modificado no se va a poder. Se encripta y se desencripta con el mismo KEY asi que tengan cuidado.


Creamos el siguiente Formulario Form1.cs con sus respectivos nombres tal y como se muestra en la imagen :




Y colocamos el siguiente código (Si es necesario modificar el nombre del Namespace lo modifican) :



   1: using System;
   2: using System.Collections.Generic;
   3: using System.ComponentModel;
   4: using System.Data;
   5: using System.Drawing;
   6: using System.Linq;
   7: using System.Text;
   8: using System.Windows.Forms;
   9: using System.IO;
  10:  
  11: namespace WindowsFormsApplication1
  12: {
  13:     public partial class Form1 : Form
  14:     {
  15:         public Form1()
  16:         {
  17:             InitializeComponent();
  18:         }
  19:  
  20:         CCryptorEngine crypto = new CCryptorEngine();
  21:         StreamWriter oSW = null;
  22:         StreamReader osR = null;
  23:         String destinoE = "";
  24:         String destinoD = "";
  25:  
  26:         private void Form1_Load(object sender, EventArgs e)
  27:         {
  28:             lblEstado.Text = "Normal";
  29:         }
  30:  
  31:         private void btnEncriptar_Click(object sender, EventArgs e)
  32:         {
  33:             try
  34:             {
  35:                 openFileDialog1.Title = "Seleccione la query o txt a Encriptar";
  36:                 openFileDialog1.DefaultExt = "sql";
  37:                 openFileDialog1.Filter = "*.sql - *.txt|*.sql;*.txt";
  38:                 openFileDialog1.FilterIndex = 1;
  39:                 openFileDialog1.FileName = string.Empty;
  40:  
  41:                 if (openFileDialog1.ShowDialog() == DialogResult.OK)
  42:                 {
  43:  
  44:                     if (openFileDialog1.FileName == "")
  45:                     {
  46:                         return;
  47:                     }
  48:                     else
  49:                     {
  50:                         txtQuery.Text = openFileDialog1.FileName;
  51:                         destinoE = System.IO.Path.GetDirectoryName(openFileDialog1.FileName) + "\\encriptado_" + Path.GetFileName(openFileDialog1.FileName);
  52:                         txtDestino.Text = destinoE;
  53:                     }
  54:                     lblEstado.Text = "Normal";
  55:                     lblEstado.Update();
  56:                 }
  57:             }
  58:             catch (Exception ex)
  59:             {
  60:                 MessageBox.Show(ex.Message, "Error");
  61:             }
  62:         }
  63:  
  64:         private void btnDesencriptar_Click(object sender, EventArgs e)
  65:         {
  66:             try
  67:             {
  68:                 openFileDialog1.Title = "Seleccione la query o txt a Desencriptar";
  69:                 openFileDialog1.DefaultExt = "txt";
  70:                 openFileDialog1.Filter = "*.txt|*.txt";
  71:                 openFileDialog1.FilterIndex = 1;
  72:                 openFileDialog1.FileName = string.Empty;
  73:  
  74:                 if (openFileDialog1.ShowDialog() == DialogResult.OK)
  75:                 {
  76:  
  77:                     if (openFileDialog1.FileName == "")
  78:                     {
  79:                         return;
  80:                     }
  81:                     else
  82:                     {
  83:                         txtQuery2.Text = openFileDialog1.FileName;
  84:                         destinoD = System.IO.Path.GetDirectoryName(openFileDialog1.FileName) + "\\desencriptado_" + Path.GetFileName(openFileDialog1.FileName);
  85:                         txtDestino2.Text = destinoD;
  86:                     }
  87:                     lblEstado.Text = "Normal";
  88:                     lblEstado.Update();
  89:                 }
  90:             }
  91:             catch (Exception ex)
  92:             {
  93:                 MessageBox.Show(ex.Message, "Error");
  94:             }
  95:         }
  96:  
  97:         private void btnE_Click(object sender, EventArgs e)
  98:         {
  99:             if (txtQuery.Text.Trim().Length == 0)
 100:             {
 101:                 MessageBox.Show("Seleccione la query ó txt encryptar!", "Advertencia!", MessageBoxButtons.OK, MessageBoxIcon.Information);
 102:             }
 103:             else
 104:             {
 105:                 try
 106:                 {
 107:                     lblEstado.Text = "...Procesando...";
 108:                     lblEstado.Update();
 109:                     StreamWriter oSW = new StreamWriter(txtDestino.Text);
 110:                     StreamReader osR = new StreamReader(txtQuery.Text);
 111:                     string txt = osR.ReadToEnd();
 112:  
 113:                     string Linea = crypto.Encriptar(txt);
 114:                     oSW.WriteLine(Linea);
 115:                     oSW.Flush();
 116:                     oSW.Close();
 117:                     osR.Close();
 118:                     lblEstado.Text = "Encriptado Correctamente!";
 119:                     lblEstado.Update();
 120:                 }
 121:                 catch (Exception ex)
 122:                 {
 123:                     oSW.Close();
 124:                     osR.Close();
 125:                     lblEstado.Text = "Error al Encriptar!";
 126:                     lblEstado.Update();
 127:                     MessageBox.Show(ex.Message, "Error");
 128:                 }
 129:             }
 130:         }
 131:  
 132:         private void btnD_Click(object sender, EventArgs e)
 133:         {
 134:             if (txtQuery2.Text.Trim().Length == 0)
 135:             {
 136:                 MessageBox.Show("Seleccione la query ó txt desencryptar!", "Advertencia!", MessageBoxButtons.OK, MessageBoxIcon.Information);
 137:             }
 138:             else
 139:             {
 140:                 try
 141:                 {
 142:                     lblEstado.Text = "...Procesando...";
 143:                     lblEstado.Update();
 144:                     oSW = new StreamWriter(txtDestino2.Text);
 145:                     osR = new StreamReader(txtQuery2.Text);
 146:                     string txt = osR.ReadToEnd();
 147:  
 148:                     string Linea = crypto.Desencriptar(txt);
 149:                     oSW.WriteLine(Linea);
 150:                     oSW.Flush();
 151:                     oSW.Close();
 152:                     osR.Close();
 153:                     lblEstado.Text = "Desencriptado Correctamente!";
 154:                     lblEstado.Update();
 155:                 }
 156:                 catch (Exception ex)
 157:                 {
 158:                     oSW.Close();
 159:                     osR.Close();
 160:                     lblEstado.Text = "Error al Desencriptar!";
 161:                     lblEstado.Update();
 162:                     MessageBox.Show(ex.Message, "Error");
 163:                 }
 164:             }
 165:         }
 166:     }
 167: }

Resultado :


 imageseedd


Espero les haya sido de mucho utilidad. Hasta Pronto!!.

5 comentarios:

  1. Este comentario ha sido eliminado por el autor.

    ResponderEliminar
  2. MUCHAS GRACIAS, ME AYUDASTE MUCHO

    ResponderEliminar
  3. Donde descargo el programa amigo?

    ResponderEliminar
  4. genial solo me faltaba la parte del openfildialog y como obtener al path. habia visto como se hacia por consolapero yo queria hacer mi propio winform. apenas llego a casa lo hago a ver que sale

    ResponderEliminar