The process of exporting and importing a Password using the -Key
parameter goes like this:
- You need to generate a Key, for that you can use the
RandomNumberGenerator
Class. Note: Valid key lengths are 16, 24 and 32 bytes.
$key = [byte[]]::new(32)
$ran = [System.Security.Cryptography.RandomNumberGenerator]::Create()
$ran.GetBytes($key)
# Export the new key to a file:
Export-Clixml -InputObject $key -Path path\to\myKey.key
- Export your password using this key.
# Import the key (it should be obtained from a Vault preferably)
$key = Import-CliXml path\to\myKey.key
$myPassWord = 'myPassword'
ConvertTo-SecureString $myPassWord -AsPlainText -Force |
ConvertFrom-SecureString -Key $key |
Set-Content path\to\myPassword.txt
- Lastly you can import it whenever you want using the same key.
If you're using PowerShell Core:
# Get the encrypted password
$encryptedPassword = Get-Content path\to\myPassword.txt -Raw
# Import the key (it should be obtained from a Vault preferably)
$key = Import-CliXml path\to\myKey.key
ConvertTo-SecureString $encryptedPassword -Key $key |
ConvertFrom-SecureString -AsPlainText
# -> Outputs: `myPassword`
If you're using Windows PowerShell:
# Get the encrypted password
$encryptedPassword = Get-Content path\to\myPassword.txt -Raw
# Import the key (it should be obtained from a Vault preferably)
$key = Import-CliXml path\to\myKey.key
$secureString = ConvertTo-SecureString $encryptedPassword -Key $key
[System.Net.NetworkCredential]::new('', $secureString).Password
# -> Outputs: `myPassword`