Creating an application to encrypt and decrypt files

The Azure Key Vault client library for .NET allows you to manage keys and related assets such as certificates and secrets. The code samples next will show you how to retrieve the secret from Azure Key Vault. It then uses this secret to encrypt a file on the local system. This file will be uploaded to Azure Blob Storage, and then downloaded and decrypted as well:

  1. Open Visual Studio and add a new project.
  2. In the new project wizard, select Console App (.NET  Framework) and click Next:

Creating a new console app
  1. Add the following values and create a new project. Click Next:

App values
  1. Click Create.
  2. The console application is now created. Open the NuGet Package Manager console and add the following packages: 
Install-Package Microsoft.Azure.ConfigurationManager 
Install-Package Microsoft.Azure.Storage.Common
Install-Package Microsoft.Azure.Storage.Blob
Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory
Install-Package Microsoft.Azure.KeyVault
Install-Package Microsoft.Azure.KeyVault.Extensions
  1. Add the following values to App.config:
 <appSettings>
<add key="accountName" value="<replace-this-with-the-storage-account-name>"/>
<add key="accountKey" value="<replace-this-with-the-key>"/>
<add key="clientId" value="<replace-this-with-the-application-id"/>
<add key="clientSecret" value="<replace-this-with-the-application-secret"/>
<add key="container" value="packtcontainer"/>
</appSettings>
  1. Replace the accountName value with the name of the Storage Account. Replace the accountKey with the key that you retrieved in the last step of the first section of this demo. Replace the clientID with the application ID that was registered in Azure AD and the clientSecret with the secret. 
  2. Open Program.cs and add the following using directives, and make sure to add a reference to System.Configuration to the project:
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System.Configuration;
using Microsoft.Azure;
using Microsoft.Azure.Storage;
using Microsoft.Azure.Storage.Auth;
using Microsoft.Azure.Storage.Blob;
using Microsoft.Azure.KeyVault;
using System.Threading;
using System.IO;
  1. Add a method to the Program.cs class to get a token to your console application. The following method is used by Key Vault classes that need to authenticate for access to your key vault:
private async static Task<string> GetToken(string authority, string resource, string scope)
{
var authContext = new AuthenticationContext(authority);
ClientCredential clientCred = new ClientCredential(
CloudConfigurationManager.GetSetting("clientId"),
CloudConfigurationManager.GetSetting("clientSecret"));
AuthenticationResult result = await authContext.AcquireTokenAsync(resource, clientCred);

if (result == null)
throw new InvalidOperationException("Failed to obtain the JWT token");

return result.AccessToken;
}

  1. In the Main() method, add the following code to interact with the blob container. If this container doesn't exist, it will get created. Then, use the KeyVaultKeyResolver to retrieve the token:
 // This is standard code to interact with Blob storage.
StorageCredentials creds = new StorageCredentials(
CloudConfigurationManager.GetSetting("accountName"),
CloudConfigurationManager.GetSetting("accountKey")
);
CloudStorageAccount account = new CloudStorageAccount(creds, useHttps: true);
CloudBlobClient client = account.CreateCloudBlobClient();
CloudBlobContainer contain = client.GetContainerReference(CloudConfigurationManager.GetSetting("container"));
contain.CreateIfNotExists();

// The Resolver object is used to interact with Key Vault for Azure Storage.
// This is where the GetToken method from above is used.
KeyVaultKeyResolver cloudResolver = new KeyVaultKeyResolver(GetToken);
  1. Now, create a Temp folder on your C drive and create a file with some text in it. Call this file PacktFile.txt.
  2. Then below the previous code, add the following. This will retrieve the secret that we create in PowerShell in the previous section. Then, it will use this key to encrypt the file:
  // Retrieve the secret that you created previously.
SymmetricKey sec = (SymmetricKey)cloudResolver.ResolveKeyAsync(
"https://packtdataencryptionvault.vault.azure.net/secrets/Secret2/",
CancellationToken.None).GetAwaiter().GetResult();

// Now you simply use the SimmetricKey to encrypt by setting it in the BlobEncryptionPolicy.
BlobEncryptionPolicy policy = new BlobEncryptionPolicy(sec, null);
BlobRequestOptions options = new BlobRequestOptions() { EncryptionPolicy = policy };

// Reference a block blob.
CloudBlockBlob blob = contain.GetBlockBlobReference("PacktFile.txt");

//Upload using the UploadFromStream method.
using (var stream = System.IO.File.OpenRead(@"C:TempPacktFile.txt"))
blob.UploadFromStream(stream, stream.Length, null, options, null);
  1. Last, we can decrypt the file, as well, by passing the resolver. Therefore, below the previous code, add the following:
  BlobEncryptionPolicy policy1 = new BlobEncryptionPolicy(null, cloudResolver);
BlobRequestOptions options1 = new BlobRequestOptions() { EncryptionPolicy = policy1 };

using (var np = File.Open(@"C:TempMyFileDecrypted.txt", FileMode.Create))
blob.DownloadToStream(np, null, options1, null);

We have now encrypted a text file and uploaded it to Azure Blob Storage, using a secret that is stored in Azure Key Vault. We then downloaded and decrypted the file to our local system. 

We have now concluded this demo. In the next section, we are going to cover how to encrypt and decrypt data in transit.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.47.218