2019-10-07 08:14:47 -06:00
|
|
|
// Copyright (c) Mainflux
|
2018-08-26 13:15:48 +02:00
|
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
|
2018-05-10 23:53:25 +02:00
|
|
|
// Package bcrypt provides a hasher implementation utilising bcrypt.
|
2017-09-23 01:03:27 +02:00
|
|
|
package bcrypt
|
|
|
|
|
|
|
|
import (
|
2018-05-10 23:53:25 +02:00
|
|
|
"github.com/mainflux/mainflux/users"
|
2017-09-23 01:03:27 +02:00
|
|
|
"golang.org/x/crypto/bcrypt"
|
|
|
|
)
|
|
|
|
|
|
|
|
const cost int = 10
|
|
|
|
|
2018-05-10 23:53:25 +02:00
|
|
|
var _ users.Hasher = (*bcryptHasher)(nil)
|
2017-09-23 01:03:27 +02:00
|
|
|
|
|
|
|
type bcryptHasher struct{}
|
|
|
|
|
2018-03-11 18:06:01 +01:00
|
|
|
// New instantiates a bcrypt-based hasher implementation.
|
2018-05-10 23:53:25 +02:00
|
|
|
func New() users.Hasher {
|
2017-09-23 01:03:27 +02:00
|
|
|
return &bcryptHasher{}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (bh *bcryptHasher) Hash(pwd string) (string, error) {
|
|
|
|
hash, err := bcrypt.GenerateFromPassword([]byte(pwd), cost)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
return string(hash), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (bh *bcryptHasher) Compare(plain, hashed string) error {
|
|
|
|
return bcrypt.CompareHashAndPassword([]byte(hashed), []byte(plain))
|
|
|
|
}
|