-
Notifications
You must be signed in to change notification settings - Fork 3
/
marshaller.go
49 lines (44 loc) · 1006 Bytes
/
marshaller.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
package pemparser
import (
"crypto"
"crypto/ecdsa"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"reflect"
)
func MarshalPrivateKey(priv crypto.PrivateKey) ([]byte, error) {
switch impl := priv.(type) {
case (*rsa.PrivateKey):
bs := pem.EncodeToMemory(&pem.Block{
Type: RSAPrivateKeyPemType,
Bytes: x509.MarshalPKCS1PrivateKey(impl),
})
return bs, nil
case (*ecdsa.PrivateKey):
kbs, err := x509.MarshalECPrivateKey(impl)
if err != nil {
return nil, err
}
bs := pem.EncodeToMemory(&pem.Block{
Type: ECPrivateKeyPemType,
Bytes: kbs,
})
return bs, nil
default:
return nil, fmt.Errorf("Couldn't marshal unknown private key type: %v", reflect.TypeOf(priv))
}
}
func MarshalCertificateDer(certDer []byte) []byte {
return pem.EncodeToMemory(&pem.Block{
Type: CertificatePemType,
Bytes: certDer,
})
}
func MarshalCertificateRequestDer(der []byte) []byte {
return pem.EncodeToMemory(&pem.Block{
Type: CertificateRequestPemType,
Bytes: der,
})
}