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
$mypwd = ConvertTo-SecureString -String "<<certificate password>>" -Force -AsPlainText $cert = New-SelfSignedCertificate ` -Type DocumentEncryptionCert ` -Subject "CN=AppConfig" ` -KeyExportPolicy Exportable ` -KeySpec KeyExchange ` -NotAfter "2100-01-01" Export-PfxCertificate -Cert $cert -FilePath ".\AppConfig.pfx" -Password $mypwd $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
<configProtectedData> <providers> <add name="Pkcs12Provider" thumbprint="<<thumbprint of your certificate>>" type="MyApp.Core.Security.Pkcs12ProtectedConfigurationProvider, MyApp.Core" storeLocation="LocalMachine"/> </providers> </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):
. "C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe" ` -pef "system.net/mailSettings/smtp" ` "C:\projects\MyProject" ` -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”