Feat: compatible digest algorithm with V2
This commit is contained in:
parent
c4c174f560
commit
25d1735c1d
3 changed files with 38 additions and 3 deletions
2
assets
2
assets
|
@ -1 +1 @@
|
||||||
Subproject commit 4f146a643bebec30e13866bef92cb3327b587fb3
|
Subproject commit fdf67a42027207cfef168b439706406620e7ee06
|
|
@ -1,6 +1,7 @@
|
||||||
package model
|
package model
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"crypto/md5"
|
||||||
"crypto/sha1"
|
"crypto/sha1"
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
@ -191,11 +192,24 @@ func (user *User) CheckPassword(password string) (bool, error) {
|
||||||
|
|
||||||
// 根据存储密码拆分为 Salt 和 Digest
|
// 根据存储密码拆分为 Salt 和 Digest
|
||||||
passwordStore := strings.Split(user.Password, ":")
|
passwordStore := strings.Split(user.Password, ":")
|
||||||
if len(passwordStore) != 2 {
|
if len(passwordStore) != 2 && len(passwordStore) != 3 {
|
||||||
return false, errors.New("Unknown password type")
|
return false, errors.New("Unknown password type")
|
||||||
}
|
}
|
||||||
|
|
||||||
// todo 兼容V2/V1密码
|
// 兼容V2密码,升级后存储格式为: md5:$HASH:$SALT
|
||||||
|
if len(passwordStore) == 3 {
|
||||||
|
if passwordStore[0] != "md5" {
|
||||||
|
return false, errors.New("Unknown password type")
|
||||||
|
}
|
||||||
|
hash := md5.New()
|
||||||
|
_, err := hash.Write([]byte(passwordStore[2] + password))
|
||||||
|
bs := hex.EncodeToString(hash.Sum(nil))
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
return bs == passwordStore[1], nil
|
||||||
|
}
|
||||||
|
|
||||||
//计算 Salt 和密码组合的SHA1摘要
|
//计算 Salt 和密码组合的SHA1摘要
|
||||||
hash := sha1.New()
|
hash := sha1.New()
|
||||||
_, err := hash.Write([]byte(password + passwordStore[0]))
|
_, err := hash.Write([]byte(password + passwordStore[0]))
|
||||||
|
|
|
@ -144,6 +144,27 @@ func TestUser_CheckPassword(t *testing.T) {
|
||||||
asserts.Error(err)
|
asserts.Error(err)
|
||||||
asserts.False(res)
|
asserts.False(res)
|
||||||
|
|
||||||
|
// 未知密码类型
|
||||||
|
user = User{}
|
||||||
|
user.Password = "1:2:3"
|
||||||
|
res, err = user.CheckPassword("Cause Sega does what nintendon't")
|
||||||
|
asserts.Error(err)
|
||||||
|
asserts.False(res)
|
||||||
|
|
||||||
|
// V2密码,错误
|
||||||
|
user = User{}
|
||||||
|
user.Password = "md5:2:3"
|
||||||
|
res, err = user.CheckPassword("Cause Sega does what nintendon't")
|
||||||
|
asserts.NoError(err)
|
||||||
|
asserts.False(res)
|
||||||
|
|
||||||
|
// V2密码,正确
|
||||||
|
user = User{}
|
||||||
|
user.Password = "md5:d8446059f8846a2c111a7f53515665fb:sdshare"
|
||||||
|
res, err = user.CheckPassword("admin")
|
||||||
|
asserts.NoError(err)
|
||||||
|
asserts.True(res)
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestNewUser(t *testing.T) {
|
func TestNewUser(t *testing.T) {
|
||||||
|
|
Loading…
Add table
Reference in a new issue