Search code examples
powershellsecurestringsysprep

Secure String can't be decrypted after Sysprep


I have two PowerShell scripts I'm building for a Windows 7 image. Prior to the image I run PRE-IMAGE.ps1, and it has a line like this in it:

$JoinDomainPassword = Read-Host -Prompt "Please enter the password for $joinDomainUser" -AsSecureString
$strPass = $joinDomainPassword | ConvertFrom-SecureString

I then save the the $strPass secure string to the registry, and run sysprep.

After a reboot with sysprep, the POST-IMAGE.ps1 then pulls $strPass from the registry, and has a line like this:

$strPass = $strPass | ConvertTo-SecureString
$credentials = New-Object System.Management.Automation.PSCredential ($JoinDomainUser, $strPass)

However, these lines in POST-IMAGE.ps1 get the "Key not valid" error you'll see when you run convertto-securestring and convertfrom-securestring as different Windows users. (similiar to this question) - but the catch here is I -AM- using the same user to convert to and from secure strings. I'm guessing this has something to do with sysprep - but I can't wrap my head around it.

I apologize if this has been asked about before, I've found a few questions that touch on parts of this, but don't describe my EXACT problem.


Solution

  • If you do not specify a key for the ConvertFrom-SecureString command, it will use DPAPI to encrypt the string. Sysprep apparently re-initializes the key used by DPAPI. From http://www.mombu.com/microsoft/security-crypto/t-local-machine-masterkey-in-dpapi-1053937-print.html

    DPAPI will generate the local system master key during the specialization phase of sysprep.