-
Notifications
You must be signed in to change notification settings - Fork 1
/
keyinfo.go
93 lines (86 loc) · 1.82 KB
/
keyinfo.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package certutil
import (
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rsa"
"github.com/go-jose/go-jose/v3"
"github.com/pkg/errors"
)
// KeyInfo provides information about the key
type KeyInfo struct {
KeySize int
Type string
IsPrivate bool
Hash crypto.Hash
Key interface{}
}
// NewKeyInfo returns *SignerInfo
func NewKeyInfo(k interface{}) (*KeyInfo, error) {
ki := &KeyInfo{Key: k}
var pubKey crypto.PublicKey
// find the Public
switch typ := k.(type) {
case *rsa.PrivateKey:
ki.KeySize = typ.N.BitLen()
ki.IsPrivate = true
ki.Type = "RSA"
ki.Hash = hashAlgo(typ.Public)
return ki, nil
case *ecdsa.PrivateKey:
ki.Type = "ECDSA"
ki.IsPrivate = true
ki.KeySize = typ.Curve.Params().BitSize
ki.Hash = hashAlgo(typ.Public)
return ki, nil
case crypto.Signer:
pubKey = typ.Public()
case crypto.Decrypter:
pubKey = typ.Public()
case *jose.JSONWebKey:
return NewKeyInfo(typ.Key)
default:
pubKey = k
}
switch typ := pubKey.(type) {
case *rsa.PublicKey:
ki.KeySize = typ.N.BitLen()
ki.Type = "RSA"
case *ecdsa.PublicKey:
ki.Type = "ECDSA"
ki.KeySize = typ.Curve.Params().BitSize
default:
return nil, errors.Errorf("key not supported: %T", typ)
}
ki.Hash = hashAlgo(pubKey)
return ki, nil
}
func hashAlgo(pub crypto.PublicKey) crypto.Hash {
switch pub := pub.(type) {
case *rsa.PublicKey:
keySize := pub.N.BitLen()
switch {
case keySize >= 4096:
return crypto.SHA512
case keySize >= 3072:
return crypto.SHA384
case keySize >= 2048:
return crypto.SHA256
default:
return crypto.SHA1
}
case *ecdsa.PublicKey:
switch pub.Curve {
case elliptic.P256():
return crypto.SHA256
case elliptic.P384():
return crypto.SHA384
case elliptic.P521():
return crypto.SHA512
default:
return crypto.SHA1
}
default:
return crypto.SHA1
}
}