Encrypt And Decrypt String In Windows Runtime Apps

Here are the steps, 

Step 1: Create a simple Windows Project. New Project, Visual C#, Windows 8, Windows, then click Blank App (Windows 8.1).
blank

Step 2:

Lets add the following elements in MainPage.xaml :
  • Input Field to enter the plain string
  • Input field to enter the key to encrypt
  • Two buttons Encrypt string and Decrypt string with click events
  • Two Textblocks to display the encrypted and decrypted string.

Complete MainPage.xaml code snippet is:

  1. <Page  
  2.     x:Class="EncryptDecryptString.MainPage"  
  3.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  4.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
  5.     xmlns:local="using:EncryptDecryptString"  
  6.     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  
  7.     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
  8.     mc:Ignorable="d">  
  9.   
  10.     <Grid Background="#FF449FF5">  
  11.         <TextBox x:Name="txtPlainString" HorizontalAlignment="Left" TextWrapping="Wrap" PlaceholderText="Enter plain string to encrypt" VerticalAlignment="Top" Margin="92,60,0,0" Width="540" Height="48" FontSize="25"/>  
  12.         <TextBox x:Name="txtKey" HorizontalAlignment="Left" TextWrapping="Wrap" PlaceholderText="Enter Encryption/Decryption Key" VerticalAlignment="Top" Margin="648,60,0,0" Width="434" FontSize="25" Height="48"/>  
  13.         <Button x:Name="btnEncrypt" Content="Encrypt plain string" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="89,123,0,0" Height="60" Width="546" Click="btnEncrypt_Click"/>  
  14.         <TextBlock HorizontalAlignment="Left" TextWrapping="Wrap" Text="Encrypted String : " VerticalAlignment="Top" FontSize="25" Margin="92,229,0,0" Foreground="Black"/>  
  15.         <TextBlock x:Name="txtEncryptedString" HorizontalAlignment="Left" TextWrapping="Wrap" VerticalAlignment="Top" Margin="92,289,0,0" Height="40" FontSize="30" Width="899"/>  
  16.         <Button x:Name="btnDecrypt" Content="Decrypt encrypted string" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="89,398,0,0" Height="60" Width="546" Click="btnDecrypt_Click"/>  
  17.         <TextBlock HorizontalAlignment="Left" TextWrapping="Wrap" Text="Decrypted String : " VerticalAlignment="Top" Margin="92,486,0,0" FontSize="25" Height="34" Width="238" Foreground="Black"/>  
  18.         <TextBlock x:Name="txtdecryptedString" HorizontalAlignment="Left" TextWrapping="Wrap" VerticalAlignment="Top" Margin="92,547,0,0" FontSize="30" Height="40" Width="899"/>  
  19.     </Grid>  
  20. </Page>  
output

Step 3:

In the code behind: MainPage.xaml.cs.

Update your code with this:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.IO;  
  4. using System.Linq;  
  5. using System.Runtime.InteropServices.WindowsRuntime;  
  6. using System.Threading.Tasks;  
  7. using Windows.Foundation;  
  8. using Windows.Foundation.Collections;  
  9. using Windows.Security.Cryptography;  
  10. using Windows.Security.Cryptography.Core;  
  11. using Windows.Storage.Streams;  
  12. using Windows.UI.Xaml;  
  13. using Windows.UI.Xaml.Controls;  
  14. using Windows.UI.Xaml.Controls.Primitives;  
  15. using Windows.UI.Xaml.Data;  
  16. using Windows.UI.Xaml.Input;  
  17. using Windows.UI.Xaml.Media;  
  18. using Windows.UI.Xaml.Navigation;  
  19.   
  20. // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238  
  21.   
  22. namespace EncryptDecryptString  
  23. {  
  24.     /// <summary>  
  25.     /// An empty page that can be used on its own or navigated to within a Frame.  
  26.     /// </summary>  
  27.     public sealed partial class MainPage : Page  
  28.     {  
  29.         public MainPage()  
  30.         {  
  31.             this.InitializeComponent();  
  32.         }  
  33.   
  34.         private async void btnEncrypt_Click(object sender, RoutedEventArgs e)  
  35.         {  
  36.             string plainString = txtPlainString.Text;  
  37.             string key = txtKey.Text;  
  38.   
  39.             string encryptedString = await EncryptStringHelper(plainString, key);  
  40.   
  41.             txtEncryptedString.Text = encryptedString;  
  42.         }  
  43.   
  44.         private async void btnDecrypt_Click(object sender, RoutedEventArgs e)  
  45.         {  
  46.             string encryptedString = txtEncryptedString.Text;  
  47.             string key = txtKey.Text;  
  48.   
  49.             string decryptedString = await DecryptStringHelper(encryptedString, key);  
  50.   
  51.             txtdecryptedString.Text = decryptedString;  
  52.   
  53.         }  
  54.   
  55.         private async Task<string> EncryptStringHelper(string plainString, string key)  
  56.         {  
  57.             try  
  58.             {  
  59.                 var hashKey = GetMD5Hash(key);  
  60.                 var decryptBuffer = CryptographicBuffer.ConvertStringToBinary(plainString, BinaryStringEncoding.Utf8);  
  61.                 var AES = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);  
  62.                 var symmetricKey = AES.CreateSymmetricKey(hashKey);  
  63.                 var encryptedBuffer = CryptographicEngine.Encrypt(symmetricKey, decryptBuffer, null);  
  64.                 var encryptedString = CryptographicBuffer.EncodeToBase64String(encryptedBuffer);  
  65.                 return encryptedString;  
  66.             }  
  67.             catch (Exception ex)  
  68.             {  
  69.                 return "";  
  70.             }  
  71.         }  
  72.         private async Task<string> DecryptStringHelper(string encryptedString, string key)  
  73.         {  
  74.             try  
  75.             {  
  76.                 var hashKey = GetMD5Hash(key);  
  77.                 IBuffer decryptBuffer = CryptographicBuffer.DecodeFromBase64String(encryptedString);  
  78.                 var AES = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);  
  79.                 var symmetricKey = AES.CreateSymmetricKey(hashKey);  
  80.                 var decryptedBuffer = CryptographicEngine.Decrypt(symmetricKey, decryptBuffer, null);  
  81.                 string decryptedString = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, decryptedBuffer);  
  82.                 return decryptedString;  
  83.             }  
  84.             catch (Exception ex)  
  85.             {  
  86.                 return "";  
  87.             }  
  88.         }  
  89.         private static IBuffer GetMD5Hash(string key)  
  90.         {  
  91.             IBuffer bufferUTF8Msg = CryptographicBuffer.ConvertStringToBinary(key, BinaryStringEncoding.Utf8);  
  92.             HashAlgorithmProvider hashAlgorithmProvider = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);  
  93.             IBuffer hashBuffer = hashAlgorithmProvider.HashData(bufferUTF8Msg);  
  94.             if (hashBuffer.Length != hashAlgorithmProvider.HashLength)  
  95.             {  
  96.                 throw new Exception("There was an error creating the hash");  
  97.             }  
  98.             return hashBuffer;  
  99.         }  
  100.     }  
  101. }  
Step 4:

Now you are all set. Run the application and enter plain string and key. Click on the Encrypt string button. You will see the encrypted string.

output

That’s it.

Thanks, Happy Coding!
 
Read more articles on Windows Runtime apps:

Up Next
    Ebook Download
    View all
    Learn
    View all