title: ProtectedData.Unprotect Method Fails to Decrypt
body: <p>We have a build process that needs to decrypt a password which it then uses to connect to a database.  We are using the Data Protection API (DPAPI) to encrypt the password at the machine scope on the build server (I'm logged in with my own domain account) using PowerShell:</p>
  
  <pre><code>[Security.Cryptography.ProtectedData]::Protect( $passwordBytes, $null, [Security.Cryptography.DataProtectionScope]::LocalMachine );
  </code></pre>
  
  <p>The decryption is also done in a PowerShell script, which is executed by CruiseControl.NET, running as our build user:</p>
  
  <pre><code> [Security.Cryptography.ProtectedData]::Unprotect( $encryptedbytes, $null, [Security.Cryptography.DataProtectionScope]::LocalMachine );
  </code></pre>
  
  <p>The call to <code>Unprotect</code>, however, fails with the following message:  "Key not valid for use in specified state.".  <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.protecteddata.protect.aspx" rel="nofollow">According to the docs</a>, this error can occur using impersonation, and the impersonating code should load the user's profile.</p>
  
  <p>For security purposes, the build user is denied the Log on through Terminal Services right.  To test the problem, I logged into the build server as myself, then used runas to open a PowerShell prompt as the build user:</p>
  
  <pre><code>runas /profile /user:DOMAIN\BUILDUSER powershell.exe
  </code></pre>
  
  <p>I then run the PowerShell script to unprotect/decrypt the password, and get the same error.</p>
  
  <p>I used <a href="http://technet.microsoft.com/en-us/sysinternals/bb896645" rel="nofollow">Process Monitor</a> to watch for any failures or access denied events, and there weren't any.</p>
  
  <p>I'm able to decrypt the password when I log in with my own domain account.</p>
  
  <p>What's going on?  Is my build user's profile not being loaded?  Is there some security setting somewhere I don't know about to enable this?  Why can't I decrypt the password?</p>