-
Notifications
You must be signed in to change notification settings - Fork 0
/
certificates.go
108 lines (76 loc) · 2.31 KB
/
certificates.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
108
package sigs
import (
"crypto"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"github.com/benpate/derp"
)
// EncodePrivatePEM converts a private key into a PEM string
func EncodePrivatePEM(privateKey *rsa.PrivateKey) string {
// Get ASN.1 DER format
privDER := x509.MarshalPKCS1PrivateKey(privateKey)
// pem.Block
privBlock := pem.Block{
Type: "RSA PRIVATE KEY",
Headers: nil,
Bytes: privDER,
}
// Private key in PEM format
privatePEM := pem.EncodeToMemory(&privBlock)
return string(privatePEM)
}
// EncodePublicPEM converts a public key into a PEM string
func EncodePublicPEM(privateKey *rsa.PrivateKey) string {
// Get ASN.1 DER format
publicDER := x509.MarshalPKCS1PublicKey(&privateKey.PublicKey)
// pem.Block
publicBlock := pem.Block{
Type: "RSA PUBLIC KEY",
Headers: nil,
Bytes: publicDER,
}
// Private key in PEM format
publicPEM := pem.EncodeToMemory(&publicBlock)
return string(publicPEM)
}
// DecodePrivatePEM converts a PEM string into a private key
func DecodePrivatePEM(pemString string) (crypto.PrivateKey, error) {
const location = "hannibal.sigs.DecodePrivatePEM"
block, _ := pem.Decode([]byte(pemString))
if block == nil {
return nil, derp.NewInternalError(location, "Block is nil", pemString)
}
switch block.Type {
case "RSA PRIVATE KEY":
result, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil, derp.Wrap(err, location, "Error parsing PKCS1 private key")
}
return result, nil
case "PRIVATE KEY":
result, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return nil, derp.Wrap(err, location, "Error parsing PKCS8 private key")
}
return result, nil
default:
return nil, derp.NewInternalError(location, "Invalid block type", block.Type)
}
}
// DecodePublicPEM converts a PEM string into a public key
func DecodePublicPEM(pemString string) (crypto.PublicKey, error) {
const location = "hannibal.sigs.DecodePublicPEM"
block, _ := pem.Decode([]byte(pemString))
if block == nil {
return nil, derp.NewInternalError(location, "Block is nil", pemString)
}
switch block.Type {
case "RSA PUBLIC KEY":
return x509.ParsePKCS1PublicKey(block.Bytes)
case "PUBLIC KEY":
return x509.ParsePKIXPublicKey(block.Bytes)
default:
return nil, derp.NewInternalError(location, "Invalid block type", block.Type)
}
}