go语言练习:文件哈希

package main

import (
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"io"
	"os"
)

func gethash(path string) (hash string) {
	file, err := os.Open(path)
	if err == nil {
		h_ob := sha256.New()
		_, err := io.Copy(h_ob, file)
		if err == nil {
			hash := h_ob.Sum(nil)
			hashvalue := hex.EncodeToString(hash)
			return hashvalue
		} else {
			return "something wrong when use sha256 interface..."
		}
	} else {
		fmt.Printf("failed to open %s\n", path)
	}
	defer file.Close()
	return
}
func main() {
	path := "test"
	//path:="md5.go"
	hash := gethash(path)
	fmt.Printf("%s hash: %s", path, hash)
}

//test hash: 599593e4bd8f877acf8f00805e52eb0ffac4c662bc65349bf9eb3e3c9871a2bb

  

猜你喜欢

转载自www.cnblogs.com/chenadong/p/9058259.html
今日推荐