-
Notifications
You must be signed in to change notification settings - Fork 401
/
auth.go
61 lines (48 loc) · 1.3 KB
/
auth.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
// Copyright (C) 2020 Storj Labs, Inc.
// See LICENSE for copying information.
package multinodeauth
import (
"bytes"
"crypto/rand"
"encoding/base64"
"github.com/zeebo/errs"
)
// Secret crypto random 32 bytes array for multinode auth.
type Secret [32]byte
// NewSecret creates new multinode auth secret.
func NewSecret() (Secret, error) {
var b [32]byte
_, err := rand.Read(b[:])
if err != nil {
return b, errs.New("error creating multinode auth secret")
}
return b, nil
}
// String implements Stringer.
func (secret Secret) String() string {
return base64.URLEncoding.EncodeToString(secret[:])
}
// IsZero returns if secret is not set.
func (secret Secret) IsZero() bool {
var zero Secret
// this doesn't need to be constant-time, because we're explicitly testing
// against a hardcoded, well-known value
return bytes.Equal(secret[:], zero[:])
}
// SecretFromBase64 creates new secret from base64 string.
func SecretFromBase64(s string) (Secret, error) {
b, err := base64.URLEncoding.DecodeString(s)
if err != nil {
return Secret{}, err
}
return SecretFromBytes(b)
}
// SecretFromBytes creates secret from bytes slice.
func SecretFromBytes(b []byte) (Secret, error) {
if len(b) != 32 {
return Secret{}, errs.New("invalid secret")
}
var secret Secret
copy(secret[:], b)
return secret, nil
}