forked from sassoftware/relic
/
pkcs8.go
74 lines (69 loc) · 2.03 KB
/
pkcs8.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
//
// Copyright (c) SAS Institute Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// PKCS#8 is a specification for encoding private keys into an ASN.1 structure.
// See RFC 5208
//
// The Go standard library implements parsing PKCS#8 keys but does not support
// marshalling them; this module provides that function.
package pkcs8
import (
"crypto"
"crypto/ecdsa"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"errors"
"github.com/sassoftware/relic/lib/x509tools"
)
type privateKeyInfo struct {
Version int
PrivateKeyAlgorithm pkix.AlgorithmIdentifier
PrivateKey []byte
}
// Marshal a RSA or ECDSA private key as an unencrypted PKCS#8 blob
func MarshalPKCS8PrivateKey(priv crypto.PrivateKey) ([]byte, error) {
switch pkey := priv.(type) {
case *rsa.PrivateKey:
return asn1.Marshal(privateKeyInfo{
Version: 0,
PrivateKeyAlgorithm: pkix.AlgorithmIdentifier{
Algorithm: x509tools.OidPublicKeyRSA,
Parameters: asn1.NullRawValue,
},
PrivateKey: x509.MarshalPKCS1PrivateKey(pkey),
})
case *ecdsa.PrivateKey:
curve, err := x509tools.CurveByCurve(pkey.Curve)
if err != nil {
return nil, err
}
eckey, err := x509.MarshalECPrivateKey(pkey)
if err != nil {
return nil, err
}
return asn1.Marshal(privateKeyInfo{
Version: 0,
PrivateKeyAlgorithm: pkix.AlgorithmIdentifier{
Algorithm: x509tools.OidPublicKeyECDSA,
Parameters: asn1.RawValue{FullBytes: curve.ToDer()},
},
PrivateKey: eckey,
})
default:
return nil, errors.New("unsupported key type")
}
}