-
Notifications
You must be signed in to change notification settings - Fork 0
/
options.go
78 lines (72 loc) · 1.75 KB
/
options.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
72
73
74
75
76
77
78
package token
import (
"crypto/rsa"
"fmt"
"github.com/dgrijalva/jwt-go"
"github.com/goharbor/harbor/src/common/utils/log"
"github.com/goharbor/harbor/src/core/config"
"io/ioutil"
"time"
)
const (
ttl = 60 * time.Minute
issuer = "harbor-token-issuer"
signedMethod = "RS256"
)
// Options ...
type Options struct {
SignMethod jwt.SigningMethod
PublicKey []byte
PrivateKey []byte
TTL time.Duration
Issuer string
}
// DefaultOptions ...
func DefaultOptions() *Options {
privateKeyFile := config.TokenPrivateKeyPath()
privateKey, err := ioutil.ReadFile(privateKeyFile)
if err != nil {
log.Errorf(fmt.Sprintf("failed to read private key %v", err))
return nil
}
opt := &Options{
SignMethod: jwt.GetSigningMethod(signedMethod),
PrivateKey: privateKey,
Issuer: issuer,
TTL: ttl,
}
return opt
}
// GetKey ...
func (o *Options) GetKey() (interface{}, error) {
var err error
var privateKey *rsa.PrivateKey
var publicKey *rsa.PublicKey
switch o.SignMethod.(type) {
case *jwt.SigningMethodRSA, *jwt.SigningMethodRSAPSS:
if len(o.PrivateKey) > 0 {
privateKey, err = jwt.ParseRSAPrivateKeyFromPEM(o.PrivateKey)
if err != nil {
return nil, err
}
}
if len(o.PublicKey) > 0 {
publicKey, err = jwt.ParseRSAPublicKeyFromPEM(o.PublicKey)
if err != nil {
return nil, err
}
}
if privateKey == nil {
if publicKey != nil {
return publicKey, nil
}
return nil, fmt.Errorf("key is provided")
}
if publicKey != nil && publicKey.E != privateKey.E && publicKey.N.Cmp(privateKey.N) != 0 {
return nil, fmt.Errorf("the public key and private key are not match")
}
return privateKey, nil
default:
return nil, fmt.Errorf(fmt.Sprintf("unsupported sign method, %s", o.SignMethod))
}
}