-
Notifications
You must be signed in to change notification settings - Fork 974
/
Copy pathhasher_bcrypt.go
71 lines (54 loc) · 1.61 KB
/
hasher_bcrypt.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package hash
import (
"context"
"fmt"
"github.com/ory/kratos/text"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"github.com/ory/kratos/schema"
"golang.org/x/crypto/bcrypt"
"github.com/ory/kratos/driver/config"
)
type Bcrypt struct {
c BcryptConfiguration
}
type BcryptConfiguration interface {
config.Provider
}
func NewHasherBcrypt(c BcryptConfiguration) *Bcrypt {
return &Bcrypt{c: c}
}
func (h *Bcrypt) Generate(ctx context.Context, password []byte) ([]byte, error) {
conf := h.c.Config().HasherBcrypt(ctx)
_, span := otel.GetTracerProvider().Tracer(tracingComponent).Start(ctx, "hash.Generate", trace.WithAttributes(
attribute.String("hash.type", "bcrypt"),
attribute.String("hash.config", fmt.Sprintf("%#v", conf)),
))
defer span.End()
if err := validateBcryptPasswordLength(password); err != nil {
return nil, err
}
hash, err := bcrypt.GenerateFromPassword(password, int(conf.Cost))
if err != nil {
return nil, err
}
return hash, nil
}
func validateBcryptPasswordLength(password []byte) error {
// Bcrypt truncates the password to the first 72 bytes, following the OpenBSD implementation,
// so if password is longer than 72 bytes, function returns an error
// See https://en.wikipedia.org/wiki/Bcrypt#User_input
if len(password) > 72 {
return schema.NewPasswordPolicyViolationError(
"#/password",
text.NewErrorValidationPasswordMaxLength(72, len(password)),
)
}
return nil
}
func (h *Bcrypt) Understands(hash []byte) bool {
return IsBcryptHash(hash)
}