Skip to content

Commit

Permalink
使用动态盐值加密密码
Browse files Browse the repository at this point in the history
  • Loading branch information
wsczx committed Oct 26, 2024
1 parent 34e555c commit ff9d92a
Showing 1 changed file with 61 additions and 16 deletions.
77 changes: 61 additions & 16 deletions server/dbdata/user.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
package dbdata

import (
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"strings"
"sync"
"time"

"github.com/bjdgyc/anylink/base"
"github.com/bjdgyc/anylink/pkg/utils"
"github.com/xlzd/gotp"
"golang.org/x/crypto/scrypt"
Expand Down Expand Up @@ -126,7 +129,6 @@ func checkLocalUser(name, pwd, group string) error {
// return fmt.Errorf("%s %s", name, "动态码错误")
// }
// }

// 判断用户密码
if !VerifyPassword(pwd, v.PinCode) {
return fmt.Errorf("%s %s", name, "密码错误")
Expand Down Expand Up @@ -193,29 +195,72 @@ func CheckOtp(name, otp, secret string) bool {
return verify
}

// 插入数据库前加密 Password
func (u *User) BeforeInsert() {
u.PinCode = ScryptPassword(u.PinCode)
// 插入数据库前加密密码
func (u *User) BeforeInsert() error {
hashedPassword, err := ScryptPassword(u.PinCode)
if err != nil {
base.Error(err)
return err
}
u.PinCode = hashedPassword
return nil
}

// 更新数据库前加密 Password
func (u *User) BeforeUpdate() {
if len(u.PinCode) != 44 {
u.PinCode = ScryptPassword(u.PinCode)
// 更新数据库前加密密码
func (u *User) BeforeUpdate() error {
if len(u.PinCode) != 57 {
hashedPassword, err := ScryptPassword(u.PinCode)
if err != nil {
base.Error(err)
return err
}
u.PinCode = hashedPassword
}
return nil
}

// 加密
func ScryptPassword(passwd string) string {
salt := []byte{0xc8, 0x28, 0xf2, 0x58, 0xa7, 0x6a, 0xad, 0x7b}
hashPasswd, _ := scrypt.Key([]byte(passwd), salt, 1<<16, 8, 1, 32)
return base64.StdEncoding.EncodeToString(hashPasswd)
// 加密密码
func ScryptPassword(passwd string) (string, error) {
salt := make([]byte, 8)
if _, err := rand.Read(salt); err != nil {
return "", err
}

hashPasswd, err := scrypt.Key([]byte(passwd), salt, 1<<16, 8, 1, 32)
if err != nil {
return "", err
}

encodedSalt := base64.StdEncoding.EncodeToString(salt)
encodedHash := base64.StdEncoding.EncodeToString(hashPasswd)

return encodedSalt + "&" + encodedHash, nil
}

// 验证
// 验证密码
func VerifyPassword(password, hashPassword string) bool {
if len(hashPassword) != 44 {
// 老用户使用明文验证
if len(hashPassword) != 57 {
return password == hashPassword
}
return ScryptPassword(password) == hashPassword

// 分割盐值和哈希值
encodepwds := strings.SplitN(hashPassword, "&", 2)
if len(encodepwds) != 2 {
return false
}

// 解码盐值
salt, err := base64.StdEncoding.DecodeString(encodepwds[0])
if err != nil {
return false
}

// 计算新的哈希值
newHash, err := scrypt.Key([]byte(password), salt, 1<<16, 8, 1, 32)
if err != nil {
return false
}

return base64.StdEncoding.EncodeToString(newHash) == encodepwds[1]
}

0 comments on commit ff9d92a

Please sign in to comment.