doule6314 2013-04-08 12:34
浏览 435
已采纳

如何在Go中计算sha256文件校验和

I need utility for Windows that calculates sha256 file checksum so that when I download fedora I can verify checksum from here: https://fedoraproject.org/static/checksums/Fedora-18-i386-CHECKSUM

Microsoft utility from http://support.microsoft.com/kb/889768 does only md5 and sha1.

I don't want to use other downloadable tools that are not signed and not available from https or from sources that I don't know about, because it does not make any sense to download unsigned code over unencrypted connection or from untrusted source to verify signature of another code to trust it.

Luckily google provides possibility to use https for all downloads so I can download Go over secure connection and start from there.

Here is simple code that does that for a small file, but it's not very good for big files because it's not streaming.

package main

import (
    "io/ioutil"
    "crypto/sha256"
    "os"
    "log"
    "encoding/hex"
)

func main() {
    hasher := sha256.New()
    s, err := ioutil.ReadFile(os.Args[1])    
    hasher.Write(s)
    if err != nil {
        log.Fatal(err)
    }

    os.Stdout.WriteString(hex.EncodeToString(hasher.Sum(nil)))
}

How to make it to use streams so that it works on any file size.

  • 写回答

3条回答 默认 最新

  • douwen7603 2013-04-09 03:20
    关注

    The SHA256 hasher implements the io.Writer interface, so one option would be to use the io.Copy() function to copy the data from an appropriate io.Reader in blocks. Something like this should do:

    f, err := os.Open(os.Args[1])
    if err != nil {
        log.Fatal(err)
    }
    defer f.Close()
    if _, err := io.Copy(hasher, f); err != nil {
        log.Fatal(err)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 我想在一个软件里添加一个优惠弹窗,应该怎么写代码
  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流