加密凭据,导出,然后导入

Encrypt Credentials, Export, then Import

我使用 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 : The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input. At C:\Powershell\Password.ps1:15 char:13 + $Password | ConvertFrom-SecureString -Key $Key | Out-File $PasswordFile + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidArgument: (System.Security.SecureString:String) [ConvertFrom-SecureString], ParameterBindingException + FullyQualifiedErrorId : InputObjectNotBound,Microsoft.PowerShell.Commands.ConvertFromSecureStringCommand

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

为简单起见:

将凭据对象保存到磁盘:

$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)

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

如果您根本不使用密钥,则凭据将使用您当前的用户进行加密,并且只有当前用户才能将其解密。