在我的函数中,机器名的字符串形式和 [Environment]::MachineName.ToString() 的输出为什么会不同?
为什么当我把我的机器名字符串传入时,会得到两种不同的输出值?使用 [Environment]::MachineName.ToString() 时似乎也有差异。似乎SHA256将它们视为不同的输入,而我需要让它们被视为相同,从而输出相同的值。
如果你按如下所示运行Set-Value函数,第一次运行时需要在引号中填入机器名,第二次运行时再省略它,你将看到两个不同的输出
function Set-Value()
{
param (
[Parameter()]
[string]
$p_ranNumber, # required
[Parameter()]
[string]
$p_machineName # not required
)
$envMachineName = [Environment]::MachineName;
$displayOnly = $false;
if ($p_machineName -eq "")
{
$p_machineName = $envMachineName;
}
else
{
$displayOnly = $true;
}
$combinedString = "$($p_ranNumber)`:$($p_machineName)"
$bytes = [System.Text.Encoding]::UTF8.GetBytes($combinedString);
$sha256 = [System.Security.Cryptography.SHA256]::Create();
$hashBytes = $sha256.ComputeHash($bytes);
$hexString = ($hashBytes | ForEach-Object { $_.ToString("X2") }) -join '';
if ($displayOnly -eq $true)
{
Write-Host "$($p_ranNumber)_$($hexString)";
}
else
{
Write-Host "$($p_ranNumber)_$($hexString)";
}
}
Set-Value -p_ranNumber "123456" -p_machineName "[machine name string]";
Set-Value -p_ranNumber "123456";
解决方案
在注释中整理出原因,问题是由大小写不一致引起;.NET的加密哈希函数(MD5、SHA256等)是区分大小写的。解决方法是使用 .ToLowerInvariant() 或 .ToUpperInvariant() 对字符串进行规范化,例如:
function Set-Value {
param (
[Parameter()]
[string]
$p_ranNumber, # required
[Parameter()]
[string]
$p_machineName = [Environment]::MachineName.ToLowerInvariant()
)
# if p_machineName is used
if ($PSBoundParameters.ContainsKey('p_machineName')) {
# normalize it
$p_machineName = $p_machineName.ToLowerInvariant()
}
# rest remains the same..
}
此外,对于十六进制字符串,你可以在PowerShell 7+中使用 Convert.ToHexString(...):
$hexString = [System.Convert]::ToHexString($hashBytes)
或者在PowerShell 5.1中使用 BitConverter.ToString(...):
$hexString = [System.BitConverter]::ToString($hashBytes).Replace('-', '')
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。