Files
gf/crypto/gsha1/gsha1.go

53 lines
1.3 KiB
Go
Raw Normal View History

2021-01-17 21:46:25 +08:00
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
2017-12-29 16:03:30 +08:00
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
2017-12-29 16:03:30 +08:00
// Package gsha1 provides useful API for SHA1 encryption algorithms.
2017-11-23 10:21:28 +08:00
package gsha1
import (
2019-06-19 09:06:52 +08:00
"crypto/sha1"
"encoding/hex"
"io"
"os"
2019-06-21 22:23:07 +08:00
"github.com/gogf/gf/v2/errors/gerror"
2021-10-11 21:41:56 +08:00
"github.com/gogf/gf/v2/util/gconv"
2017-11-23 10:21:28 +08:00
)
// Encrypt encrypts any type of variable using SHA1 algorithms.
// It uses package gconv to convert `v` to its bytes type.
func Encrypt(v interface{}) string {
2019-06-19 09:06:52 +08:00
r := sha1.Sum(gconv.Bytes(v))
return hex.EncodeToString(r[:])
2017-11-23 10:21:28 +08:00
}
// EncryptFile encrypts file content of `path` using SHA1 algorithms.
2019-06-21 22:23:07 +08:00
func EncryptFile(path string) (encrypt string, err error) {
f, err := os.Open(path)
if err != nil {
err = gerror.Wrapf(err, `os.Open failed for name "%s"`, path)
2019-06-21 22:23:07 +08:00
return "", err
2019-06-19 09:06:52 +08:00
}
defer f.Close()
2019-06-19 09:06:52 +08:00
h := sha1.New()
2019-06-21 22:23:07 +08:00
_, err = io.Copy(h, f)
if err != nil {
err = gerror.Wrap(err, `io.Copy failed`)
2019-06-21 22:23:07 +08:00
return "", err
2019-06-19 09:06:52 +08:00
}
2019-06-21 22:23:07 +08:00
return hex.EncodeToString(h.Sum(nil)), nil
2019-06-19 09:06:52 +08:00
}
// MustEncryptFile encrypts file content of `path` using SHA1 algorithms.
// It panics if any error occurs.
func MustEncryptFile(path string) string {
result, err := EncryptFile(path)
if err != nil {
panic(err)
}
return result
}