Proyecto AjpdSoft
Principal
· Inicio
· Buscar
· Contactar
· Descargas
· Enciclopedia
· Estadísticas
· Eventos
· Foros
· Manuales, Artículos
· Nuestra historia
· Quiénes somos
· Recomiéndanos
· Temas
· Top 10
· Trucos Delphi, PHP, Java, Visual Studio
· Tu cuenta
Descargas

Últimas Descargas
· Ejemplo acceso nativo a SQLite con ADO.Net en C# .Net

· AjpdSoft Acceso MySQL Android

· AjpdSoft Acceso SQLite C# ADO.NET

· AjpdSoft Acceso MySQL con ADO.NET en C#

· AjpdSoft Gestión Integral código fuente Delphi

· AjpdSoft Indexar Texto PDF C# iTextSharp

· AjpdSoft Capturar Pantalla C#

· AjpdSoft Gestión de Transportes Ficheros instalación manual

· AjpdSoft Separar Páginas PDF código fuente C# C Sharp .Net

· AjpdSoft Convertir Texto a PDF código fuente VB.Net

· AjpdSoft Generador y Lector códigos QR VB.Net

· AjpdSoft Socket VB.Net

· AjpdSoft Acceso nativo MySQL enlazado VB.Net

· AjpdSoft Acceso nativo MySQL VB.Net

· AjpdSoft Envío SMS puerto serie módem GSM VB.Net


Lo más descargado
· AjpdSoft Registro de OCX y DLL Código Fuente Delphi

· AjpdSoft Generador de códigos de barras

· AjpdSoft Conversor Hexadecimal, Decimal, Texto - Código Fuente Delphi

· Borland Database Desktop 7.0

· AjpdSoft Aviso cambio IP pública

· AjpdSoft Inventario PCs

· AjpdSoft Administración Bases de Datos Código Fuente Delphi

· AjpdSoft Facturación Código Fuente Delphi

· AjpdSoft Puerto Paralelo Código Fuente Delphi

· AjpdSoft Inventario PCs Código Fuente Delphi

· Cómo trabajar con tablas Paradox en red

· Cómo compilar un fichero MDB Base de Datos Access

· AjpdSoft Aviso cambio IP pública Código Fuente Delphi

· AjpdSoft Conexión BD Visual Basic .Net

· AjpdSoft Agenda Código Fuente Delphi

Términos enciclopedias
Últimos
· CSRF
Enc.: Informática

· SIG
Enc.: Informática

· Ruby
Enc.: Informática

· DATEDIFF (fecha1, fecha2)
Enc.: Funciones MySQL

· DaysBetween (fecha1, fecha2)
Enc.: Funciones Delphi

· Telnet
Enc.: Informática

· OSI
Enc.: Informática

· LTO
Enc.: Informática

· DoS, DDoS
Enc.: Informática

· NVRAM
Enc.: Informática

· DATE_SUB (date, INTERVAL)
Enc.: Funciones MySQL

· CURDATE ()
Enc.: Funciones MySQL

· DES
Enc.: Informática

· RSA
Enc.: Informática

· VMFS
Enc.: Informática


Lo más visitado

· Attrib
Enc.: Comandos Windows XP/Windows 2000/2003 (consola MS-DOS)

· At
Enc.: Comandos Windows XP/Windows 2000/2003 (consola MS-DOS)

· Arp
Enc.: Comandos Windows XP/Windows 2000/2003 (consola MS-DOS)

· URL
Enc.: Informática

· net use unidad: \\nombrepc\recursocompartido
Enc.: Comandos Windows XP/Windows 2000/2003 (consola MS-DOS)

· bootcfg addsw
Enc.: Comandos Windows XP/Windows 2000/2003 (consola MS-DOS)

· MSKSrvr.exe
Enc.: Procesos en memoria

· ODBC
Enc.: Informática

· Mozilla Firefox
Enc.: Programas/Software

· xcopy
Enc.: Comandos Windows XP/Windows 2000/2003 (consola MS-DOS)

· Call
Enc.: Comandos Windows XP/Windows 2000/2003 (consola MS-DOS)

· Gpupdate
Enc.: Comandos Windows XP/Windows 2000/2003 (consola MS-DOS)

· netstat -n
Enc.: Comandos Windows XP/Windows 2000/2003 (consola MS-DOS)

· Assoc
Enc.: Comandos Windows XP/Windows 2000/2003 (consola MS-DOS)

· net view
Enc.: Comandos Windows XP/Windows 2000/2003 (consola MS-DOS)
Eventos
Junio

DLMMJVS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
Consejos
Lenguajes
Selecciona Idioma de la Interfaz:

Webs recomendadas
Orasite.com



Coloca tu web aquí
Language english
English
Funciones para encriptar y desencriptar texto en Rijndael C# .Net
Lenguaje de programación Visual C# .Net

A continuación mostramos las funciones cifrarTextoAES y descifrarTextoAES para cifrar/descifrar (encriptar/desencriptar) una cadena de texto usando el método Advanced Encryption Standard (AES) ó Rijndael. Mostramos el código completo de la clase "cifrarAES.cs". Las funciones de cifrado y descifrado permitirán elegir el algoritmo hash de encriptación (MD5, SHA1) y el tamaño de la clave: 128, 192 o 256.


using System;
using System.Security.Cryptography;
using System.Text;
using System.IO;  

namespace AjpdSoftIndexarTextoFicherosPDF
{
    class cifrarAES
    {
        public string cifrarTextoAES (string textoCifrar, string palabraPaso, 
            string valorRGBSalt, string algoritmoEncriptacionHASH, 
            int iteraciones, string vectorInicial, int tamanoClave)
        {
            try
            {
                byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(vectorInicial);
                byte[] saltValueBytes = Encoding.ASCII.GetBytes(valorRGBSalt);
                byte[] plainTextBytes = Encoding.UTF8.GetBytes(textoCifrar);

                PasswordDeriveBytes password = 
                    new PasswordDeriveBytes(palabraPaso, saltValueBytes, 
                        algoritmoEncriptacionHASH, iteraciones);

                byte[] keyBytes = password.GetBytes(tamanoClave / 8);

                RijndaelManaged symmetricKey = new RijndaelManaged();

                symmetricKey.Mode = CipherMode.CBC;

                ICryptoTransform encryptor = 
                    symmetricKey.CreateEncryptor(keyBytes, InitialVectorBytes);

                MemoryStream memoryStream = new MemoryStream();

                CryptoStream cryptoStream = 
                    new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);

                cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);

                cryptoStream.FlushFinalBlock();

                byte[] cipherTextBytes = memoryStream.ToArray();

                memoryStream.Close();
                cryptoStream.Close();

                string textoCifradoFinal = Convert.ToBase64String(cipherTextBytes);

                return textoCifradoFinal;
            }
            catch
            {                
                return null;
            }
        }


        public string descifrarTextoAES (string textoCifrado, string palabraPaso, 
            string valorRGBSalt, string algoritmoEncriptacionHASH, 
            int iteraciones, string vectorInicial, int tamanoClave)
        {
            try
            {
                byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(vectorInicial);
                byte[] saltValueBytes = Encoding.ASCII.GetBytes(valorRGBSalt);

                byte[] cipherTextBytes = Convert.FromBase64String(textoCifrado);

                PasswordDeriveBytes password = 
                    new PasswordDeriveBytes(palabraPaso, saltValueBytes, 
                        algoritmoEncriptacionHASH, iteraciones);

                byte[] keyBytes = password.GetBytes(tamanoClave / 8);

                RijndaelManaged symmetricKey = new RijndaelManaged();

                symmetricKey.Mode = CipherMode.CBC;

                ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, InitialVectorBytes);

                MemoryStream memoryStream = new MemoryStream(cipherTextBytes);

                CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);

                byte[] plainTextBytes = new byte[cipherTextBytes.Length];

                int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);

                memoryStream.Close();
                cryptoStream.Close();

                string textoDescifradoFinal = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);

                return textoDescifradoFinal;
            }
            catch
            {
                return null;
            }
        }
    }
}
Un ejemplo de uso para cifrar:
       private void formIndexarPDF_FormClosed(object sender, FormClosedEventArgs e)
        {
            cifrarAES cifradoAES = new cifrarAES();
 
            proUtilidades.guardarValorConfiguracion("AjpdSoft");
            proUtilidades.guardarValorConfiguracion("BD.Contraseña", 
                cifradoAES.cifrarTextoAES (txtContrasena.Text, "AjpdSoft_Frase_Encriptado", 
                    "AjpdSoft_Frase_Encriptado", "MD5", 22, "1234567891234567", 128));
        }
En el ejemplo vemos que los argumentos que hay que pasar a la función "cifrarTextoAES" son:

* Texto a cifrar: el texto que queramos cifrar o encriptar con AES.
* Contraseña o palabra de paso: texto que se usará para generar el algoritmo de cifrado.
* valorRGBSalt: una cadena de texto cualquiera.
* Algoritmo de cifrado: puede ser "MD5" ó "SHA1".
* Iteraciones: número de iteraciones.
* Vector inicial: un texto o número de 16 bytes (16 caracteres)
* Tamaño clave: puede ser 128, 192 o 256.

Un ejemplo de uso para descifrar:
        private void formIndexarPDF_Load(object sender, EventArgs e)
        {                    
            cifrarAES cifradoAES = new cifrarAES();

            txtUsuario.Text = "AjpdSoft";
            txtContrasena.Text =
                cifradoAES.descifrarTextoAES(txtContrasena.Text, "AjpdSoft_Frase_Encriptado", 
                     "AjpdSoft_Frase_Encriptado", "MD5", 22, "1234567891234567", 128);
        }
En el ejemplo vemos que los argumentos que hay que pasar a la función "descifrarTextoAES" son:

* Texto a descifrar: el texto cifrado previamente a descrifrar por la función.
* Contraseña o palabra de paso: texto que se usará para generar el algoritmo de descifrado, debe coincidir con el que se usó para el cifrado.
* valorRGBSalt: una cadena de texto cualquiera, debe coincidir con el que se usó para el cifrado.
* Algoritmo de cifrado: puede ser "MD5" ó "SHA1", debe coincidir con el que se usó para el cifrado.
* Iteraciones: número de iteraciones, debe coincidir con el que se usó para el cifrado.
* Vector inicial: un texto o número de 16 bytes (16 caracteres), debe coincidir con el que se usó para el cifrado.
* Tamaño clave: puede ser 128, 192 o 256, debe coincidir con el que se usó para el cifrado.









Publicado el: 2012-07-11

Este sitio web NO CONTIENE malware, todos los programas con código fuente aquí. Autor: Alonso Javier Pérez Díaz