首页 > 解决方案 > PowerShell:ConvertTo-SecureString 和 ConvertFrom-SecureString 在 PSSession 内的问题

问题描述

我尝试在 2 个 Powershell 脚本中使用 ConvertTo- 和 ConvertFrom-SecureString,但我在使用动态配置文件生成加密密码,然后在同一台机器上使用相同配置文件读取/解密它们时遇到问题。

我的脚本要求交互式用户 (IU) 输入任务用户 (TU) 的凭据。逻辑是在 IU 的 powershell 会话中为 TU 创建一个 PSSession,从纯文本(或读取主机)生成安全字符串,并将其转换为常规字符串以将其导出到文件。

$scriptUser = Read-Host "Entrez le nom de l'utilisateur qui va chiffrer/utiliser le fichier de mot de passe (domain\user)"
$scriptCredential = Get-Credential -Message "Veuillez entrer le mot de passe de l'utilisateur $scriptUser" -User $scriptUser

$Crypt = New-PSSession -Credential $scriptCredential -ComputerName localhost
if ($Crypt)
{
    Enter-PSSession $Crypt
    $Texte = "JULIEN"
    ConvertTo-SecureString $Texte -AsPlainText -Force | ConvertFrom-SecureString | Set-Content -Path C:\PathToFile\testcrypt_adm_task.txt
    Exit-PSSession
}

但是当我尝试使用带有 TU(交互式或任务调度程序)的 ConvertFrom-SecureString 读取文件的内容时:没门!

> PS C:\PathToFile> Get-Content .\testcrypt_adm_task.txt |
> convertto-securestring convertto-securestring : Key not valid for use
> in specified state. At line:1 char:40
> + Get-Content .\testcrypt_adm_task.txt | convertto-securestring
> +                                        ~~~~~~~~~~~~~~~~~~~~~~
>     + CategoryInfo          : InvalidArgument: (:) [ConvertTo-SecureString], CryptographicException
>     + FullyQualifiedErrorId : ImportSecureString_InvalidArgument_CryptographicError,Microsoft.PowerShell.Commands.Conv    ertToSecureStringCommand

如果我对我的 IU 执行完全相同的命令,没问题,就好像用于加密我的 Securestring 的密钥绑定到我的 IU 而不是我的 TU。

关键是我在真正理解 PSSession 真正加载的内容时遇到了问题,因为我的 IU 而不是我的 TU 可以读取安全字符串,即使加密操作是在具有 TU 凭据的 PSSession 中完成的。 .

Enter-PSSession 不是意味着真正进入一个会话,所有环境都包含它吗?关于使用 Enter-PSSession 加载的环境,我有什么遗漏吗?

谢谢你的帮助

标签: powershellsessionprofilesecurestring

解决方案


可能您使用不同的用户创建了安全字符串,并尝试使用不同的用户转换回纯文本。请使用同一用户使其安全并将其转换回纯文本。


推荐阅读