How to use Azure key vault with PowerShell to encrypt data

Introduction

In this blog post, I will be talking about how to use Azure Key Vault with PowerShell to perform cryptographic operations, like encrypting and decrypting data.

We will start by creating the key vault in Azure, install an encryption key and register an application with its service principal. After that, we will give rights to that application on the key vault. Finally, we will use PowerShell to authentication to Azure AD, get an access token, use this token to access our key vault, and encrypt/decrypt a simple string.

What we will cover in this blog post:

Create a resource group in Azure.

Create an Azure Key Vault and configure it with access policies.

Create an encryption key in Azure key vault.

Create an application and register it with service principal in Azure AD.

Assign permission to the application on the key vault.

Use PowerShell to connect to Azure AD and get a token to access the key vault.

Construct a string [Hello World]

Use PowerShell to connect to the key vault using the access token to the key vault.

Encrypt the [Hello World] string using the key vault key.

Decrypt the encrypted payload again.

Before going through Azure key vault with PowerShell operations, it is better to introduce couple of concepts listed below:

Creating an Application Context

In order to move forward with this blog post, I want to start by introducing the concept of registering an app in Azure.

The Azure Key vault is protecting by RBAC model [Role-based access control], to protect the vault and its secrets/keys from unauthorized access and operations. Instead of using your actual user to access the vault using your code or script, it is highly recommended to created a security identity that can act by its own, to perform the actual cryptographic operations.

Why this is important? Perhaps you want your code to run in the context of an application, or an automation task. You do not want to use your identity to that. It is easy to audit access to the vault if you have a well-known security context that is bound to that application. Think of this like when you create a service account to run a workload.

To do that in Azure, you have to create an application, and give it a name and a secret. It is like normal user accounts in AD where you have the user UPN and password. Your user can authenticate using a password or digital certificate, and so the application that you will create in Azure. It can authentication using a secrete (password) or a digital certificate.

Creating an application and with its ID and secret is not enough. We need to create a Service Principal for that application, so that Azure AD can authentication your application and know about it. Since this is all about Azure key vault with PowerShell , we will create the application from PowerShell.

Separation of concern

Azure Key Vault creates a very solid separation of concerns.

Admin will create a vault, and configure it with access policies.

Application owner will create an application in Azure AD and assign it a service principal.

Admin will assign permission to that service principal on the key vault.

Developer will use the application name and secret in his code to access the vault secret.

An auditor can then see what is happening inside the vault.

The use of Byte Array instead of string

We will go through how to do cryptographic operations inside Azure key vault with PowerShell, but first we need to talk about Byte Arrays first. In this example, we will use PowerShell to encrypt a simple string [“Hello World“] using the key vault. Instead of just passing the string to the key vault, we will convert the string to a Byte Array.

A string contains character data that is subject to interpretation and it implies encoding, while the byte array is just a binary data, which makes it easier to deal with

In our example, we will convert the string variable that holds [“Hello World”] to a byte array, send it to the key vault for encryption.

Later on, we will decrypt the data back to byte array, and then convert that to a string again.

Azure key vault with PowerShell

Now, we can start working on Azure key vault with PowerShell.The first thing to do is to go and install AzureRMPowerShell module on your machine, import the AzureRM module on your PS session, and logon to your Azure Account.

Step 1: Create the Key Vault

We will start by creating an Azure Resource Group, and then we will create our Azure Key Vault:

Key Vault Name : IgniteKV

Resource Group Name : IgniteRG

For demo purposes, we will configure the key vault with all “Advance Access Policies“, so it can be used for disk encryption, used by Azure resource manager through templates, and used for deployments.

Here is how the Azure Key Vault looks like from the Azure portal with all advanced access policies checked:

Now, we will create an application, which will give us a security context to access the key vault. To create the application, we will provide an application name and a secret. Although the secret can be a digital certificate, but for now we will use a simple string.

After creating the app, we will create a service principal for the app, so that i can authenticate with Azure AD in order to request a token. Later on, we will use that token to access the key vault.

Moreover, we will grant permission to the app, so that it can access the key vault and perform cryptographic operations.

PowerShell

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

# app name and secret

# the secret can be a digital certificate and not just a normal password. for demo purposes, we will go with simple password

$appDisplayName='IgniteApp'

$aadClientSecret='IgniteClientSecret'

# -------------------------------------

# Create App

# -------------------------------------

# create an app to descripe the entity that wants to consume Azure Key Vault, so that it will have service identity

# the HomePage and IdentifierUris switches can be filled with anything and should not resolve to DNS name.

Step 4: Encrypt a simple string from PowerShell

In this section, we will construct a string [“Hello World“], we will convert it to Byte Array, and will connect to the Azure Key Vault specifying:

Key vault name.

KeyID and version. If version is left blank, the most recent version of the key will be used.

The byte array to be encrypted.

Access token obtained.

PowerShell

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

# -------------------------------------

# let us encrypt some content using our key

# -------------------------------------

# this function will take some information about our keyID, key name and version, and vault name

# and we will inject the access token in the authorization header as bearer token

# and in the body we will add some information like:

# encryption algorithm = RSA

# the data we want to encrypt, in this case, we want to encrypt a byte array.

functionEncrypt-ByteArray

(

[string]$accessToken,

[string]$vaultName,

[string]$keyID,

[string]$keyVersion,

[byte[]]$plainArray

)

{

# converting the byte array to Base64 string

# Note from [Chris Clayton (AzureCAT)].

# "When performing the post methods there is a common theme of converting to Base64 strings which just makes sense so we do not introduce any invalid characters etc. and creating a JSON body as you can see here"

$base64Array=[Convert]::ToBase64String($plainArray)

# constructing the url for the vault encrypt operation by specifying the KeyID and Key version. If key version is not specified, then the most recent key version will be used

Step 5: Decrypt the cipher from PowerShell

Finally, we will take the encrypted data we get from the vault, and then we will try to ask the vault to decrypt it. We will get byte array as a response. We will then convert the byte array back to string, and we will get out [“Hello World“] back!

PowerShell

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

# -------------------------------------

# let us decrypt $EncryptedData

# -------------------------------------

# to do that, we will supply the same information but this time we will put the encrypted data in the body

It turns out that for some reason the process of encrypting and decrypting removes the ‘=’ characters that represent padding on a base 64 string to the length that is divisible by 4 (all base 64 encoded strings must have a length that is divisible by 4 to be valid). So as a workaround I figure out the number of missing characters and pad it myself with the ‘=’ character. After several tests this technique seems to hold up.

# now we will convert the byte array to a string again. Result will be [Hello World].

$mydataAsString=[System.Text.Encoding]::UTF8.GetString($bytes)

Final Thoughts

We saw how Azure Key Vault with PowerShell really works. We started by creating a resource group and a key vault in Azure. We then created a key inside the key vault for cryptographic operations. From the scripting side, we needed to create a service account to run the script [ this is called creating an application in Azure]. In order for Azure AD to recognize that application, we needed to register that application with a Service Principal.

After that, we discovered the authentication endpoint for the Azure Key vault. This was the Azure AD end point. Then we tried to contact Azure AD, supply the application ID and secret to get a token on the vault. The vault was configured previously to recognize that application and give it some rights on its key. Our PowerShell script will then construct a small string, sent it to the key vault for encryption, and then decrypting it back.

Credit

Big credit goes to Chris Clayton (AzureCAT) and his great blog post. Most the PowerShell code in this blog post [Azure key vault with PowerShell ]related to getting AAD token and doing the actual calls to Azure AD key vault is originally taken from his blog post, with some modifications and explanation.

I also added couple of sections in this blog post to help readers create the actual vault, resource group, application, service principal, and add couple of screenshots.

You have Successfully Subscribed!

About The Author

Ammar is a digital transformer, cloud architect, public speaker and blogger.
He is considered a trusted advisory with the ability to quickly navigate complex multi-cultural organizations and continuously improve and motivate cross-functional teams to achieve higher productivity, collaboration, revenue gain and cross-group knowledge sharing.
His contributions to the tech community helped him get awarded the Microsoft Most Valuable Professional.
Ammar appears in a lot of global conferences, and he has many publications about digital transformation and next generation technologies.