Universal Windows Platform – Cryptograph App

Cryptograph App demonstrates how to Encrypt and Decrypt Text with a CryptographicBuffer.

Step 1

If not already, follow Setup and Start on how to Install and get Started with Visual Studio 2017 or in Windows 10 choose Start, and then from the Start Menu find and select Visual Studio 2017.

vs2017

Step 2

Once Visual Studio Community 2017 has started, from the Menu choose File, then New then Project…

vs2017-file-new-project

Step 3

From New Project choose Visual C# from Installed, Templates then choose Blank App (Universal Windows) and then type in a Name and select a Location and then select Ok to create the Project
vs2017-new-project-window

Step 4

Then in New Universal Windows Project you need to select the Target Version this should be at least the Windows 10 Fall Creators Update (10.0; Build 16299) and the Minimum Version to be the same.

vs2017-target-platform

The Target Version will control what features your application can use in Windows 10 so by picking the most recent version you’ll be able to take advantage of those features. To make sure you always have the most recent version, in Visual Studio 2017 select Tools Extensions and Updates… then and then see if there are any Updates

Step 5

Once done select from the Menu, Project, then Add New Item…

vs2017-project-add-new-item

Step 6

From the Add New Item window select Visual C#, then Code from Installed then select Code File from the list, then type in the Name as Library.cs before selecting Add to add the file to the Project

vs2017-add-new-item-library

Step 7

Once in the Code View for Library.cs the following should be entered:

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Streams;
using Windows.UI.Xaml.Controls;

public class Library
{
    private const string file_extension = ".txt";

    private static readonly byte[] values =
    {
        1, 4, 8, 15, 16, 23, 42, 108, 1, 4, 8, 15, 16, 23, 42, 108,
        1, 4, 8, 15, 16, 23, 42, 108, 1, 4, 8, 15, 16, 23, 42, 108
    };
    private static readonly SymmetricKeyAlgorithmProvider algorithm =
        SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);
    private static readonly CryptographicKey key =
        algorithm.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(values));
    private static readonly IBuffer iv = values.AsBuffer();

    public async void OpenAsync(TextBox display)
    {
        try
        {
            FileOpenPicker picker = new FileOpenPicker
            {
                SuggestedStartLocation = PickerLocationId.DocumentsLibrary
            };
            picker.FileTypeFilter.Add(file_extension);
            StorageFile file = await picker.PickSingleFileAsync();
            display.Text = await FileIO.ReadTextAsync(file);
        }
        catch
        {

        }
    }

    public async void SaveAsync(TextBox display)
    {
        try
        {
            FileSavePicker picker = new FileSavePicker
            {
                SuggestedStartLocation = PickerLocationId.DocumentsLibrary,
                DefaultFileExtension = file_extension,
                SuggestedFileName = "Document"
            };
            picker.FileTypeChoices.Add("Plain Text", new List<string>() { file_extension });
            StorageFile file = await picker.PickSaveFileAsync();
            if (file != null)
            {
                await FileIO.WriteTextAsync(file, display.Text);
            }
        }
        catch
        {

        }
    }

    public void Encrypt(ref TextBox display)
    {
        try
        {
            IBuffer buffer = CryptographicBuffer.ConvertStringToBinary(display.Text,
            BinaryStringEncoding.Utf8);
            IBuffer bufferEncrypt = CryptographicEngine.Encrypt(key, buffer, iv);
            display.Text = CryptographicBuffer.EncodeToBase64String(bufferEncrypt);
        }
        catch
        {

        }
    }

    public void Decrypt(ref TextBox display)
    {
        try
        {
            IBuffer buffer = Convert.FromBase64String(display.Text).AsBuffer();
            IBuffer bufferDecrypt = CryptographicEngine.Decrypt(key, buffer, iv);
            display.Text = CryptographicBuffer.ConvertBinaryToString(
                BinaryStringEncoding.Utf8, bufferDecrypt);
        }
        catch
        {

        }
    }
}

In the Library.cs there are using statements to include the necessary functionality. There are Members that help with encryption including SymmetricKeyAlgorithmProvider, CryptographicKey and a IBuffer. OpenAsync is used to set the TextBox contents to the contents of a file – this is opened with a FileOpenPicker using ReadTextAsync, SaveAsync is used to get the contents of the TextBox and then this is saved to a file, using the FileSavePicker and WriteTextAsync. The Encrypt Method will encode any text so it is encrypted and Decrypt is used to decode any text so it is decrypted.

Step 8

In the Solution Explorer select MainPage.xaml

vs2017-mainpage-library

Step 9

From the Menu choose View and then Designer

vs2017-view-designer

Step 10

The Design View will be displayed along with the XAML View and in this between the Grid and /Grid elements, enter the following XAML:

<TextBox Name="Display" AcceptsReturn="True" TextWrapping="Wrap" VerticalAlignment="Stretch"/>
<CommandBar VerticalAlignment="Bottom">
	<AppBarButton Icon="OpenFile" Label="Open" Click="Open_Click"/>
	<AppBarButton Icon="Save" Label="Save" Click="Save_Click"/>
	<AppBarButton Name="Encrypt" Icon="ProtectedDocument" Label="Encrypt" Click="Encrypt_Click"/>
	<AppBarButton Name="Decrypt" Icon="Document" Label="Decrypt" Click="Decrypt_Click"/>
</CommandBar>

The first block of XAML the main user interface of the Application, this features a TextBox where any text may be entered that can be decrypted or encrypted. The second block of XAML is is the CommandBar which contain Open which will allow a file to be opened and Save will allow a file to be saved. Encrypt is used to perform encryption and Decrypt is used to perform decryption.

Step 11

From the Menu choose View and then Code

vs2017-view-code

Step 12

Once in the Code View, below the end of public MainPage() { … } the following Code should be entered:

Library library = new Library();

private void Open_Click(object sender, RoutedEventArgs e)
{
	library.OpenAsync(Display);
}

private void Save_Click(object sender, RoutedEventArgs e)
{
	library.SaveAsync(Display);
}

private void Encrypt_Click(object sender, RoutedEventArgs e)
{
	library.Encrypt(ref Display);
}

private void Decrypt_Click(object sender, RoutedEventArgs e)
{
	library.Decrypt(ref Display);
}

Below the MainPage() Method an instance of the Library Class is created, Open_Click and Save_Click Methods call the related methods in the Library Class as does Encrypt_Click and Decrypt_Click.

Step 13

That completes the Universal Windows Platform Application so Save the Project then in Visual Studio select the Local Machine to run the Application

vs2017-local-machine

Step 14

After the Application has started running you can enter any text then use Encrypt to encode the text or Decrypt to decode the text in the Application

ran-cryptograph-app

Step 15

To Exit the Application select the Close button in the top right of the Application

vs2017-close

Creative Commons License

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s