要点
计算字符串或码流的SHA1: sha1.Sum()
示例代码
util.go
package main
import (
"fmt"
"crypto/sha1"
"io/ioutil"
)
/*
Get the sha1 of file's content.
If success, return the sha1 hex string.
If fail, return "".
*/
func GetFileSHA1(filename string) string {
data, err := ioutil.ReadFile(filename)
if err != nil {
fmt.Println("sum error: ", err)
return ""
}
b := sha1.Sum(data)
return fmt.Sprintf("%X", b)
}
main.go
package main
import (
"fmt"
"io/ioutil"
"os"
)
func main() {
temp_file_name := "xyzabcdefghijklmnxyz.xyz"
content := []byte("Hello, Go Programming Language!")
err := ioutil.WriteFile(temp_file_name, content, 0666)
if err != nil {
fmt.Println(err)
return
}
sha1 := GetFileSHA1(temp_file_name)
fmt.Println(sha1)
os.Remove(temp_file_name)
}
运行
$ go run main.go util.go
C6ADC2F32EF2455EE0A7F66A874431B20043384F
$
相关命令 shasum & openssl sha1
$ echo -n Hello, Go Programming Language! > xyzabcdefghijklmnxyz.xyz
$ shasum xyzabcdefghijklmnxyz.xyz
c6adc2f32ef2455ee0a7f66a874431b20043384f xyzabcdefghijklmnxyz.xyz
$ openssl sha1 xyzabcdefghijklmnxyz.xyz
SHA1(xyzabcdefghijklmnxyz.xyz)= c6adc2f32ef2455ee0a7f66a874431b20043384f
$
有疑问加站长微信联系(非本文作者)