Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConvertTo-SecureString without -AsPlainText -Force

The PSScriptAnalyzer has a PSAvoidUsingConvertToSecureStringWithPlainText warning. Meaning that using the following code will fail.

$password = [System.Web.Security.Membership]::GeneratePassword(128,0)
$securePassword = ConvertTo-SecureString -String $password -AsPlainText -Force
$configCredential = New-Object System.Management.Automation.PSCredential ($username,$securePassword)

However there is very little (/none) guidance on how convert a regular string into a secure string without the -AsPlainText -Force options. (I do understand the security implications of regular strings)

How can I achieve the above securely / without irking PSScriptAnalyzer (I'm not looking to suppress the message)

like image 520
Michael B Avatar asked Oct 04 '16 04:10

Michael B


1 Answers

I can't quite tell what you're asking, but I'll give answers for the different interpretations I have for your question.

"How can I generate a password for a PSCredential without ConvertTo-SecureString?"

You can pass a regular string directly to the constructor and it will convert it to a SecureString internally.

$password = [System.Web.Security.Membership]::GeneratePassword(128,0)
$configCredential = New-Object PSCredential ($username, $password)

However, best practice when using SecureString values is to never have the secret value in plaintext in the first place - the reason you have to specify -Force with -AsPlainText, and probably also why the PSScriptAnalyzer rule exists in the first place, is to discourage this practice. If you rely on the security of the SecureString for threat mitigation, you should follow this gentle coercion by avoiding the plaintext $password variable:

$configCredential = New-Object PSCredential ($username, [System.Web.Security.Membership]::GeneratePassword(128,0))

"How can I convert a string to a secure string without tripping or suppressing PSScriptAnalyzer errors?"

If you don't care about the credential object itself, but want a SecureString without using ConvertTo-SecureString, you can still (ab)use the PSCredential class for this purpose. An easier to read example:

$password = [System.Web.Security.Membership]::GeneratePassword(128,0)
$configCredential = New-Object PSCredential ($username, $password)
$securePassword = $configCredential.Password

A one-liner that follows best practices:

$securePassword = New-Object PSCredential ($username, [System.Web.Security.Membership]::GeneratePassword(128,0)) | Select-Object -ExpandProperty Password

You can also divide a string into characters and append them to a SecureString one by one:

$securePassword = New-Object SecureString
foreach ($char in [System.Web.Security.Membership]::GeneratePassword(128,0).ToCharArray()) {
    $securePassword.AppendChar($char)
}
like image 148
Micah R Ledbetter Avatar answered Sep 21 '22 10:09

Micah R Ledbetter