-
Notifications
You must be signed in to change notification settings - Fork 26
/
purpose.go
84 lines (69 loc) · 2.15 KB
/
purpose.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
package key
import (
"bytes"
"fmt"
)
// Purpose is an enumerated type describing the reason a given
// key is being used. This type implements Parser.
//
// All Purpose values assume PEM-encoded keys. For other formats,
// a custom Parser decorator can be used. Purpose.RequiresPrivateKey()
// determines whether to parse the key as a private key.
type Purpose int
const (
// PurposeVerify refers to a key used to verify a signature. This is the zero-value
// for Purpose. These keys must be public keys encoded as PEM blocks.
PurposeVerify Purpose = Purpose(iota)
// PurposeSign refers to a key used to create a signature. These keys must be private,
// PEM-encoded keys.
PurposeSign
// PurposeEncrypt refers to a key used to encrypt data. These keys must be private,
// PEM-encoded keys.
PurposeEncrypt
// PurposeDecrypt refers to a key used to decrypt data. These keys must be public,
// PEM-encoded keys.
PurposeDecrypt
)
var (
purposeMarshal = map[Purpose]string{
PurposeSign: "sign",
PurposeVerify: "verify",
PurposeEncrypt: "encrypt",
PurposeDecrypt: "decrypt",
}
purposeUnmarshal = map[string]Purpose{
"sign": PurposeSign,
"verify": PurposeVerify,
"encrypt": PurposeEncrypt,
"decrypt": PurposeDecrypt,
}
)
// String returns a human-readable, string representation for a Purpose.
// Unrecognized purpose values are assumed to be PurposeVerify.
func (p Purpose) String() string {
if value, ok := purposeMarshal[p]; ok {
return value
}
return purposeMarshal[PurposeVerify]
}
func (p *Purpose) UnmarshalJSON(data []byte) error {
if data[0] == '"' {
if unmarshalValue, ok := purposeUnmarshal[string(data[1:len(data)-1])]; ok {
*p = unmarshalValue
return nil
}
}
return fmt.Errorf("Invalid key purpose: %s", data)
}
func (p Purpose) MarshalJSON() ([]byte, error) {
var buffer bytes.Buffer
buffer.WriteString("\"")
buffer.WriteString(p.String())
buffer.WriteString("\"")
return buffer.Bytes(), nil
}
// RequiresPrivateKey returns true if this purpose requires a private key,
// false if it requires a public key.
func (p Purpose) RequiresPrivateKey() bool {
return p == PurposeSign || p == PurposeEncrypt
}