Powershell 字节数组转十六进制

问题描述 投票:0回答:4

我有以下字节数组,我想获取十六进制格式,以便使用 aes-256-ecb 解密加密字符串。 (如果您在

ConvertFrom-SecureString
函数中指定密钥参数,PowerShell 将使用 AES 加密)

为了检查这一点,我使用 openssl 进行验证:

echo 'mysecretdata' | openssl enc -d -aes-256-ecb -K 303534303438303439303939303438303938303937303435303530303530303937303537303435303439303439303130310a

十六进制字符串太长 无效的十六进制键值

我错过了什么?

arrays powershell encryption byte aes
4个回答
27
投票

您可以在每个单独的字节上使用

X2
格式字符串来获取其十六进制表示形式,然后使用
-join
运算符连接字符串:

$bytes = 0,54,0,48,0,49,0,99,0,48,0,98,0,97,0,45,0,50,0,50,0,97,0,57,0,45,0,49,0,49,0,101
$hexString = ($bytes|ForEach-Object ToString X2) -join ''

(如果这是您的实际密钥,您可能不想再次使用它,因为它已成为公共知识;-))


15
投票

如果您可以使用连字符,则可以使用

string System.BitConverter::ToString(byte[] value)
静态方法:

PS> $bytes = 0,7,14,21,28,35,42
PS> [System.BitConverter]::ToString($bytes)
00-07-0E-15-1C-23-2A
PS>
PS> # If you'd like to use this in a pipeline:
PS> ,$bytes | % { [System.BitConverter]::ToString($_) }
00-07-0E-15-1C-23-2A
PS>
PS> # If you can't obtain a byte[]-compatible input:
PS> $bytes | . { [System.BitConverter]::ToString(@($input)) }
00-07-0E-15-1C-23-2A

逗号运算符 (

,
) 确保传入字节数组(或可转换为此类的对象)(通过
ForEach-Object
(
%
)
在 1 元素数组上运行脚本块)照原样,而不是迭代。

如果这是不可避免的,则后一个示例使用 点采购运算符 (

.
)、脚本块和 数组子表达式运算符 (
@( )
)
$input
自动收集项目函数变量(一个
IEnumerator
not
IEnumerable
)并生成一个数组
ToString
很满意。


1
投票

这是将字节数组转换为十六进制字符串的通用方法:

$array  = [byte[]](1..15)
$hexbin = [System.Runtime.Remoting.Metadata.W3cXsd2001.SoapHexBinary]::new()
$hexbin.Value = $array
$hexString = $hexbin.ToString()

给出了这个结果: 0102030405060708090A0B0C0D0E0F

另一个方向是这样的:

$bytes = [System.Runtime.Remoting.Metadata.W3cXsd2001.SoapHexBinary]::Parse($hexString).Value

在您原来的问题中,我根本没有看到数组,但 AES256 密钥必须精确为 32 个字节长(由 64 个字符的十六进制字符串表示)。您的咒语长度为 100 个字符。


0
投票

虽然目前这里得到最多支持的答案建议使用管道,但我建议使用 ForEach 方法,如下所示:

$bytes = -split '0 54 0 48 0 49 0 99 0 48 0 98 0 97 0 45 0 50 0 50 0 97 0 57 0 45 0 49 0 49 0 101' -as 'byte[]'
$hexString = -join $bytes.ForEach('ToString','X2')  # for lowercase string, use 'x2' instead of 'X2'

您可以从这篇

powershellmagazine.com 文章
(archive.org) (archive.today) 提供的 ForEach 和Where 方法的详细细分中了解更多关于我如何使用 ForEach 的信息。或者,这是我提出的相关部分的精简版本:

ForEach(字符串方法名称) / ForEach(字符串方法名称, 对象[]参数)

提供方法名称作为第一个参数;提供的任何后续参数都将传递给该方法。

$strings = 'Foo', 'BAR', 'loRem', 'ipsum'

# Output each string as lowercase
$strings.ForEach('ToLower')
$dates = [datetime]'2023-01-04', [datetime]'2022-04-12', [datetime]'2021-10-30'

# Output with a year deducted from each date
$dates.ForEach('AddYears',-1)

© www.soinside.com 2019 - 2024. All rights reserved.