Board logo

标题: [转载代码] [PowerShell每日技巧]“隐藏”密码(20131210) [打印本页]

作者: DAIC    时间: 2013-12-20 17:20     标题: [PowerShell每日技巧]“隐藏”密码(20131210)

How can you securely embed confidential passwords in a PowerShell script? You can't. But you can make it harder for people to discover the secret.

Here is a code generator script that is designed to run inside the PowerShell ISE editor:
  1. # ask for credentials
  2. $cred = Get-Credential
  3. $pass = $cred.Password
  4. $user = $cred.UserName
  5. # create random encryption key
  6. $key = 1..32 | ForEach-Object { Get-Random -Maximum 256 }
  7. # encrypt password with key
  8. $passencrypted = $pass | ConvertFrom-SecureString -Key $key
  9. # turn key and password into text representations
  10. $secret = -join ($key | ForEach-Object { '{0:x2}' -f $_ })
  11. $secret += $passencrypted
  12. # create code
  13. $code  = '$i = ''{0}'';' -f $secret
  14. $code += '$cred = New-Object PSCredential('''
  15. $code += $user + ''', (ConvertTo-SecureString $i.SubString(64)'
  16. $code += ' -k ($i.SubString(0,64) -split "(?<=\G[0-9a-f]{2})(?=.)" |'
  17. $code += ' % { [Convert]::ToByte($_,16) })))'
  18. # write new script
  19. $editor = $psise.CurrentPowerShellTab.files.Add().Editor
  20. $editor.InsertText($code)
  21. $editor.SetCaretPosition(1,1)
复制代码
When you run it, it asks for a username and a password. Then, it generates a cryptic piece of PowerShell code that you can use in your scripts.

Here's a sample cryptic piece of code generated by the script above:
  1. $i = '73cc7284f9e79f68e9d245b5b2d96c4026397d96cfac6023325d1375414e5f7476492d1116743f0423413b16050a5345MgB8AGgAdABLAEkARABiAFIARgBiAGwAZwBHAHMAaQBLAFoAeQB2AGQAOQAyAGcAPQA9AHwAMgBiADIAMABmADYANwA1ADYANwBiAGYAYwA3AGMAOQA0ADIAMQA3ADcAYwAwADUANAA4ADkAZgBhADYAZgBkADkANgA4ADMAZAA5ADUANABjADgAMgAwADQANQA1ADkAZAA3AGUAMwBmADMAMQAzADQAZgBmADIAZABlADgAZQA=';$cred = New-Object PSCredential('contoso\fabrikam', (ConvertTo-SecureString $i.SubString(64) -k ($i.SubString(0,64) -split "(?<=\G[0-9a-f]{2})(?=.)" | % { [Convert]::ToByte($_,16) })))
复制代码
The cryptic auto-generated script code will define the variable $cred, which will hold a valid credential including the password. You can then use $cred inside of your script wherever a -Credential parameter wants a username and password from you.

http://powershell.com/cs/blogs/tips/archive/2013/12/10/obfuscating-credentials.aspx




欢迎光临 批处理之家 (http://bbs.bathome.net/) Powered by Discuz! 7.2