首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用常用的散列算法对PowerShell中的字符串、字节数组和io流进行散列

如何使用常用的散列算法对PowerShell中的字符串、字节数组和io流进行散列
EN

Stack Overflow用户
提问于 2020-05-01 20:07:30
回答 1查看 150关注 0票数 0

如何使用MD4、MD5、SHA1等常用散列算法对字符串、字节数组、io流等数据进行散列处理……我正在写一个脚本,使驱动器备份,并防止不必要的副本,并检测如果文件被损坏,它需要用一些散列算法,如MD4快速散列文件。如果有人知道如何散列文件,io流,字节数组,字符串...使用任何散列算法,请让我知道。另外,Get-FileHash cmdlet并不是在我遇到的所有Windows安装中都存在。

EN

回答 1

Stack Overflow用户

发布于 2020-05-01 20:23:46

创建一个[System.Security.Cryptography.MD5]实例,然后将文件流传递给它的ComputeHash()方法:

代码语言:javascript
复制
function Get-MD5Sum
{
  param(
    [Parameter(Mandatory, ValueFromPipelineByPropertyName)]
    [Alias('PSPath')]
    [string[]]$Path
  )
  begin {
    $md5 = [System.Security.Cryptography.MD5]::Create()
  }

  process {
    foreach($filePath in $Path){
      # Resolve filesystem item
      $file = Get-Item -LiteralPath $Path

      # Skip if not a file
      if($file -isnot [System.IO.FileInfo]){
        continue
      }

      # Open a stream to read the file
      $filestream = $file.OpenRead()

      try {
        # Calculate + format hash, then output
        Write-Output $([pscustomobject]@{
          File = $file.FullName
          Hash = [BitConverter]::ToString($MD5.ComputeHash($filestream)) -replace '-'
        })
      }
      finally {
        # close file stream handle 
        $filestream.Dispose()
      }
    }
  }

  end {
    # Dispose of the hash provider
    $MD5.Dispose()
  }
}

现在您可以在不使用Get-FileHash的情况下计算MD5文件哈希

代码语言:javascript
复制
PS C:\> $fileHashes = Get-ChildItem . |Get-MD5Sum
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61542205

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档