Encrypt String with the Machine Key in Powershell?

Viewed 2697

I want to Encrypt a password in Powershell to save it to a file. The ConvertTo-SecureString uses the current credentials to encrypt and decrypt the string.

I want to encrypt it with the local machine key (probably the SYSTEM account credentials) so every username on the same computer will be able to use the password.

I want the string to be undecryptable on other computers.

1 Answers

It's possible to use the [Security.Cryptography.ProtectedData]::Protect function along with [Security.Cryptography.DataProtectionScope]::LocalMachine as the entity.

Code example:

Function Encrypt-WithMachineKey($s) {
    Add-Type -AssemblyName System.Security

    $bytes = [System.Text.Encoding]::Unicode.GetBytes($s)
    $SecureStr = [Security.Cryptography.ProtectedData]::Protect($bytes, $null, [Security.Cryptography.DataProtectionScope]::LocalMachine)
    $SecureStrBase64 = [System.Convert]::ToBase64String($SecureStr)
    return $SecureStrBase64
}

Function Decrypt-WithMachineKey($s) {
    Add-Type -AssemblyName System.Security

    $SecureStr = [System.Convert]::FromBase64String($s)
    $bytes = [Security.Cryptography.ProtectedData]::Unprotect($SecureStr, $null, [Security.Cryptography.DataProtectionScope]::LocalMachine)
    $Password = [System.Text.Encoding]::Unicode.GetString($bytes)
    return $Password
}
Related