Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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

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

[Environment]::SetEnvironmentVariable((Read-Host "Enter name"), (Read-Host "Enter value" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString), [EnvironmentVariableTarget]::User)

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

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