Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save duncansmart/74329ef89b209878fd65256b0da3c3a5 to your computer and use it in GitHub Desktop.
Save duncansmart/74329ef89b209878fd65256b0da3c3a5 to your computer and use it in GitHub Desktop.
Secure environment variables on windows

Encrypting

To create a DPAPI-encrypted environment variable run the following PowerShell:

[Environment]::SetEnvironmentVariable((Read-Host "Enter name"), (Read-Host "Enter value" -AsSecureString | ConvertFrom-SecureString), 'User')

And follow the prompts:

image

(You may need to restart any apps that wish to use this value now)

Then you can see the value is encrypted:

image showing encrypted value in Powershell and the Command Prompt

image showing encrypted value in Control Panel

Decrypting

The value can be decrypted using the following PowerShell line (replace MY_ENV_VAR with your variable name):

[Net.NetworkCredential]::new('', (ConvertTo-SecureString $env:MY_ENV_VAR)).Password

Therefore to use in node:

let myEnvVar = require('child_process').execSync("powershell -exec bypass [Net.NetworkCredential]::new('', (ConvertTo-SecureString $env:MY_ENV_VAR)).Password").toString('utf-8').trim()

Or in .NET

var password = Process.Start(new ProcessStartInfo("powershell", "-exec bypass [Net.NetworkCredential]::new('', (ConvertTo-SecureString $env:MY_ENV_VAR)).Password") { RedirectStandardOutput = true }).StandardOutput.ReadToEnd().Trim();

Also in .NET you could pull in System.Security.Cryptography.ProtectedData and call System.Security.Cryptography.ProtectedData.Unprotect(), but this is easier to do as a one-liner with no dependencies.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment