github.com/gogf/gf/v2@v2.7.4/crypto/gsha1/gsha1.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/gogf/gf.
     6  
     7  // Package gsha1 provides useful API for SHA1 encryption algorithms.
     8  package gsha1
     9  
    10  import (
    11  	"crypto/sha1"
    12  	"encoding/hex"
    13  	"io"
    14  	"os"
    15  
    16  	"github.com/gogf/gf/v2/errors/gerror"
    17  	"github.com/gogf/gf/v2/util/gconv"
    18  )
    19  
    20  // Encrypt encrypts any type of variable using SHA1 algorithms.
    21  // It uses package gconv to convert `v` to its bytes type.
    22  func Encrypt(v interface{}) string {
    23  	r := sha1.Sum(gconv.Bytes(v))
    24  	return hex.EncodeToString(r[:])
    25  }
    26  
    27  // EncryptFile encrypts file content of `path` using SHA1 algorithms.
    28  func EncryptFile(path string) (encrypt string, err error) {
    29  	f, err := os.Open(path)
    30  	if err != nil {
    31  		err = gerror.Wrapf(err, `os.Open failed for name "%s"`, path)
    32  		return "", err
    33  	}
    34  	defer f.Close()
    35  	h := sha1.New()
    36  	_, err = io.Copy(h, f)
    37  	if err != nil {
    38  		err = gerror.Wrap(err, `io.Copy failed`)
    39  		return "", err
    40  	}
    41  	return hex.EncodeToString(h.Sum(nil)), nil
    42  }
    43  
    44  // MustEncryptFile encrypts file content of `path` using SHA1 algorithms.
    45  // It panics if any error occurs.
    46  func MustEncryptFile(path string) string {
    47  	result, err := EncryptFile(path)
    48  	if err != nil {
    49  		panic(err)
    50  	}
    51  	return result
    52  }