github.com/Go-To-Byte/DouSheng/user_center@v0.0.0-20230524130918-ad531c1a3f6a/common/utils/hash.go (about)

     1  // @Author: Ciusyan 2023/1/30
     2  package utils
     3  
     4  import (
     5  	"crypto/md5"
     6  	"encoding/json"
     7  	"fmt"
     8  	"golang.org/x/crypto/bcrypt"
     9  )
    10  
    11  // BcryptHash Bcrypt 将敏感数据做强类型慢速哈希
    12  func BcryptHash(data any) string {
    13  
    14  	// 先将数据序列化
    15  	dataMarshal, err := json.Marshal(data)
    16  	if err != nil {
    17  		panic(err)
    18  	}
    19  
    20  	// 对数据做 hash
    21  	bytesPassword, err := bcrypt.GenerateFromPassword(dataMarshal, 14)
    22  
    23  	if err != nil {
    24  		panic(err)
    25  	}
    26  
    27  	return string(bytesPassword)
    28  }
    29  
    30  // VerifyBcryptHash 验证 BcryptHash
    31  func VerifyBcryptHash(data any, hash string) bool {
    32  
    33  	dataMarshal, err := json.Marshal(data)
    34  	if err != nil {
    35  		panic(err)
    36  	}
    37  
    38  	err = bcrypt.CompareHashAndPassword([]byte(hash), dataMarshal)
    39  
    40  	return err == nil
    41  }
    42  
    43  // Md5Hash 对不敏感数据做快速 Hash
    44  func Md5Hash(data any) string {
    45  
    46  	dataMarshal, err := json.Marshal(data)
    47  	if err != nil {
    48  		panic(err)
    49  	}
    50  
    51  	hash := md5.New()
    52  	_, err = hash.Write(dataMarshal)
    53  
    54  	if err != nil {
    55  		panic(err)
    56  	}
    57  
    58  	hd := hash.Sum(nil)
    59  
    60  	return fmt.Sprintf("%x", hd)
    61  }
    62  
    63  // VerifyMd5Hash 验证 Md5Hash
    64  func VerifyMd5Hash(data any, hash string) bool {
    65  	return Md5Hash(data) == hash
    66  }