如何在Powershell中使用给定的AES密钥加密XML内容

时间:2019-01-18 13:00:41

标签: powershell encryption aes

我需要使用供应商API自动创建支持凭单。 API需要使用给定AES密钥加密的XML内容。我怎样才能做到这一点?我在执行以下代码时遇到问题。

$xml =
'
<Service>
    <Action>SubmitTicket</Action>
    <UserName>xxx@xxx.com</UserName>
    <Case>
        <Title>Title</Title>
        <Description>Description</Description>
        <ProductName>ProductName</ProductName>
        <ProductVersion>1.0</ProductVersion>
        <ProductLanguage>English</ProductLanguage>
    <Purpose>Support</Purpose>
    </Case>
</Service>
'

$Key = '!QeRs6%x2RXzk6ab' (fake but similar one)

$secureString = ConvertTo-SecureString $xml -AsPlainText -Force
$encrypted_xml = ConvertFrom-SecureString $secureString -SecureString $key

我收到以下错误消息。

ConvertFrom-SecureString : Cannot bind parameter 'Key'. Cannot convert value 
"!QeRs6%x2RXzk6ab" to type "System.Byte". Error: "Input string was not in a 
correct format." At C:\Users\user\Desktop\Powershell\API_Submitter.ps1:39 
char:62 + $EncryptedInfo = ConvertFrom-SecureString $secureSTring -Key $key
+ CategoryInfo: InvalidArgument: (:) [ConvertFrom-SecureString], 
ParameterBindingException + FullyQualifiedErrorId : 
CannotConvertArgumentNoMessage, 
Microsoft.PowerShell.Commands.ConvertFromSecureStringCommand

1 个答案:

答案 0 :(得分:2)

Key的{​​{1}}参数应该是ConvertFrom-SecureString数组,而不是字符串。您可以使用Byte实现以下目的:(我假设使用GetBytes编码)

UTF8

在调用中指定参数名称:

$Key = [System.Text.Encoding]::UTF8.GetBytes('!QeRs6%x2RXzk6ab')