Brendan McKenzie

Encrypting web.config values

Tuesday, 21 July 2020

This is a quick guide on how to encrypt values in a web.config file and how to make it work with Azure App Services.

Start by creating a self-signed certificate, take note of the thumbprint that is output at the end. This will be used when configuring the App Service. You will need to specify a password (replacing <<certificate password>>).

1$mypwd = ConvertTo-SecureString -String "<<certificate password>>" -Force -AsPlainText
2$cert = New-SelfSignedCertificate `
3  -Type DocumentEncryptionCert `
4  -Subject "CN=AppConfig" `
5  -KeyExportPolicy Exportable `
6  -KeySpec KeyExchange `
7  -NotAfter "2100-01-01"
9Export-PfxCertificate -Cert $cert -FilePath ".\AppConfig.pfx" -Password $mypwd

This will give you a file called AppConfig.pfx.

You will then need to upload the certificate to your App Service.

In the Azure portal, navigate to your App Service then TLS/SSL settings -> Private Key Certificates then click "Upload Certificate". Upload the pfx file using the password you specified during its creation.

You will then need to let the App Service that it needs to load the certificate on startup.

Still in the App Service Azure portal, navigate to Configuration. Click "New application setting" and create one called WEBSITE_LOAD_CERTIFICATES with the value that is the thumbprint from the certificate you created. This is a comma-separated value if you are working with multiple certificates.

You can now encrypt configuration in your web.config file.

Create this class in your project.

Add the following section to your web.config as a child of <configuration />

2    <providers>
3      <add
4        name="Pkcs12Provider"
5        thumbprint="<<thumbprint of your certificate>>"
6        type="MyApp.Core.Security.Pkcs12ProtectedConfigurationProvider, MyApp.Core"
7        storeLocation="LocalMachine"/>
8    </providers>
9  </configProtectedData>

n.b. the type, storeLocation and thumbprint will likely vary for your purposes. When running on Azure App Services storeLocation will need to be "CurrentUser"

Build your project.

Now add the pieces of configuration to your web.config file that you would like encrypted.

Run the command (updating the path to your local development copy of the site):

1. "C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe" `
2  -pef "" `
3  "C:\projects\MyProject" `
4  -prov Pkcs12Provider

n.b. The pef parameter will be the section you want to encrypt, in this example it is encrypting the SMTP settings. The path will need to be updated to point to your project's folder, where the web.config file is located.

If you receive the “Keyset does not exist” error locally, follow these steps.

  1. Open mmc (Start -> Run -> mmc)
  2. Add Certificates, for “Computer account”, “Local computer”
  3. Locate the certificate (AppConfig) under Personal/Certificates
  4. Right-click, All Tasks, Manage Private Keys
  5. Add access for “Everyone”