Foro de elhacker.net

Programación => .NET (C#, VB.NET, ASP) => Mensaje iniciado por: Mace Windu en 11 Enero 2009, 15:26 pm



Título: [C#] cifrar/descifrar en AES
Publicado por: Mace Windu en 11 Enero 2009, 15:26 pm
Bueno, el código está hecho en C# y corre perfectamente bajo VS 2008. Utiliza el famoso algoritmo de cifrado AES.

Namespaces utilizados:

  • System;
  • System.Security.Cryptography;

Argumentos:

  • PlainText: Texto a cifrar.
  • Password: Nuestra contraseña.
  • hashAlgorithm: El algoritmo para generar el hash, puede ser MD5 o SHA1.
  • SaltValue: Puede ser cualquier cadena.
  • InitialVector: Debe ser una cadena de 16 bytes, es decir, 16 caracteres.
  • PasswordIterations: Con uno o dos será suficiente.
  • KeySize: Puede ser cualquiera de estos tres valores: 128, 192 o 256.

Esta función cifra:

Código
  1. public static string Encrypt(string PlainText, string Password, string SaltValue, string hashAlgorithm, int PasswordIterations, string InitialVector, int KeySize)
  2.        {
  3.            try
  4.            {
  5.                byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
  6.                byte[] saltValueBytes = Encoding.ASCII.GetBytes(SaltValue);
  7.                byte[] plainTextBytes = Encoding.UTF8.GetBytes(PlainText);
  8.  
  9.                PasswordDeriveBytes password = new PasswordDeriveBytes(Password, saltValueBytes, hashAlgorithm, PasswordIterations);
  10.  
  11.                byte[] keyBytes = password.GetBytes(KeySize / 8);
  12.  
  13.                RijndaelManaged symmetricKey = new RijndaelManaged();
  14.  
  15.                symmetricKey.Mode = CipherMode.CBC;
  16.  
  17.                ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, InitialVectorBytes);
  18.  
  19.                MemoryStream memoryStream = new MemoryStream();
  20.  
  21.                CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
  22.  
  23.                cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
  24.  
  25.                cryptoStream.FlushFinalBlock();
  26.  
  27.                byte[] cipherTextBytes = memoryStream.ToArray();
  28.  
  29.                memoryStream.Close();
  30.                cryptoStream.Close();
  31.  
  32.                string cipherText = Convert.ToBase64String(cipherTextBytes);
  33.  
  34.                return cipherText;
  35.            }
  36.            catch
  37.            {
  38.                MessageBox.Show("The typed information is wrong. Please, check it.", "FoS TeaM", MessageBoxButtons.OK, MessageBoxIcon.Stop);
  39.                return null;
  40.            }
  41.        }

Y esta descifra:

Código
  1. public static string Decrypt(string PlainText, string Password, string SaltValue, string HashAlgorithm, int PasswordIterations, string InitialVector, int KeySize)
  2.        {
  3.            try
  4.            {
  5.                byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
  6.                byte[] saltValueBytes = Encoding.ASCII.GetBytes(SaltValue);
  7.  
  8.                byte[] cipherTextBytes = Convert.FromBase64String(PlainText);
  9.  
  10.                PasswordDeriveBytes password = new PasswordDeriveBytes(Password, saltValueBytes, HashAlgorithm, PasswordIterations);
  11.  
  12.                byte[] keyBytes = password.GetBytes(KeySize / 8);
  13.  
  14.                RijndaelManaged symmetricKey = new RijndaelManaged();
  15.  
  16.                symmetricKey.Mode = CipherMode.CBC;
  17.  
  18.                ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, InitialVectorBytes);
  19.  
  20.                MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
  21.  
  22.                CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
  23.  
  24.                byte[] plainTextBytes = new byte[cipherTextBytes.Length];
  25.  
  26.                int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
  27.  
  28.                memoryStream.Close();
  29.                cryptoStream.Close();
  30.  
  31.                string plainText = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
  32.  
  33.                return plainText;
  34.            }
  35.            catch
  36.            {
  37.                MessageBox.Show("The typed information is wrong. Please, check it.", "FoS TeaM", MessageBoxButtons.OK, MessageBoxIcon.Stop);
  38.                return null;
  39.            }
  40.        }

Salu2


Título: Re: [C#] cifrar/descifrar en AES
Publicado por: WODZAROD en 20 Diciembre 2010, 03:44 am
Hola, tienes alguna aplicación en Visual C# o en otro software de cifrado AES. Haber si me puedes facilitar una aplicacòn con tu ejemplo mostrado, te lo agradecería mucho.

Rómulo


Título: Re: [C#] cifrar/descifrar en AES
Publicado por: [D4N93R] en 20 Diciembre 2010, 04:10 am
Ese código lo posteó otra persona, en otro foro. Por favor editar el post y colocar la fuente original, sino será borrado.

Un saludo!


Título: Re: [C#] cifrar/descifrar en AES
Publicado por: Shell Root en 20 Diciembre 2010, 04:24 am
No creo que mi amigo Javier sea un copión. ES EL MISMO USUARIO. :D

PD: @[D4N93R], lo viste en WinJaNet?


Título: Re: [C#] cifrar/descifrar en AES
Publicado por: [D4N93R] en 20 Diciembre 2010, 04:56 am
Por casualidad alguien me había mandado eso hace tiempo para que lo revisara y me acordé, por eso llo busqué y encontré el mismo en varios foros, por lo que si es el autor todo lo que tiene es que ponerse como tal, eso es todo :) Tu sabes, para evitar problemas.

Un saludo!

PD: Pase lo que pase es un buen código, por lo que apenas él edite el post, lo pongo en Temas interesantes.! :)