...

Source file src/github.com/sassoftware/relic/lib/pkcs8/pkcs8.go

Documentation: github.com/sassoftware/relic/lib/pkcs8

     1  //
     2  // Copyright (c) SAS Institute Inc.
     3  //
     4  // Licensed under the Apache License, Version 2.0 (the "License");
     5  // you may not use this file except in compliance with the License.
     6  // You may obtain a copy of the License at
     7  //
     8  //     http://www.apache.org/licenses/LICENSE-2.0
     9  //
    10  // Unless required by applicable law or agreed to in writing, software
    11  // distributed under the License is distributed on an "AS IS" BASIS,
    12  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  // See the License for the specific language governing permissions and
    14  // limitations under the License.
    15  //
    16  
    17  // PKCS#8 is a specification for encoding private keys into an ASN.1 structure.
    18  // See RFC 5208
    19  //
    20  // The Go standard library implements parsing PKCS#8 keys but does not support
    21  // marshalling them; this module provides that function.
    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  // Marshal a RSA or ECDSA private key as an unencrypted PKCS#8 blob
    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