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,
|
2019-02-02 16:18:25 +08:00
|
|
|
// You can obtain one at https://github.com/gogf/gf.
|
2017-12-29 16:03:30 +08:00
|
|
|
|
2019-05-24 19:59:08 +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
|
|
|
|
2021-12-21 22:59:14 +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
|
|
|
)
|
|
|
|
|
|
2019-05-24 19:59:08 +08:00
|
|
|
// Encrypt encrypts any type of variable using SHA1 algorithms.
|
2021-09-16 20:57:59 +08:00
|
|
|
// It uses package gconv to convert `v` to its bytes type.
|
2018-08-08 10:05:16 +08:00
|
|
|
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
|
|
|
}
|
|
|
|
|
|
2021-09-16 20:57:59 +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 {
|
2021-12-21 22:59:14 +08:00
|
|
|
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
|
|
|
}
|
2019-10-11 22:54:25 +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 {
|
2021-12-21 22:59:14 +08:00
|
|
|
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
|
|
|
}
|
2019-12-12 11:40:23 +08:00
|
|
|
|
2021-09-16 20:57:59 +08:00
|
|
|
// MustEncryptFile encrypts file content of `path` using SHA1 algorithms.
|
2019-12-12 11:40:23 +08:00
|
|
|
// It panics if any error occurs.
|
|
|
|
|
func MustEncryptFile(path string) string {
|
|
|
|
|
result, err := EncryptFile(path)
|
|
|
|
|
if err != nil {
|
|
|
|
|
panic(err)
|
|
|
|
|
}
|
|
|
|
|
return result
|
|
|
|
|
}
|