-
Notifications
You must be signed in to change notification settings - Fork 1
/
pkix.go
104 lines (94 loc) · 2.1 KB
/
pkix.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
94
95
96
97
98
99
100
101
102
103
104
package keyremix
import (
"crypto/ecdsa"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
)
type pkix struct {
Pem bool
}
func (p *pkix) Serialize(key interface{}, args map[string]string) (output []byte, err error) {
if _, ok := args["password"]; ok {
err = ErrNotImplemented
return
}
var name string
switch k := key.(type) {
case *rsa.PublicKey:
output, err = x509.MarshalPKIXPublicKey(k)
name = "PUBLIC KEY"
case *ecdsa.PublicKey:
output, err = x509.MarshalPKIXPublicKey(k)
name = "PUBLIC KEY"
default:
err = ErrUnsuitableKeyType
return
}
if p.Pem {
b := pem.Block{Type: name, Headers: nil, Bytes: output}
output = pem.EncodeToMemory(&b)
}
return
}
func (p *pkix) Deserialize(input []byte, args map[string]string) (key interface{}, rest []byte, err error) {
if p.Pem {
var b *pem.Block
b, rest = pem.Decode(input)
input = b.Bytes
switch b.Type {
case "PUBLIC KEY":
key, err = x509.ParsePKIXPublicKey(input)
default:
err = ErrUnsuitableKeyType
}
} else {
key, err = x509.ParsePKIXPublicKey(input)
}
return
}
func (p *pkix) Recognize(input []byte, args map[string]string) (fit Fit, err error) {
if p.Pem {
b, _ := pem.Decode(input)
if b == nil {
fit = DoesNotFit
return
}
switch b.Type {
case "PUBLIC KEY":
fit = UnambiguousFit
return
default:
fit = DoesNotFit
return
}
} else {
// TODO we could do a simple 'is it like DER' test.
fit = AmbiguousFit
}
return
}
func (p *pkix) Name() string {
if p.Pem {
return "pkix"
}
return "pkixder"
}
func (p *pkix) Description() string {
if p.Pem {
return "RFC3279/PKIX format (public keys only)"
}
return "RFC3279/PKIX format (raw DER)"
}
// PkixPem is PKIX format, with PEM encoding.
//
// Only RSA and ECDSA public keys are supported. See https://tools.ietf.org/html/rfc3279 and https://tools.ietf.org/html/rfc7468.
var PkixPem = &pkix{Pem: true}
// PkixDer is PKIX format, with DER encoding.
//
// Only RSA and ECDSA public keys are supported. See https://tools.ietf.org/html/rfc3279.
var PkixDer = &pkix{Pem: false}
func init() {
registerKeyFormat(PkixPem)
registerKeyFormat(PkixDer)
}