7

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.

4
  • What is your use case? Preventing the password being visible in script files? Commented Sep 25, 2017 at 8:44
  • 1
    @LievenKeersmaekers Nope. For that base64 is fine. I want to prevent from other people being able to use the password if they grab the file (through an SMB or NFS share that was open by mistake). Only users that have access to the specific computer should have access to the password. Commented Sep 25, 2017 at 17:30
  • Ok, thanks for the update. not my downvote btw Commented Sep 25, 2017 at 19:33
  • @LievenKeersmaekers That's OK. Thanks :) Commented Sep 26, 2017 at 11:45

1 Answer 1

13

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
}
Sign up to request clarification or add additional context in comments.

4 Comments

This is awesome! One question though: this "machine key", how long does it last? Is it like the AD Machine password that resets every 30 days? Or is it the primary certificate in the machine personal store? Or... something else?
It is created on the installation on windows and does not expire. You can replace if manually I guess, but it's not something that will happen automatically
Awesome, what about if CurrentUser is used instead of LocalMachine?
Okay found this, a bit old but informative: support.microsoft.com/en-us/help/309408/… Also worth noting the risks of using DPAPI: harmj0y.net/blog/redteaming/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.