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.