Wednesday, May 31, 2006

FIRMAR DOCUMENTO



Hasta ahora se ha mostrado como pasar un txt a pdf, este que es un archivo binario se le puede aplicar la funcion hash, luego se crean las respactivas claves publicas y privadas, validas para cifrar y firmar respectivamente.
Ahora es el turno de firmar el documento, para esto se debe tener un documento al que firmar, ya que la firma digital no existe por si sola, cada usuario involucrado en el proceso (emisor y receptor), poseen sus correspondientes claves. Por ahora solo se leeran los archivos que se almacenen en la carpeta Debug del programa, mas adelante esto se deberá conectar a una base de datos para dar mayor seguridad al esquema general, tema que se mostrará mas adelante.

http://rapidshare.de/files/21855035/EnviarRecibirFirma.rar.html

En este enlace se puede bajar el archivo correspondiente a este programa, falta aun la parte de comprobacion de la firma, se separó el firmar y comprobar para tener una mejor visualizacion del tema, en la mayoria de los ejemplos encontrados esta todo en una misma hoja, esta bien pero no es lo real, ya que los documentos o mensajes son enviados de un lugar a otro.

Tuesday, May 30, 2006

CREAR CLAVES PRIVADAS Y PUBLICAS


Hola a todos, veremos a continuacion como crear claves publicas y privadas para el cifrado y la firma digital.
Diremos primero que ocupamos la clase del algoritmo RSA, estas claves son ocupadas por los distintos usuarios que actuan en el intercambio de mensajes o documentos, ocupamos la clave publica para cifrar informacion, y ocupamos la clave privada para adjuntar una firma a los distintos documentos, pueden adjuntarse varias firmas si es necesario.

Esto se realiza a traves de la clase:

  • RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

Clave Privada:

  • RSA.ToXmlString(true);
  • RSA.ExportParameters(true);

Clave Publica:

  • RSA.ToXmlString(false);
  • RSA.ExportParameters(true);

El codigo es el siguiente, los datos se guardan en archivos .xml:


using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace CrearClavesPublicasPrivadas
{
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Button button1;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Label label1;
private System.ComponentModel.Container components = null;
public Form1()
{
InitializeComponent();
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Código generado por el Diseñador de Windows Forms
///


/// Método necesario para admitir el Diseñador. No se puede modificar
/// el contenido del método con el editor de código.
///

private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.textBox1 = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// button1
//
this.button1.Font = new System.Drawing.Font("Courier New", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.button1.Location = new System.Drawing.Point(8, 8);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(104, 48);
this.button1.TabIndex = 0;
this.button1.Text = "Generar claves";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// textBox1
//
this.textBox1.Font = new System.Drawing.Font("Courier New", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.textBox1.Location = new System.Drawing.Point(120, 40);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(144, 26);
this.textBox1.TabIndex = 1;
this.textBox1.Text = "";
//
// label1
//
this.label1.Location = new System.Drawing.Point(120, 8);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(152, 24);
this.label1.TabIndex = 2;
this.label1.Text = "Nombre clave";
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(280, 94);
this.Controls.Add(this.label1);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.button1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void button1_Click(object sender, System.EventArgs e)
{
if(textBox1.Text != "")
{
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(4096);
string PCB = RSA.ToXmlString(true);
string CPubB = RSA.ToXmlString(false);
string nombre = textBox1.Text;
nombre += "PCB.xml";
StreamWriter PCAwriter = new StreamWriter(nombre);
PCAwriter.Write(PCB);
PCAwriter.Close();
string nombre2 = textBox1.Text;
nombre2 += "CPubB.xml";
StreamWriter CPubAwriter = new StreamWriter(nombre2);
CPubAwriter.Write(CPubB);
CPubAwriter.Close();
MessageBox.Show("LAS CLAVES FUERON CREADAS CON EXITO","",MessageBoxButtons.OK,MessageBoxIcon.Asterisk);
}
else
{
MessageBox.Show("DEBE LLENAR EL CAMPO NOMBRE CLAVE.", "",MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

Wednesday, May 17, 2006

CREAR VALOR HASH



La funcion Hash, se utiliza en los metodos de encriptacion, lo que hace es hacer un resumen del mensaje utilizado, por ejemplo en el proceso de firma digital se aplica la funcion al documento o mensaje a enviar, ya que los algoritmos de cifrado asimetricos son lentos y no soportan grandes cantidades de bits, pero por ahora eso es otra historia.
La imagen (aunque no muy buena), muestra un texto original, que es donde se ingresa un texto, en las otras pantallas muestra las distintas formas de ver el valor hash generado...
Por ahora nada mas...

using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace visualSha1
{
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.TextBox textBox2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox textBox3;
private System.Windows.Forms.TextBox textBox4;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label4;
private System.ComponentModel.Container components = null;
public Form1()
{
InitializeComponent();
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Código generado por el Diseñador de Windows Forms
private void InitializeComponent()
{
this.textBox1 = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.textBox2 = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.textBox3 = new System.Windows.Forms.TextBox();
this.textBox4 = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.SuspendLayout();
// textBox1
this.textBox1.Location = new System.Drawing.Point(8, 32);
this.textBox1.Multiline = true;
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(272, 72);
this.textBox1.TabIndex = 0;
this.textBox1.Text = "";
// button1
this.button1.Location = new System.Drawing.Point(32, 112);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(232, 32);
this.button1.TabIndex = 1;
this.button1.Text = "Crear Valor Hash SHA1";
this.button1.Click += new System.EventHandler(this.button1_Click);
// textBox2
this.textBox2.BackColor = System.Drawing.SystemColors.InfoText;
this.textBox2.ForeColor = System.Drawing.SystemColors.HighlightText;
this.textBox2.Location = new System.Drawing.Point(16, 176);
this.textBox2.Multiline = true;
this.textBox2.Name = "textBox2";
this.textBox2.ReadOnly = true;
this.textBox2.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.textBox2.Size = new System.Drawing.Size(272, 88);
this.textBox2.TabIndex = 2;
this.textBox2.Text = "";
// label1
this.label1.Font = new System.Drawing.Font("Courier New", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.label1.Location = new System.Drawing.Point(16, 8);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(144, 24);
this.label1.TabIndex = 3;
this.label1.Text = "Texto Original";
// label2
this.label2.Font = new System.Drawing.Font("Courier New", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.label2.Location = new System.Drawing.Point(16, 152);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(224, 24);
this.label2.TabIndex = 4;
this.label2.Text = "Texto Cifrado normal";
// textBox3
this.textBox3.BackColor = System.Drawing.SystemColors.InfoText;
this.textBox3.ForeColor = System.Drawing.SystemColors.HighlightText;
this.textBox3.Location = new System.Drawing.Point(304, 32);
this.textBox3.Multiline = true;
this.textBox3.Name = "textBox3";
this.textBox3.ReadOnly = true;
this.textBox3.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.textBox3.Size = new System.Drawing.Size(288, 104);
this.textBox3.TabIndex = 5;
this.textBox3.Text = "";
// textBox4
this.textBox4.BackColor = System.Drawing.SystemColors.InfoText;
this.textBox4.ForeColor = System.Drawing.SystemColors.HighlightText;
this.textBox4.Location = new System.Drawing.Point(304, 176);
this.textBox4.Multiline = true;
this.textBox4.Name = "textBox4";
this.textBox4.ReadOnly = true;
this.textBox4.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.textBox4.Size = new System.Drawing.Size(288, 88);
this.textBox4.TabIndex = 6;
this.textBox4.Text = "";
// label3
this.label3.Font = new System.Drawing.Font("Courier New", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.label3.Location = new System.Drawing.Point(304, 8);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(264, 24);
this.label3.TabIndex = 7;
this.label3.Text = "Texto Cifrado hexadecimal";
// label4
this.label4.Font = new System.Drawing.Font("Courier New", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.label4.Location = new System.Drawing.Point(304, 152);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(216, 24);
this.label4.TabIndex = 8;
this.label4.Text = "Texto Cifrado decimal";
// Form1
this.AutoScaleBaseSize = new System.Drawing.Size(8, 19);
this.ClientSize = new System.Drawing.Size(600, 270);
this.Controls.Add(this.label4);
this.Controls.Add(this.label3);
this.Controls.Add(this.textBox4);
this.Controls.Add(this.textBox3);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.textBox2);
this.Controls.Add(this.button1);
this.Controls.Add(this.textBox1);
this.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void button1_Click(object sender, System.EventArgs e)
{
if (textBox1.Text != "")
{
HashAlgorithm cod = new SHA1CryptoServiceProvider();
byte[] texto = Encoding.UTF8.GetBytes(textBox1.Text);
byte[] valor = cod.ComputeHash(texto);
cod.Clear();
textBox2.Text = Convert.ToBase64String(valor);
textBox3.Text = BitConverter.ToString(valor);
string suma;
foreach(byte b in valor)
{
suma = Convert.ToString(b);
textBox4.Text += suma + " ";
}
FileStream fs1 = new FileStream("original.arp",FileMode.Create,FileAccess.Write);
BinaryWriter sw = new BinaryWriter(fs1);
sw.Write(Encoding.ASCII.GetString(texto));
sw.Flush();
sw.Close();
fs1.Close();
fs1 = new FileStream("cifrado.arp",FileMode.Create,FileAccess.Write);
BinaryWriter bw = new BinaryWriter(fs1);
bw.Write(Convert.ToBase64String(valor));
bw.Close();
}
}
}
}

Friday, May 12, 2006

Pasando un archivo de texto a PDF


  • Esta vez mostraré como pasar un archivo de texto a formato pdf, es decir de un .txt a un .pdf, para esto hay que utilizar itextsharp.dll que lo puedes buscar en este enlace: http://itextsharp.sourceforge.net/ , encontraras informacion para poder hacer PDFs desde tu plataforma C#, es muy sencillo de usar y OpenSource, es decir, gratis... Recuerda que debes cargar la dll a traves de las referencias:
  • agregar referencia
  • Proyectos - examinar
  • Aceptar

Como vez es muy sencillo, obviamente debe existir un archivo .txt en el debug.


using System;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Text;
using System.Security.Cryptography;
namespace ArchivoaPDF
{
class Class1
{
static string LeerArchivo(string path)
{
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
byte[] abyt = new byte[Convert.ToInt32(fs.Length)];
fs.Read(abyt, 0, abyt.Length);
fs.Close();
return Encoding.UTF8.GetString(abyt);
}
[STAThread]
static void Main(string[] args)
{
Console.WriteLine("Ingrese nombre archivo : ");
string nombre = Console.ReadLine();
nombre += ".txt";
/****************************************************************/
string texto = LeerArchivo(nombre);
Console.WriteLine("");
Console.WriteLine(texto);
/****************************************************************/
Console.WriteLine("Ingrese nombre archivo PDF : ");
string pdfNombre = Console.ReadLine();
pdfNombre += ".pdf";;
/****************************************************************/
Document pdf = new Document();
PdfWriter.GetInstance(pdf,new FileStream(pdfNombre, FileMode.Create));
pdf.Open();
pdf.Add(new Paragraph(texto));
pdf.Close();
Console.ReadLine();
}
}
}

Eso sería por ahora...

Tuesday, May 09, 2006

LIBRO para DESARROLLADORES en MONO


Aca va la direccion del libro para desarrolladores en mono, para quienes aun no lo saben, el Proyecto Mono, es dsarrollado como una alternativa a .NET, el lenguaje utilizado es obviamente C#

http://www.monohispano.es/index.php/Portada


Faltan algunos capitulos por editar, pero esto esta en desarrollo, y tu tambien puedes ser parte de esto, no es necesario que seas un genio en la programacion...
Mas informacion en este enlace
Proyecto Mono

Monday, May 08, 2006

Leer caracteres


Esta es la publicacion del primer programa, lo denomino lector de caracteres, de que se trata, se ingresa un texto, se presiona enter y saldrá por pantalla, la lectura de los caracteres en ASCII y en binario.
El codigo es el siguiente:

using System;
using System.Security.Cryptography;
using System.Text;
namespace cadenas
{ public class leer
{
int c;
public void lee()
{ //se instancian las matrices para que no tengan valor nulo
char[] texto=new char[128];
byte[] texto2=new byte[128];
string[] binario=new string[128];
Console.WriteLine("Ingrese mensaje : ");
//se almacena la entrada en un string
string Mensaje = Console.ReadLine();
//se instancia la clase
UnicodeEncoding UE = new UnicodeEncoding();
//se toman los valores del texto ingresado como byte
//con este comando separamos el string a caracteres

byte[] MensajeBytes = UE.GetBytes(Mensaje);
//almacenamos los valores en matrices para su posterior uso
foreach(byte b in MensajeBytes)
{ if(b!=0)
{ texto[c]=Convert.ToChar(b);
texto2[c]=Convert.ToByte(b);
c=c+1; }
}
Console.WriteLine("Existen "+c+" caracteres en la frase \n");
for(int i=0;i<=(c-1);i++)
{ string b=Convert.ToString(texto2[i]);
binario[i]=DecBin(valor(b));
Console.WriteLine(texto[i]+"\t"+texto2[i]+"\t"+binario[i]); }
Console.ReadLine();
}
public static int valor(string NumBin)
{ return int.Parse(NumBin); }
public static string DecBin(int Num)
{/*conversion a codigo binario, recorriendo el texto*/
string NumBin="";
int LeeNum=1<<7;
for(int i=0;i<=7;i++)
{ /*se realiza una comparacion binaria bit a bit*/
if((Num & LeeNum)!=0)
NumBin+="1";
else
NumBin+="0";
Num<<=1; }
return NumBin;
} } }
Por ultimo se instancia la clase:

using System;
namespace cadenas
{
class Class1
{
static void Main(string[] args)
{ leer l=new leer();
l.lee();
} } }

Friday, May 05, 2006

MALDITOS CODIGOS...


Hola a todos, estoy trabajando con C#, C Sharp, C gato o como demonio quieran llamarlos, todavia no aprendo a utilizar la version 2003 y ya tengo en mis manos la version 2005, bueno durante mi desarrollo he visitado una variedad de paginas que compartiré con ustedes, ademas de publicar los pequeños programas que he realizado, en relacion a archivos de texto, binarios, PDFs, y seguridad.
Espero poder interactuar con otros programadores a traves de este tiempo...
Desconozco el porcentaje de persinas que programa en este lenguaje, ya sea con Visual Studio .NET o con el Proyecto Mono de todas formas este será un lugar de ayuda...