...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package pkcs8
23
24 import (
25 "crypto"
26 "crypto/ecdsa"
27 "crypto/rsa"
28 "crypto/x509"
29 "crypto/x509/pkix"
30 "encoding/asn1"
31 "errors"
32
33 "github.com/sassoftware/relic/lib/x509tools"
34 )
35
36 type privateKeyInfo struct {
37 Version int
38 PrivateKeyAlgorithm pkix.AlgorithmIdentifier
39 PrivateKey []byte
40 }
41
42
43 func MarshalPKCS8PrivateKey(priv crypto.PrivateKey) ([]byte, error) {
44 switch pkey := priv.(type) {
45 case *rsa.PrivateKey:
46 return asn1.Marshal(privateKeyInfo{
47 Version: 0,
48 PrivateKeyAlgorithm: pkix.AlgorithmIdentifier{
49 Algorithm: x509tools.OidPublicKeyRSA,
50 Parameters: asn1.NullRawValue,
51 },
52 PrivateKey: x509.MarshalPKCS1PrivateKey(pkey),
53 })
54 case *ecdsa.PrivateKey:
55 curve, err := x509tools.CurveByCurve(pkey.Curve)
56 if err != nil {
57 return nil, err
58 }
59 eckey, err := x509.MarshalECPrivateKey(pkey)
60 if err != nil {
61 return nil, err
62 }
63 return asn1.Marshal(privateKeyInfo{
64 Version: 0,
65 PrivateKeyAlgorithm: pkix.AlgorithmIdentifier{
66 Algorithm: x509tools.OidPublicKeyECDSA,
67 Parameters: asn1.RawValue{FullBytes: curve.ToDer()},
68 },
69 PrivateKey: eckey,
70 })
71 default:
72 return nil, errors.New("unsupported key type")
73 }
74 }
75
View as plain text