Go语言常用的哈希加密函数

安装包

1
go get -u -v golang.org/x/crypto/bcrypt

哈希加密和解密函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// @package    : bcrypt
// @file : pwd.go
// @author : hqd8080
// @contact : hanquanding@163.com
// @time : 2024/1/02
// @description: 哈希密码加密和密码校验

package bcrypt

import "golang.org/x/crypto/bcrypt"

// HashPassword 密码哈希加密
func HashPassword(password string) (string, error) {
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.MinCost)
return string(hash), err
}

// CheckPasswordHash 密码校验 password:原始密码 hash:加密之后的密码
func CheckPasswordHash(password, hash string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
if err != nil {
return false
}
return true
}

单元测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// @package    : bcrypt
// @file : pwd_test.go
// @author : hqd8080
// @contact : hanquanding@163.com
// @time : 2024/1/02
// @description: pwd_test

package bcrypt

import "testing"

func TestHashPassword(t *testing.T) {
password, err := HashPassword("123456")
if err != nil {
t.Fatal(err)
}
t.Log(password)
}

func TestCheckPasswordHash(t *testing.T) {
isOk := CheckPasswordHash("123456", "$2a$04$7UBIkdPQq44m0v6FenQ2Ke8Yp6EBrJQJ4Fuox15IkRJ.eHGbOwcwC")
t.Log(isOk)
}
1
2
3
4
5
6
7
8
9
10
11
=== RUN   TestHashPassword
pwd_test.go:17: $2a$04$7UBIkdPQq44m0v6FenQ2Ke8Yp6EBrJQJ4Fuox15IkRJ.eHGbOwcwC
--- PASS: TestHashPassword (0.00s)
PASS


=== RUN TestCheckPasswordHash
pwd_test.go:22: true
--- PASS: TestCheckPasswordHash (0.00s)
PASS