Storing Secret Data

by Apr 4, 2014

If you wanted to store sensitive data in a way that only you could retrieve it, you can use a funny approach: convert some plain text into a secure string, then convert the secure string back, and save it to disk:

$storage = "$env:temp\secretdata.txt"
$mysecret = 'Hello, I am safe.'

$mysecret | 
  ConvertTo-SecureString -AsPlainText -Force |
  ConvertFrom-SecureString |
  Out-File -FilePath $storage

When you look at the file, it will look like this:

Your secret was automatically encrypted by the built-in Windows data protection API (DPAPI), using your identity and your machine as encryption key. So only you (or any process that runs on your behalf) can decipher the secret again, and only on the machine where it was encrypted.

To get back the secret, try this:

$storage = "$env:temp\secretdata.txt"
$secureString = Get-Content -Path $storage | 
  ConvertTo-SecureString
  
$ptr = [System.Runtime.InteropServices.Marshal]::SecureStringToGlobalAllocUnicode($secureString)
$mysecret = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($ptr) 

$mysecret 

It works–you get back the exact same text that you encrypted before.

Now, try the same as someone else. You will see that any other user cannot decrypt the secret file. And you won't be able to, either, when you try it from a different machine.

Twitter This Tip! ReTweet this Tip!