实现说明
sha1 计算遗留数据摘要可以归结为函数 main。
使用要点
- 跑完文件,输出里会留下标记——
digest hex:、digest bytes:、streamed matches:。
常见问题
运行「sha1 计算遗留数据摘要」会打印什么?
整个文件跑完,输出行以 digest hex:、digest bytes:、streamed matches: 这类前缀开头。
核心语句
other := sha1.Sum([]byte("legacy artifact indax"))
代码示例
package main
import (
"crypto/sha1"
"encoding/hex"
"fmt"
)
func main() {
manifest := []byte("legacy artifact index")
// Sum:一次性计算,返回 [20]byte 定长数组
sum := sha1.Sum(manifest)
fmt.Println("digest hex:", hex.EncodeToString(sum[:]))
fmt.Println("digest bytes:", len(sum))
// 分块写入与整段计算等价:适合大文件流式场景
hash := sha1.New()
hash.Write([]byte("legacy "))
hash.Write([]byte("artifact index"))
fmt.Println("streamed matches:", hex.EncodeToString(hash.Sum(nil)) == hex.EncodeToString(sum[:]))
// 相同输入必得相同摘要;改动一个字节摘要完全不同
other := sha1.Sum([]byte("legacy artifact indax"))
fmt.Println("same digest:", sum == other)
}