欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Go语言常见哈希函数的使用

程序员文章站 2022-11-15 12:10:41
myhash.go /** * created with intellij idea. * user: liaojie * date: 12-9-8...

myhash.go

/**
 * created with intellij idea.
 * user: liaojie
 * date: 12-9-8
 * time: 下午3:53
 * to change this template use file | settings | file templates.
 */
package main
import (
  "crypto/md5"
  "crypto/sha1"
  "crypto/sha256"
  "crypto/sha512"
  "flag" //命令行选项解析器
  "fmt"
  "hash"
  "io"
  "os"
)
var style = flag.string("s", "sha256", "采用的哈西函数:sha1,sha256")
var filename = flag.string("f", "", "需要计算散列值的文件名")
func main() {
  flag.parse()
  var hs hash.hash
  switch *style {
  case "md5":
    hs = md5.new()
  case "sha1":
    hs = sha1.new()
  case "sha512":
    hs = sha512.new()
  default:
    hs = sha256.new()
  }
  if len(*filename) == 0 {
    filein, err := os.open(flag.args()[len(flag.args())-1])
    if err != nil {
      return
    } else {
      io.copy(hs, filein)
    }
  } else {
    filein, err := os.open(*filename)
    if err != nil {
      return
    } else {
      io.copy(hs, filein)
    }
  }
  hashstring := hs.sum(nil)
  fmt.printf("%x\n", hashstring)
}

以上所述就是本文的全部内容了,希望大家能够喜欢。