/
types.go
107 lines (85 loc) · 2.63 KB
/
types.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
105
106
107
package encoder
import (
"crypto/x509"
"encoding/pem"
"fmt"
"go.mozilla.org/pkcs7"
)
type KeyFileFormat int
const (
KeyFileFormatInvalid KeyFileFormat = iota
KeyFileFormatPKCS1RSAPrivateKey
KeyFileFormatPKCS1RSAPublicKey
KeyFileFormatPKCS7Message
KeyFileFormatPKCS8PrivateKey
KeyFileFormatPKIXPublicKey
KeyFileFormatECPrivateKey
KeyFileFormatECPublicKey
KeyFileFormatECParameters
KeyFileFormatCertificate
KeyFileFormatCertificateRequest
KeyFileFormatPEM
)
var keyFileFormatNameMap = map[KeyFileFormat]string{
KeyFileFormatInvalid: "INVALID",
KeyFileFormatPKCS1RSAPrivateKey: "RSAPrivateKey[PKCS1]",
KeyFileFormatPKCS1RSAPublicKey: "RSAPublicKey[PKCS1]",
KeyFileFormatPKCS7Message: "PKCS7Message",
KeyFileFormatPKCS8PrivateKey: "PrivateKey[PKCS8]",
KeyFileFormatPKIXPublicKey: "PublicKey[PKIX]",
KeyFileFormatECPrivateKey: "ECPrivateKey",
KeyFileFormatECPublicKey: "ECPublicKey",
KeyFileFormatECParameters: "ECParameters",
KeyFileFormatCertificate: "Certificate",
KeyFileFormatCertificateRequest: "CertificateRequest",
KeyFileFormatPEM: "PEM",
}
func (f KeyFileFormat) String() string {
name, known := keyFileFormatNameMap[f]
if known {
return name
}
return fmt.Sprintf("KeyFileFormat(%d)", int(f))
}
func canParseKey[T any](data []byte, loader func([]byte) (T, error)) bool {
_, err := loader(data)
return err == nil
}
func derDetect(data []byte) KeyFileFormat {
result := KeyFileFormatInvalid
if canParseKey(data, x509.ParsePKCS1PrivateKey) {
result = KeyFileFormatPKCS1RSAPrivateKey
} else if canParseKey(data, x509.ParsePKCS1PublicKey) {
result = KeyFileFormatPKCS1RSAPublicKey
} else if canParseKey(data, pkcs7.Parse) {
result = KeyFileFormatPKCS7Message
} else if canParseKey(data, x509.ParsePKCS8PrivateKey) {
result = KeyFileFormatPKCS8PrivateKey
} else if canParseKey(data, x509.ParsePKIXPublicKey) {
result = KeyFileFormatPKIXPublicKey
} else if canParseKey(data, x509.ParseECPrivateKey) {
result = KeyFileFormatECPrivateKey
} else if canParseKey(data, x509.ParseCertificate) {
result = KeyFileFormatCertificate
} else if canParseKey(data, x509.ParseCertificateRequest) {
result = KeyFileFormatCertificateRequest
}
return result
}
func TypeDetect(data []byte) []KeyFileFormat {
outTypes := make([]KeyFileFormat, 0)
block, rest := pem.Decode(data)
if block != nil {
keyType := derDetect(block.Bytes)
outTypes = append(outTypes,
KeyFileFormatPEM,
keyType,
)
if len(rest) > 0 {
outTypes = append(outTypes, TypeDetect(rest)...)
}
} else {
outTypes = append(outTypes, derDetect(data))
}
return outTypes
}