Windows Phone 7 – Tutorial XXIX–Seguridad III – Encriptación de Datos II

En el anterior artículo vimos la encriptación HMAC, en este vamos a ver

 

Rfc2898DeriveBytes y AES para Encriptación de Datos

Para cifrar los datos de miradas indiscretas en un dispositivo de Windows 7, se necesita un cifrado de alta seguridad mecanismo que, a su vez, se basa en una clave de cifrado fuerte para soportar todos los intentos de romperla. El algoritmo Rfc2898DeriveBytes crea una clave en encriptación para usarlo en una encriotacion AES como password. En el siguiente ejemplo vamos a ver como utilizar estos dos algoritmos conjuntamente para construir un cifrado muy complicado de romper.

En este caso crearemos una solución con el nombre AESEncryption

image_thumb9

Nuestra interfaz de usuario seria de la siguiente manera

1 <Grid x:Name="LayoutRoot" Background="Transparent"> 2 <Grid.RowDefinitions> 3 <RowDefinition Height="Auto"/> 4 <RowDefinition Height="*"/> 5 </Grid.RowDefinitions> 6 <!--TitlePanel contains the name of the application and page title--> 7 <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="24,24,0,12"> 8 <TextBlock x:Name="ApplicationTitle" Text="CLASSIFIED" Style="{StaticResource PhoneTextNormalStyle}"/> 9 <TextBlock x:Name="PageTitle" Text="AES Encryption" Margin="-3,-8,0,0" Style="{StaticResource PhoneTextTitle1Style}"/> 10 </StackPanel> 11 <!--ContentPanel - place additional content here--> 12 <Grid x:Name="ContentGrid" Grid.Row="1"> 13 <TextBox Height="65" HorizontalAlignment="Left" Margin="6,41,0,0" Name="txtDataToEncrypt" Text="" VerticalAlignment="Top" Width="462" /> 14 <TextBlock Height="30" HorizontalAlignment="Left" Margin="20,21,0,0" Name="textBlock1" Text="Datos a encriptar:" VerticalAlignment="Top" Width="419" /> 15 <TextBox Height="72" HorizontalAlignment="Left" Margin="6,334,0,0" Name="txtPassword" Text="" VerticalAlignment="Top" Width="462" /> 16 <TextBlock Height="30" HorizontalAlignment="Left" Margin="20,310,0,0" Name="textBlock2" Text="Password" VerticalAlignment="Top" Width="346" /> 17 <TextBox Height="72" HorizontalAlignment="Left" Margin="6,426,0,0" Name="txtSalt" Text="" VerticalAlignment="Top" Width="462" /> 18 <TextBlock Height="36" HorizontalAlignment="Left" Margin="21,403,0,0" Name="textBlock3" Text="Salt:" VerticalAlignment="Top" Width="304" /> 19 <Button Content="Encrypt" Height="72" HorizontalAlignment="Left" Margin="20,504,0,0" Name="button1" VerticalAlignment="Top" Width="160" Click="button1_Click" 20 /> 21 <TextBlock Height="30" HorizontalAlignment="Left" Margin="24,101,0,0" Name="textBlock4" Text="Datos encriptados" VerticalAlignment="Top" Width="432" /> 22 <TextBox Height="72" HorizontalAlignment="Left" Margin="8,123,0,0" Name="txtEncryptedData" Text="" VerticalAlignment="Top" Width="460" /> 23 <TextBlock Height="27" HorizontalAlignment="Left" Margin="21,197,0,00" Name="textBlock5" Text="Datos Desencriptados" VerticalAlignment="Top" Width="435" /> 24 <TextBox Height="72" HorizontalAlignment="Left" Margin="13,221,0,0" Name="txtDecryptedData" Text="" VerticalAlignment="Top" Width="460" /> 25 </Grid> 26 </Grid> 27

Lo que nos daría la siguiente pantalla

image_thumb12

Vamos a encriptar el mensaje y desencriptarlo después, para el método de encriptación necesitaremos el mensaje a encriptar, la password y salt que iran como parámetros, utilizaremos la clase Rfc2898DerivedBytes para generar una key a partir de la password y salt, esta key se utilizara en el algoritmo AES para encriptar los datos. El código seria el siguiente

1 public string Encrypt(string dataToEncrypt, string password, string salt) 2 { 3 AesManaged aes = null; 4 MemoryStream memStream = null; 5 CryptoStream crStream = null; 6 try 7 { 8 //Generate a Key based on a Password and Salt 9 Rfc2898DeriveBytes rfc2898 = new Rfc2898DeriveBytes(password, 10 Encoding.UTF8.GetBytes(salt)); 11 //Create AES algorithm with 256 bit key and 128-bit block size 12 aes = new AesManaged(); 13 aes.Key = rfc2898.GetBytes(aes.KeySize / 8); 14 aes.IV = rfc2898.GetBytes(aes.BlockSize / 8); 15 memStream = new MemoryStream(); 16 crStream = new CryptoStream(memStream, aes.CreateEncryptor(),CryptoStreamMode.Write); 17 byte[] data = Encoding.UTF8.GetBytes(dataToEncrypt); 18 crStream.Write(data, 0, data.Length); 19 crStream.FlushFinalBlock(); 20 //Return Base 64 String 21 return Convert.ToBase64String(memStream.ToArray()); 22 } 23 finally 24 { 25 //cleanup 26 if (crStream != null) 27 crStream.Close(); 28 if (memStream != null) 29 memStream.Close(); 30 if (aes != null) 31 aes.Clear(); 32 } 33 } 34

Ahora para desenciptarlo el método recibirá como parámetros el mensaje encriptado la password y salt, como AES es un algoritmo simetrico utilizara la password calculada anteriormente para descencriptar el mensaje .

1 public string Decrypt(string dataToDecrypt, string password, string salt) 2 { 3 AesManaged aes = null; 4 MemoryStream memStream = null; 5 CryptoStream crStream = null; 6 try 7 { 8 Rfc2898DeriveBytes rfc2898 = new Rfc2898DeriveBytes(password, Encoding.UTF8.GetBytes(salt)); 9 aes = new AesManaged(); 10 aes.Key = rfc2898.GetBytes(aes.KeySize / 8); 11 aes.IV = rfc2898.GetBytes(aes.BlockSize / 8); 12 memStream = new MemoryStream(); 13 crStream = new CryptoStream(memStream, aes.CreateDecryptor(), 14 CryptoStreamMode.Write); 15 byte[] data = Convert.FromBase64String(dataToDecrypt); 16 crStream.Write(data, 0, data.Length); 17 crStream.FlushFinalBlock(); 18 byte[] decryptBytes = memStream.ToArray(); 19 return Encoding.UTF8.GetString(decryptBytes, 0, decryptBytes.Length); 20 } 21 finally 22 { 23 if (crStream != null) 24 crStream.Close(); 25 if (memStream != null) 26 memStream.Close(); 27 if (aes != null) 28 aes.Clear(); 29 } 30 } 31

Ya solo nos queda llamar a los métodos y mostrar los mensajes encriptados y desencriptados en los textbox.

1 private void button1_Click(object sender, RoutedEventArgs e) 2 { 3 txtEncryptedData.Text = Encrypt(txtDataToEncrypt.Text, txtPassword.Text, txtSalt.Text); 4 txtDecryptedData.Text = Decrypt(txtEncryptedData.Text, txtPassword.Text,txtSalt.Text); 5 } 6

Ejecutando la aplicación obtendríamos

image_thumb14

Como habéis podido ver es muy sencillo proteger nuestros datos encriptandolos, lo debemos de recordar cada vez que tratemos datos sensibles para el usuario.

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *