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
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" 8 9Export-PfxCertificate -Cert $cert -FilePath ".\AppConfig.pfx" -Password $mypwd 10 11$cert
This will give you a file called
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
1<configProtectedData> 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>
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 "system.net/mailSettings/smtp" ` 3 "C:\projects\MyProject" ` 4 -prov Pkcs12Provider
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.
mmc(Start -> Run -> mmc)
- Add Certificates, for “Computer account”, “Local computer”
- Locate the certificate (AppConfig) under Personal/Certificates
- Right-click, All Tasks, Manage Private Keys
- Add access for “Everyone”