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
复制代码 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.
http://powershell.com/cs/blogs/tips/archive/2014/04/04/storing-secret-data.aspx |