【问题标题】:Encrypt Credentials, Export, then Import加密凭证,导出,然后导入
【发布时间】:2016-03-14 22:19:22
【问题描述】:

我使用 Powershell 已经有一段时间了,但我不明白加密是如何工作的,甚至不确定我在阅读帮助文件时使用了正确的语法。

#Get User Information
$User = Read-Host "Please enter your username"
$Password = Read-Host "Please enter your password. This will be encrypted" -AsSecureString | ConvertTo-SecureString -AsPlainText -Force

#Define a Key File
$KeyFile = "C:\Powershell\AES.key"
$Key = New-Object Byte[] 32
[Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($Key)
$Key | out-file $KeyFile

#Encrypt using AES
$PasswordFile = "C:\Powershell\Password.txt"
$KeyFile = "C:\Powershell\AES.key"
$Key = Get-Content $KeyFile
$Password | ConvertFrom-SecureString | Out-File $PasswordFile

#Set credentials to be called.
$myCredentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, (Get-Content $PasswordFile | ConvertTo-SecureString -Key $key)

#Open text file.
Invoke-Command -ComputerName localhost -Credential $MyCredentials -ScriptBlock{
    Invoke-Item C:\Powershell\Password.txt
    }

我在运行这个时收到一个错误,我不确定为什么我不能通过管道传输这个:

ConvertFrom-SecureString : 输入对象不能绑定到任何 该命令的参数要么是因为该命令不采用 管道输入或输入及其属性与任何 接受管道输入的参数。在 C:\Powershell\Password.ps1:15 字符:13 + $密码 | ConvertFrom-SecureString -Key $Key |输出文件 $PasswordFile + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidArgument: (System.Security.SecureString:String) [ConvertFrom-SecureString], 参数绑定异常 + FullyQualifiedErrorId : InputObjectNotBound,Microsoft.PowerShell.Commands.ConvertFromSecureStringCommand

是否有任何加密专家可以提供帮助?我试图简单地将密码保存到文本文件(加密),然后我想使用另一个脚本使用加密密码使用新凭据调用各种程序,但我什至无法让加密密码正常工作。提前致谢。

【问题讨论】:

    标签: powershell password-encryption


    【解决方案1】:

    为了简单起见:

    将凭据对象保存到磁盘:

    $credential = Get-Credential
    $Key = [byte]1..32
    $credential.Password | ConvertFrom-SecureString -Key $Key | Set-Content c:\cred.key
    

    将其加载回 Powershell:

    $Key = [byte]1..32
    $username = "type the username here"
    $encrypted = Get-Content c:\cred.key | ConvertTo-SecureString -Key $Key
    
    ## Create The Credential Object:
    
    $credential = New-Object System.Management.Automation.PsCredential($username, $encrypted)
    

    确保这不安全,因为看到您的代码的每个人都可以重复使用凭据,

    如果您根本不使用密钥,则凭据将使用您的当前用户加密,并且只有当前用户可以将其解密回来。

    【讨论】:

    • 这似乎工作得很好。我试图在 Invoke-Command 中传递这些凭据,但每次我运行它来调用 txt 文件时,我什么也得不到。也许我没有正确地做那部分。 Nvm,我真是太笨了,想太多了,今天是星期一。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 2016-06-20
    • 2016-04-24
    • 2013-10-07
    • 2020-10-14
    相关资源
    最近更新 更多