douou0977 2015-06-23 10:31
浏览 115
已采纳

比较Golang中的错误

I'm writing a basic password authentication system in golang.
I use bcrypt to hash the password and save the hash in a database.
Here's the function to retrieve an authenticated account from the database.

func FindAccount(db *gorp.DbMap, email, password string) (*Account, error) {
    account, err := FindByEmail(db, email)
    if err != nil {
        return nil, err
    }
    if account == nil {
        return nil, nil
    }
    if err := bcrypt.CompareHashAndPassword([]byte(account.HashedPassword), []byte(password)); err != nil {
        return nil, err
    }
    return account, nil
}

And the caller:

account, err := FindAccount(db, email, password)
if err != nil {
    if err == bcrypt.ErrMismatchedHashAndPassword {
        log.Printf("Why doesn't this condition match?")
        return nil, EmailPasswordInvalidError{}
    }

    log.Printf("bcrypt.Err: %p, %#v", bcrypt.ErrMismatchedHashAndPassword, bcrypt.ErrMismatchedHashAndPassword)
    log.Printf("err       : %p, %#v", err, err)
    return nil, err
}

And when I use this code and provide invalid email and password, here's what happens:

sessions.go:51: bcrypt.Err: 0xc2080290b0, &errors.errorString{s:"crypto/bcrypt: hashedPassword is not the hash of the given password"}
sessions.go:52: err       : 0xc2080291e0, &errors.errorString{s:"crypto/bcrypt: hashedPassword is not the hash of the given password"}

Why is the pointer address different? Can't we just compare errors?

  • 写回答

1条回答 默认 最新

  • dongtaihui5131 2015-06-23 10:57
    关注

    I had two bcrypt packages imported.. The file which has FindAccount imported "code.google.com/p/go.crypto/bcrypt", and the caller imported "golang.org/x/crypto/bcrypt".

    Thus there were multiple

    var ErrMismatchedHashAndPassword = errors.New("crypto/bcrypt: hashedPassword is not the hash of the given password")
    

    with different pointers.

    Replacing all "code.google.com/p/go.crypto/bcrypt" with "golang.org/x/crypto/bcrypt" fixed the issue.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来