pkcs8.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Copyright 2011 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package x509
  5. import (
  6. "errors"
  7. "fmt"
  8. "github.com/zmap/zcrypto/encoding/asn1"
  9. "github.com/zmap/zcrypto/x509/pkix"
  10. )
  11. // pkcs8 reflects an ASN.1, PKCS#8 PrivateKey. See
  12. // ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-8/pkcs-8v1_2.asn
  13. // and RFC 5208.
  14. type pkcs8 struct {
  15. Version int
  16. Algo pkix.AlgorithmIdentifier
  17. PrivateKey []byte
  18. // optional attributes omitted.
  19. }
  20. // ParsePKCS8PrivateKey parses an unencrypted, PKCS#8 private key.
  21. // See RFC 5208.
  22. func ParsePKCS8PrivateKey(der []byte) (key interface{}, err error) {
  23. var privKey pkcs8
  24. if _, err := asn1.Unmarshal(der, &privKey); err != nil {
  25. return nil, err
  26. }
  27. switch {
  28. case privKey.Algo.Algorithm.Equal(oidPublicKeyRSA):
  29. key, err = ParsePKCS1PrivateKey(privKey.PrivateKey)
  30. if err != nil {
  31. return nil, errors.New("x509: failed to parse RSA private key embedded in PKCS#8: " + err.Error())
  32. }
  33. return key, nil
  34. case privKey.Algo.Algorithm.Equal(oidPublicKeyECDSA):
  35. bytes := privKey.Algo.Parameters.FullBytes
  36. namedCurveOID := new(asn1.ObjectIdentifier)
  37. if _, err := asn1.Unmarshal(bytes, namedCurveOID); err != nil {
  38. namedCurveOID = nil
  39. }
  40. key, err = parseECPrivateKey(namedCurveOID, privKey.PrivateKey)
  41. if err != nil {
  42. return nil, errors.New("x509: failed to parse EC private key embedded in PKCS#8: " + err.Error())
  43. }
  44. return key, nil
  45. default:
  46. return nil, fmt.Errorf("x509: PKCS#8 wrapping contained private key with unknown algorithm: %v", privKey.Algo.Algorithm)
  47. }
  48. }