比较 Azure Properties.ContentMD5 和 Get-Filehash 之间的字符串输出

Comparing string outputs between Azure Properties.ContentMD5 and Get-Filehash

如何直接比较 Get-FileHash 的输出与 Properties.ContentMD5 的输出?


我正在整理一个 PowerShell 脚本,该脚本从我的系统中获取一些本地文件并将它们复制到 Azure Blob 存储容器。

文件每天都在变化,所以我添加了一个检查,在上传之前检查文件是否已经存在于容器中。

我用Get-FileHash读取本地文件:

$LocalFileHash = (Get-FileHash "D:\file.zip" -Algorithm MD5).Hash

这导致 $LocalFileHash 持有这个:67BF2B6A3E6657054B4B86E137A12382

我使用此代码获取已传输到容器的 blob 文件的校验和:

$BlobFile = "Path\To\file.zip"
$AZContext = New-AZStorageContext -StorageAccountName $StorageAccountName -SASToken "<token here>"

$RemoteBlobFile = Get-AzStorageBlob -Container $ContainerName -Context $AZContext -Blob $BlobFile -ErrorAction Ignore 
if ($ExistingBlobFile) { 
    $cloudblob = [Microsoft.Azure.Storage.Blob.CloudBlockBlob]$RemoteBlobFile.ICloudBlob
    $RemoteBlobHash = $cloudblob.Properties.ContentMD5
}

这个$RemoteBlobHash的值设置为Z78raj5mVwVLS4bhN6Ejgg==

没问题,我想,我将解密 Base64 字符串并进行比较:

$output = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($RemoteBlobHash))

这给了我 g�+j>fWKK��7�#� 所以不能直接比较 ☹


显示有人在类似的泡菜中,但我认为他们没有使用 Get-FileHash 给出他们本地 MD5 结果的格式。

我尝试过的其他事情:

$output = [System.Text.Encoding]::UTF8.GetBytes([System.Text.Encoding]::UTF16.GetString([System.Convert]::FromBase64String($RemoteBlobHash)))

注意:使用 md5sum 比较本地文件和 file.zip 的下载副本会产生与 Get-FileHash 相同的 MD5 字符串:67BF2B6A3E6657054B4B86E137A12382

提前致谢!

ContentMD5binary 哈希值的 base64 表示,而不是生成的十六进制字符串 :)

$md5sum = [convert]::FromBase64String('Z78raj5mVwVLS4bhN6Ejgg==')
$hdhash = [BitConverter]::ToString($md5sum).Replace('-','')

这里我们转换base64 -> 二进制 -> 十六进制


如果您需要以相反的方式进行(即获取本地文件哈希,然后使用它在 Azure 中搜索 blob),您首先需要将十六进制字符串拆分为字节大小块,然后将生成的字节数组转换为 base64:

$hdhash = '67BF2B6A3E6657054B4B86E137A12382'
$bytes  = [byte[]]::new($hdhash.Length / 2)
for($i = 0; $i -lt $bytes.Length; $i++){
  $offset = $i * 2
  $bytes[$i] = [convert]::ToByte($hdhash.Substring($offset,2), 16)
}
$md5sum = [convert]::ToBase64String($bytes)