PowerShell中实现混淆密码示例

适用于PowerShell 3.0或者更高版本,
尽管我们并不推荐将密码硬编码在脚本文件中,但是仍旧有一些场景非如此不可。与将密码以一种纯文本的方式硬编码相比,我们还可以稍微花点心思,把密码混淆一下。虽然混淆密码是一种非常低级的保护方式,但是对于不懂PowerShell的人来讲,还是比较神秘的。

接下来的脚本会向用户询问用户名和密码,然后删除通过混淆脚本进行处理,产生用户凭据对象。

当你运行了下面的脚本以后,用户凭据已经被保存在$cred。接下来你几乎可以在任何带有CCredential参数的命令中使用它了。

代码如下:

$cred = Get-Credential -Message 'Enter Domain\Username and Password'

$pwd = $cred.Password

$user = $cred.UserName

$key = 1..32 | ForEach-Object { Get-Random -Maximum 256 }

$pwdencrypted = $pwd | ConvertFrom-SecureString -Key $key

 

$private:ofs = ' '

 

$generatedScript = @()

$generatedScript += '$password = ''{0}''' -f $pwdencrypted

$generatedScript += '$key = ''{0}''' -f "$key "

 

$generatedScript += '$passwordSecure = ConvertTo-SecureString -String $password -Key ([Byte[]]$key.Split('' ''))'

$generatedScript += '$cred = New-Object system.Management.Automation.PSCredential(''{0}'', $passwordSecure)' -f $user

$generatedScript += '$cred'

 

$file = $psise.CurrentPowerShellTab.Files.Add()

$file.Editor.Text = $generatedScript | Out-String

$file.Editor.SetCaretPosition(1,1)

产生的密码可能像这样:

代码如下:

$password = '76492d1116743f0423413b16050a5345MgB8AHMAUQA3AFAAVwB0AGkAUQBUAC8AdwBqADYAUABVAFYAUwB4AEYAYgB4AFEAPQA9AHwAZgA0ADgAOQA4AGYANwA0AGEAMAA0ADUANwA5ADkAMwA5ADkAMwA1ADUANQA0AGYANwA5AGQANwBkAGYAOQBmAGEAYQA3ADMAYgBkADIAOQA3AGMAYQBmADUAMgA3ADEANwA3AGEAYgBmADAAYgA1AGYAYwAyADYAYgAzADkAOAA='

$key = '187 98 34 82 148 52 13 86 246 2 130 197 217 97 147 98 75 197 149 246 74 35 27 7 211 15 131 93 182 231 171 3'

$passwordSecure = ConvertTo-SecureString -String $password -Key ([Byte[]]$key.Split(' '))

$cred = New-Object system.Management.Automation.PSCredential('mickey\mouse', $passwordSecure)

$cred

相关推荐