feat: first version.
This commit is contained in:
17
crypto/crypto.go
Normal file
17
crypto/crypto.go
Normal file
@@ -0,0 +1,17 @@
|
||||
package crypto
|
||||
|
||||
import (
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
// HashPassword 加密密码
|
||||
func HashPassword(password string) (string, error) {
|
||||
bytes, err := bcrypt.GenerateFromPassword([]byte(password), 10)
|
||||
return string(bytes), err
|
||||
}
|
||||
|
||||
// CheckPasswordHash 校验密码
|
||||
func CheckPasswordHash(password, hash string) bool {
|
||||
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
|
||||
return err == nil
|
||||
}
|
||||
32
crypto/crypto_test.go
Normal file
32
crypto/crypto_test.go
Normal file
@@ -0,0 +1,32 @@
|
||||
package crypto
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHashPassword(t *testing.T) {
|
||||
text := "admin"
|
||||
hash, _ := HashPassword(text)
|
||||
fmt.Println(hash)
|
||||
}
|
||||
|
||||
func TestCheckPasswordHash(t *testing.T) {
|
||||
text := "123456"
|
||||
hash3 := "$2a$10$ygWrRwHCzg2GUpz0UK40kuWAGva121VkScpcdMNsDCih2U/bL2qYy"
|
||||
bMatched := CheckPasswordHash(text, hash3)
|
||||
assert.True(t, bMatched)
|
||||
|
||||
bMatched = CheckPasswordHash(text, hash3)
|
||||
assert.True(t, bMatched)
|
||||
}
|
||||
|
||||
func TestJwtToken(t *testing.T) {
|
||||
const bearerWord string = "Bearer"
|
||||
token := "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjowfQ.XgcKAAjHbA6o4sxxbEaMi05ingWvKdCNnyW9wowbJvs"
|
||||
auths := strings.SplitN(token, " ", 2)
|
||||
assert.Equal(t, len(auths), 2)
|
||||
assert.Equal(t, strings.EqualFold(auths[0], bearerWord), true, "JWT token is missing")
|
||||
}
|
||||
Reference in New Issue
Block a user