茫茫網海中的冷日
         
茫茫網海中的冷日
發生過的事,不可能遺忘,只是想不起來而已!
 恭喜您是本站第 1670906 位訪客!  登入  | 註冊
主選單

Google 自訂搜尋

Goole 廣告

隨機相片
IMG_60D_00352.jpg

授權條款

使用者登入
使用者名稱:

密碼:


忘了密碼?

現在就註冊!

微軟帝國 : [分享]PowerShell ConvertTo-SecureString

發表者 討論內容
冷日
(冷日)
Webmaster
  • 註冊日: 2008/2/19
  • 來自:
  • 發表數: 15771
[分享]PowerShell ConvertTo-SecureString

ConvertTo-SecureString

Convert an encrypted standard string into a secure string, can also convert plain text into a secure string.


Syntax
ConvertTo-SecureString [-String] String
[[-secureKey] SecureString]
[CommonParameters]
ConvertTo-SecureString [-String] String
[-key Byte[]]
[CommonParameters]
ConvertTo-SecureString [-String] String
[[-asPlainText] [-force]]
[CommonParameters]
key
-String SecureString
The string to convert to a secure string
-secureKey SecureString
The encryption key as a secure string,
this is converted to a byte array before being used as the key.
Valid key lengths are 16, 24, and 32 bytes
-key Byte
The encryption key as a byte array.
Valid key lengths are 16, 24, and 32 bytes
-asPlainText
A plain text string to convert to a secure string.
The text is not encrypted so the input is not protected/confidential
To use this option, you must also specify -Force
-force
Set this to confirm that you understand the security risks of using PlainText
CommonParameters:
-Verbose, -Debug, -ErrorAction, -ErrorVariable, -WarningAction, -WarningVariable,
-OutBuffer -OutVariable.

If the standard string being converted was encrypted with ConvertFrom-SecureString using a specified key, that same key must be provided as the value of the Key or SecureKey parameter of the ConvertTo-SecureString cmdlet.

To store the data in a file for later use, the secure string can be converted back to an encrypted, standard string using ConvertFrom-SecureString

Examples

Create a secure string from plain text:

PS C:\> $my_secure_password = convertto-securestring "P@ssW0rD!" -asplaintext -force

Create a secure string using the Read-Host cmdlet:

PS C:\> $my_secure_password = read-host -assecurestring

Save an encrypted string to disc:


PS C:\> $my_encrypted_string = convertfrom-securestring $my_secure_password -key (1..16)
PS C:\> $my_encrypted_string > password.txt

Read an encrypted string from disc and convert back to a secure string:

PS C:\> $my_secure_password = convertto-securestring (get-content password.txt) -key (1..16)

“The great strength of the totalitarian state is that it forces those who fear it to imitate it” - Adolf Hitler


原文出處:ConvertTo-SecureString | PowerShell | SS64.com
冷日
(冷日)
Webmaster
  • 註冊日: 2008/2/19
  • 來自:
  • 發表數: 15771
[轉貼]Working with Passwords, Secure Strings and Credentials in Windows PowerShell
Working with Passwords, Secure Strings and Credentials in Windows PowerShell

Introduction
Passwords in PowerShell can be stored in a number of different forms:
String - Plain text strings. Used to store any text and of course these can store passwords too. Strings are unsecure, they are stored in memory as plain text and most cmdlets will not accept passwords in this form.
System.Security.SecureString - This type is like the usual string, but its content are encrypted in memory. It uses reversible encrypting so the password can be decrypted when needed, but only by the principal that encrypted it.
System.Management.Automation.PSCredential - PSCredential is class that is composed of username (string) and password (SecureString). This is type that most cmdlets require for specifying credentials.

Converting from one type to another is not always an obvious task. The suggested methods are as follows;

Create SecureString
Type the password in an interactive prompt
$SecurePassword = Read-Host -Prompt "Enter password" -AsSecureString

Convert from existing plaintext variable
$PlainPassword = "P@ssw0rd"
$SecurePassword = $PlainPassword | ConvertTo-SecureString -AsPlainText -Force

Create PSCredentials
Assuming that you have password in SecureString form in $SecurePassword variable:
$UserName = "Domain\User"
$Credentials = New-Object System.Management.Automation.PSCredential `
     -ArgumentList $UserName, $SecurePassword

Extract password from PSCredentials
The password can be easily obtained from PSCredential object using GetNetworkCredential method:
$PlainPassword = $Credentials.GetNetworkCredential().Password

Extract password from SecureString
If you have just simple SecureString with the password, you can construct a PSCredentials object and extract password by using the previous method. Another method is this:
$BSTR = `
    [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecurePassword)
$PlainPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

Saving encrypted password to file or registry
If you need to store password for script that runs in unattended mode by scheduler or using some other ways, it possible to save it to file system or registry in encrypted form. It is like the string representation of SecureString. Only user that created this line can decrypt and use it, so when saving this value, use the same account that the script or service will use.
Converting SecureString variable to secure plain text representation
$SecureStringAsPlainText = $SecurePassword | ConvertFrom-SecureString

$SecureStringAsPlainText looks like this "ea32f9d30de3d3dc7fcd86a6a8f587ed9" (actually longer) and can be easily stored in file, registry property or any other storage. When script will need to obtain secure string object it can be done this way:
$SecureString = $SecureStringAsPlainText  | ConvertTo-SecureString

Best Practices
Where possible do not ask for passwords and try to use integrated Windows authentication.
When it is not possible or when specifying different credentials is useful, cmdlets should accept passwords only in the form of PSCredentials or (if username is not needed) as SecureString, but not plain text.
If you need to ask user for credential, use Get-Credential cmdlet. It uses a standard Windows function to receive password in consistent and secure manner without storing it in memory as clear text.
Credentials should be passed to external system also in most secure way possible, ideally as PSCredentials too.
Password should not be saved to disk, registry or other not protected storage as plain text. Use plaintext representation of SecureString when possible.

TechNet Gallery
https://gallery.technet.microsoft.com/Execute-PowerShell-Script-38881dce

原文出處:Working with Passwords, Secure Strings and Credentials in Windows PowerShell - TechNet Articles - United States (English) - TechNet Wiki
冷日
(冷日)
Webmaster
  • 註冊日: 2008/2/19
  • 來自:
  • 發表數: 15771
[轉貼]Decode System.Security.SecureString to readable password
PowerShell - Decode System.Security.SecureString to readable password

I want to decode the password from a System.Security.SecureString to a readable password.
$password = convertto-securestring "TestPassword" -asplaintext -force
$credentials = New-Object System.Net.NetworkCredential("TestUsername", $password, "TestDomain")

This code part works fine, I can use the $credentials object. But later in my code I need the password in a readable format. Because a methode needs the password in readable string. So I must decode the password back.
How it is possible to decode the password from the $credentials object?

Update
Not working:
$password = convertto-securestring "TestPassword" -asplaintext -force
$credentials = New-Object System.Net.NetworkCredential("TestUsername", $password, "TestDomain")

$Ptr = [System.Runtime.InteropServices.Marshal]::SecureStringToCoTaskMemUnicode($credentials.password)
$result = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($Ptr)
[System.Runtime.InteropServices.Marshal]::ZeroFreeCoTaskMemUnicode($Ptr)
$result


Here you go:
$password = ConvertTo-SecureString 'P@ssw0rd' -AsPlainText -Force

$Ptr = [System.Runtime.InteropServices.Marshal]::SecureStringToCoTaskMemUnicode($password)
$result = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($Ptr)
[System.Runtime.InteropServices.Marshal]::ZeroFreeCoTaskMemUnicode($Ptr)
$result

P@ssw0rd

For a "System.Net.NetworkCredential" object, all you need to do is read the String password.
$password = convertto-securestring "TestPassword" -asplaintext -force
$credentials = New-Object System.Net.NetworkCredential("TestUsername", $password, "TestDomain")
$credentials.Password
TestPassword

$credentials | gm

TypeName: System.Net.NetworkCredential

Name           MemberType Definition
----           ---------- ----------
Equals         Method     bool Equals(System.Object obj)
GetCredential  Method     System.Net.NetworkCredential GetCredential(uri uri, str
GetHashCode    Method     int GetHashCode()
GetType        Method     type GetType()
ToString       Method     string ToString()
Domain         Property   string Domain {get;set;}
Password       Property   string Password {get;set;}
SecurePassword Property   securestring SecurePassword {get;set;}
UserName       Property   string UserName {get;set;}

If you end up with a PSCredential object, from an interactive command like Get-Credential use
$credentials=Get-Credential
$credentials.GetNetworkCredential().UserName
TestUsername
$credentials.GetNetworkCredential().Domain
TestDomain
$credentials.GetNetworkCredential().Password
TestPassword

See http://blogs.technet.com/b/heyscriptingguy/archive/2013/03/26/decrypt-powershell-secure-string-password.aspx for details.

Note: I used PS 4 for this example.

The details are explained http://blogs.msdn.com/b/besidethepoint/archive/2010/09/21/decrypt-secure-strings-in-powershell.aspx
and I have yet another slightly different way of doing it.
$pass=convertto-securestring "P@ssw0rd" -asplaintext -force  | ConvertFrom-SecureString
[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR( (ConvertTo-SecureString $pass) ))

P@ssw0rd
($credentials.GetNetworkCredential()).Password


原文出處:PowerShell - Decode System.Security.SecureString to readable password - Stack Overflow
冷日
(冷日)
Webmaster
  • 註冊日: 2008/2/19
  • 來自:
  • 發表數: 15771
[轉貼]Secure Password with PowerShell: Encrypting Credentials - Part 1

Secure Password with PowerShell: Encrypting Credentials – Part 1

Posted on Posted in PowerShell

Like many systems administrators out there, I’ve often found myself with a task that needs to be automated. Automating is great with PowerShell until you need to pass credentials into a script.

kris_resized

At this point, I have seen many administrators put passwords into the body of their script. For testing purposes, this may be forgiven, but in production scripts, putting your passwords in plain view isn’t just a bad thing…it’s a terrifying thing. It should be a cardinal sin. But you can secure a password with Powershell (or at least reduce password visibility).

First, we should touch base on how to supply a credential without having to save it directly in your script.


Get-Credential and Read-Host

You can create a PSCredential object by using the cmdlet Get-Credential and storing the output into a variable. You can pass that variable directly into cmdlets that support PSCredential objects.


$MyCredential = Get-Credential

secure password powershell

Notice that when you access the variable $MyCredential, you are able to see the username but you are unable to see the password. It only displays, “System.Security.SecureString” on the screen. This is because the password is now stored as a SecureString.

You can then use this new PSCredential object directly with cmdlets that support PSCredential objects. You can also individually reference the username or the password for cmdlets that don’t accept a PSCredential object but will support username and password parameters.

In those cases, you can use $MyCredential.Username and $MyCredential.Username


Alternatively, you can use Read-Host to prompt for input and store the result in a variable. This includes prompting for a SecureString (for a password).


$user = Read-Host "Enter Username"
$pass = Read-Host "Enter Password" -AsSecureString

secure password powershell

Notice that the output is very similar to the output of the Get-Credential variable we used, $MyCredential. It shows the username as, “MyUserName” and the password as, “System.Security.SecureString.”

This is great for manual runs of scripts as it helps to remove the password from the script, but it doesn’t really help with our automation. We’re looking for a solution that will be able to run automatically without having to constantly supply credentials via Get-Credential/Read-Host or by leaving our passwords in plain view for anybody to read.


ConvertTo-SecureString – Encrypting passwords and other strings

ConvertTo-SecureString is used to convert plain text or encrypted standard strings into a SecureString object. The SecureString object can be used with cmdlets that support parameters of type SecureString, as is the case with a PSCredential object. You can use the command directly or pipe results into the command.

Syntax:

ConvertTo-SecureString [-String] SomeString
ConvertTo-SecureString [-String] SomeString [-SecureKey SecureString] ConvertTo-SecureString [-String] SomeString [-Key Byte[]] ConvertTo-SecureString [-String] SomeString [-AsPlainText] [-Force]

String String
The string to convert to a SecureString

SecureKey SecureString
Encryption key as a SecureString.

Key Byte[]
Encryption key as a byte array.

AsPlainText
Tells command to treat string as plain text. The string is not encrypted when using this command. Because of the lack of security, the -Force parameter is also required.

Force
Confirms you understand the lack of security when using -AsPlainText

 

When you are not using the –Key or –SecureKey parameters, PowerShell uses the Windows Data Protection API (
DPAPI) to encrypt/decrypt your strings. This effectively means that only the same user account on the same computer will be able to use this encrypted string. That is something to keep in mind as you attempt to automate any scripts. If you’re using a service account, you’ll need to use the –Key or -SecureKey parameters.

Let’s say, for example, you want to take the text, “P@ssword1” and convert it to a SecureString. Since this is a plain text string, we’re going to use the –AsPlainText and –Force parameters.


"P@ssword1" | ConvertTo-SecureString -AsPlainText -Force

secure powershell password

The result is a SecureString object. Unfortunately, you cannot directly save a SecureString object to a file for later use. You have to convert this SecureString object to an encrypted standard string. You can do this with ConvertFrom-SecureString.

ConvertFrom-SecureString – Saving encrypted standard strings

ConvertFrom-SecureString is used to convert secure strings into encrypted standard strings. You can use the command directly or pipe results into the command.

Syntax:


ConvertFrom-SecureString [-SecureString] SecureString
ConvertFrom-SecureString [-SecureString] SecureString [-SecureKey SecureString] ConvertFrom-SecureString [-SecureString] SecureString [-Key Byte[]]

String String

The string to convert to a SecureString

SecureKey SecureString
Encryption key as a SecureString.

Key Byte[]
Encryption key as a byte array.

 

Following the same example above, we’ll take the output of the previous example and pipe it into the ConvertFrom-SecureString command to get an encrypted standard string.


"P@ssword1" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString

secure password powershell

The result is an encrypted standard string that you can then save for later retrieval.

Putting it all together

We now know how to convert a SecureString to an encrypted standard string. We can take any method we like to get a SecureString, convert it to a standard string and then save it to a file. Here is an example of each:

Exporting SecureString from Plain text


"P@ssword1" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File "C:\Temp 2\Password.txt"

Exporting SecureString from Get-Credential


(Get-Credential).Password | ConvertFrom-SecureString | Out-File "C:\Temp 2\Password.txt"

Exporting SecureString from Read-Host


Read-Host "Enter Password" -AsSecureString |  ConvertFrom-SecureString | Out-File "C:\Temp 2\Password.txt"

Any one of these examples should provide you with a Password.txt file that has an encrypted standard string the represents the password.

When you need to use this encrypted password, you simply reverse the process by importing the data from your file and use ConvertTo-SecureString. If all you need is a SecureString, you can stop there. You could even take it a step further and create a PSCredential object.

Creating SecureString object


$pass = Get-Content "C:\Temp 2\Password.txt" | ConvertTo-SecureString

Creating PSCredential object


$User = "MyUserName"
$File = "C:\Temp 2\Password.txt"
$MyCredential=New-Object -TypeName System.Management.Automation.PSCredential `
-ArgumentList $User, (Get-Content $File | ConvertTo-SecureString)

Final Notes

This will not stop anybody who knows what they’re doing from decrypting your password or from reusing your encrypted password if they ever are able to compromise your login. The whole point of converting your password to a SecureString and storing it in a file is to keep it out of plain text in your scripts so that it’s not as easily discovered. It’s not foolproof, but it’s pretty good.

As mentioned above, when you are not specifying a key or securekey, this will only work for the same user on the same computer will be able to decrypt the encrypted string if you’re not using Keys/SecureKeys. Any process that runs under that same user account will be able to decrypt that encrypted string on that same machine.

If you want to be able to share a credential with multiple machines/logins/etc, then you’ll need to use Keys/SecureKeys. I’ll save that for another post.



原文出處:Secure Password with PowerShell: Encrypting Credentials - Part 1
冷日
(冷日)
Webmaster
  • 註冊日: 2008/2/19
  • 來自:
  • 發表數: 15771
[轉貼]Secure Password with PowerShell: Encrypting Credentials - Part 2

Secure Password with PowerShell: Encrypting Credentials – Part 2

Posted on Posted in PowerShell

In continuing with my previous post,
Secure Password with PowerShell: Encrypting Credentials Part 1, I’d kris_resizedlike to talk about sharing credentials between different machines/users/etc.

To recap my last blog, part 1 of Encrypting Credentials, when you use ConvertTo-SecureString and ConvertFrom-SecureString without a Key or SecureKey, Powershell will use Windows Data Protection API ( DPAPI) to encrypt/decrypt your strings. This means that it will only work for the same user on the same computer.


When you use a Key/SecureKey, the Advanced Encryption Standard (AES – wiki link) encryption algorithm is used. You are able to use the stored credential from any machine with any user so long as you know the AES Key that was used.

Here’s a small snippet from my last blog post for easy reference for the two cmdlets ( link to full post).

ConvertTo-SecureString and ConvertFrom-SecureString

Syntax:

ConvertTo-SecureString [-String] SomeString
ConvertTo-SecureString [-String] SomeString [-SecureKey SecureString] ConvertTo-SecureString [-String] SomeString [-Key Byte[]] ConvertTo-SecureString [-String] SomeString [-AsPlainText] [-Force]

ConvertFrom-SecureString [-SecureString] SecureString [-SecureKey SecureString] ConvertFrom-SecureString [-SecureString] SecureString [-Key Byte[]]

String String
The string to convert to a SecureString

SecureKey SecureString
Encryption key as a SecureString.

Key Byte[] Encryption key as a byte array.

Using no Key/SecureKey

First, let’s show an example of what you will see if you try to create a credential from one machine (Machine 1) and then access it from another machine (Machine 2) without providing a key.

Encrypting a password without a key and saving it to file from Machine 1

This will create the file Password.txt with an encrypted standard string representing the password. It will use DPAPI.



$File = "\\Machine1\SharedPath\Password.txt"
$Password = "P@ssword1" | ConvertTo-SecureString -AsPlainText -Force
$Password | ConvertFrom-SecureString | Out-File $File


Accessing the encrypted password file from Machine 1

This will successfully get the encrypted standard string and convert it to a SecureString.


$File = "\\Machine1\SharedPath\Password.txt"
Get-Content $File | ConvertTo-SecureString

Secure password with powershell

 

Accessing the encrypted password file from Machine 2

This will fail with an error indicating that the key is invalid. Example below:


$File = "\\Machine1\SharedPath\Password.txt"
Get-Content $File | ConvertTo-SecureString

Admin: Windows PowerShell

 

Using Key/SecureKey

Now, let’s show a simple example of creating an encrypted standard string with the use of a key. AES encryption only supports 128-bit (16 bytes), 192-bit (24 bytes) or 256-bit key (32 bytes) lengths, so we’ll need to create or generate an appropriate key. For simplicity, let’s create a simple byte array of ascending numbers. We’ll use a 128-bit key, so we’ll need a 16-byte array.

Long way:


[Byte[]] $key = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)

Short way:


[Byte[]] $key = (1..16)

Encrypting a password and saving it to file from Machine 1

This will create the file Password.txt with an encrypted standard string representing the password. It will use AES.


$File = "\\Machine1\SharedPath\Password.txt"
[Byte[]] $key = (1..16)
$Password = "P@ssword1" | ConvertTo-SecureString -AsPlainText -Force
$Password | ConvertFrom-SecureString -key $key | Out-File $File

Accessing the encrypted password file from Machine 1

This will successfully get the encrypted standard string and convert it to a SecureString. It will use the AES key that we provided earlier.


$File = "\\Machine1\SharedPath\Password.txt"
[Byte[]] $key = (1..16)
Get-Content $File | ConvertTo-SecureString -Key $key

convert to securestring

 

Accessing the encrypted password file from Machine 2

This will successfully get the encrypted standard string and convert it to a SecureString by using the AES key.


$File = "\\Machine1\SharedPath\Password.txt"
[Byte[]] $key = (1..16)
Get-Content $File | ConvertTo-SecureString -Key $key

encrypted password file

Putting it all together

Now that you know how to use an AES key to make SecureStrings created by different user accounts and workstations, you have to protect that key as best as you can since anybody who has that AES key can now decrypt the data protected.

In my previous example, I used a very simple 16-byte array that is stored in the body of the script itself. This is not a good practice and is essentially the same as if you were to write the password in clear text. Alternatively, you could create/generate a key beforehand in a separate script.


As an example, I have built a small script to generate a random 16-byte array. I have used the System.Security.Cryptography.RNGCryptoServiceProvider class to fill a byte array with randomly-generated data.

 

Creating AES key with random data and export to file


$KeyFile = "\\Machine1\SharedPath\AES.key"
$Key = New-Object Byte[] 16 # You can use 16, 24, or 32 for AES
[Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($Key)
$Key | out-file $KeyFile

Creating SecureString object


$PasswordFile = "\\Machine1\SharedPath\Password.txt"
$KeyFile = "\\Machine1\SharedPath\AES.key"
$Key = Get-Content $KeyFile
$Password = "P@ssword1" | ConvertTo-SecureString -AsPlainText -Force
$Password | ConvertFrom-SecureString -key $Key | Out-File $PasswordFile

Creating PSCredential object


$User = "MyUserName"
$PasswordFile = "\\Machine1\SharedPath\Password.txt"
$KeyFile = "\\Machine1\SharedPath\AES.key"
$key = Get-Content $KeyFile
$MyCredential = New-Object -TypeName System.Management.Automation.PSCredential `
-ArgumentList $User, (Get-Content $PasswordFile | ConvertTo-SecureString -Key $key)

Final Notes

That’s it! You will be able to use the key file to decrypt the password file from any machine with any user.

Be sure to protect that AES key as if it were your password. Anybody who can read the AES key can decrypt anything that was encrypted with it.

At the very least, you should implement strict NTFS access controls for both your password and key files. This should keep out most prying eyes. Additionally, you may consider storing the data in a database with strict access controls or even implementing public-key (asymmetric) cryptography for additional control.

In any case, you should be good to use AES keys with your SecureStrings now.

Cheers!


原文出處:Secure Password with PowerShell: Encrypting Credentials - Part 2
前一個主題 | 下一個主題 | 頁首 | | |



Powered by XOOPS 2.0 © 2001-2008 The XOOPS Project|