/
crypto_util.go
105 lines (87 loc) · 2.45 KB
/
crypto_util.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
package util
import (
"crypto/ecdsa"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
)
// ECDSA parsing errors.
var (
ErrorKeyMustBePEMEncoded = errors.New("key must be pem encoded")
ErrorNotECPublicKey = errors.New("Key is not a valid ECDSA public key")
ErrorNotECPrivateKey = errors.New("Key is not a valid ECDSA private key")
ErrorNotRSAPrivateKey = errors.New("Key is not a valid RSA private key")
ErrorNotRSAPublicKey = errors.New("Key is not a valid RSA public key")
)
// ParseECPrivateKeyFromPEM will parse a PEM encoded EC Private
// Key Structure.
func ParseECPrivateKeyFromPEM(key []byte) (*ecdsa.PrivateKey, error) {
block, _ := pem.Decode(key)
if block == nil {
return nil, ErrorKeyMustBePEMEncoded
}
// Parse the key
if parsedKey, err := x509.ParseECPrivateKey(block.Bytes); err == nil {
return parsedKey, nil
} else {
Debug(err)
}
return nil, ErrorNotECPrivateKey
}
// ParseECPublicKeyFromPEM will parse a PEM encoded PKCS1 or PKCS8 public key
func ParseECPublicKeyFromPEM(key []byte) (*ecdsa.PublicKey, error) {
block, _ := pem.Decode(key)
if block == nil {
return nil, ErrorKeyMustBePEMEncoded
}
parsedKey, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, err
}
parsedKey = cert.PublicKey
}
if pkey, ok := parsedKey.(*ecdsa.PublicKey); ok {
return pkey, nil
}
return nil, ErrorNotECPublicKey
}
// Parse PEM encoded PKCS1 or PKCS8 private key
func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error) {
block, _ := pem.Decode(key)
if block == nil {
return nil, ErrorKeyMustBePEMEncoded
}
pkey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
if parsedKey, err := x509.ParsePKCS8PrivateKey(block.Bytes); err != nil {
var ok bool
if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok {
return nil, ErrorNotRSAPrivateKey
}
}
}
return pkey, nil
}
// Parse PEM encoded PKCS1 or PKCS8 public key
func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) {
block, _ := pem.Decode(key)
if block == nil {
return nil, ErrorKeyMustBePEMEncoded
}
// Parse the key
parsedKey, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
if cert, err := x509.ParseCertificate(block.Bytes); err == nil {
parsedKey = cert.PublicKey
} else {
return nil, err
}
}
if pkey, ok := parsedKey.(*rsa.PublicKey); ok {
return pkey, nil
}
return nil, ErrorNotRSAPublicKey
}