@marcel91200 / caddy Mirror · read-only
Fork 0

Fast and extensible multi-platform HTTP/1-2-3 web server with automatic HTTPS

Mirrored from https://github.com/Slazee/caddy.git

Synced Nov 11, 01:00 UTC

master
go 83 lines 2.25 KB
Raw
1 // Copyright 2015 Matthew Holt and The Caddy Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package caddyauth
16
17 import (
18 "errors"
19
20 "golang.org/x/crypto/bcrypt"
21
22 "github.com/caddyserver/caddy/v2"
23 )
24
25 func init() {
26 caddy.RegisterModule(BcryptHash{})
27 }
28
29 // defaultBcryptCost cost 14 strikes a solid balance between security, usability, and hardware performance
30 const (
31 bcryptName = "bcrypt"
32 defaultBcryptCost = 14
33 )
34
35 // BcryptHash implements the bcrypt hash.
36 type BcryptHash struct {
37 // cost is the bcrypt hashing difficulty factor (work factor).
38 // Higher values increase computation time and security.
39 cost int
40 }
41
42 // CaddyModule returns the Caddy module information.
43 func (BcryptHash) CaddyModule() caddy.ModuleInfo {
44 return caddy.ModuleInfo{
45 ID: "http.authentication.hashes.bcrypt",
46 New: func() caddy.Module { return new(BcryptHash) },
47 }
48 }
49
50 // Compare compares passwords.
51 func (BcryptHash) Compare(hashed, plaintext []byte) (bool, error) {
52 err := bcrypt.CompareHashAndPassword(hashed, plaintext)
53 if errors.Is(err, bcrypt.ErrMismatchedHashAndPassword) {
54 return false, nil
55 }
56 if err != nil {
57 return false, err
58 }
59 return true, nil
60 }
61
62 // Hash hashes plaintext using a random salt.
63 func (b BcryptHash) Hash(plaintext []byte) ([]byte, error) {
64 cost := b.cost
65 if cost < bcrypt.MinCost || cost > bcrypt.MaxCost {
66 cost = defaultBcryptCost
67 }
68
69 return bcrypt.GenerateFromPassword(plaintext, cost)
70 }
71
72 // FakeHash returns a fake hash.
73 func (BcryptHash) FakeHash() []byte {
74 // hashed with the following command:
75 // caddy hash-password --plaintext "antitiming" --algorithm "bcrypt"
76 return []byte("$2a$14$X3ulqf/iGxnf1k6oMZ.RZeJUoqI9PX2PM4rS5lkIKJXduLGXGPrt6")
77 }
78
79 // Interface guards
80 var (
81 _ Comparer = (*BcryptHash)(nil)
82 _ Hasher = (*BcryptHash)(nil)
83 )