pkcs8.go 1.7 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. // START CT CHANGES
  7. "github.com/google/certificate-transparency/go/asn1"
  8. "github.com/google/certificate-transparency/go/x509/pkix"
  9. // END CT CHANGES
  10. "errors"
  11. "fmt"
  12. )
  13. // pkcs8 reflects an ASN.1, PKCS#8 PrivateKey. See
  14. // ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-8/pkcs-8v1_2.asn
  15. // and RFC5208.
  16. type pkcs8 struct {
  17. Version int
  18. Algo pkix.AlgorithmIdentifier
  19. PrivateKey []byte
  20. // optional attributes omitted.
  21. }
  22. // ParsePKCS8PrivateKey parses an unencrypted, PKCS#8 private key. See
  23. // http://www.rsa.com/rsalabs/node.asp?id=2130 and RFC5208.
  24. func ParsePKCS8PrivateKey(der []byte) (key interface{}, err error) {
  25. var privKey pkcs8
  26. if _, err := asn1.Unmarshal(der, &privKey); err != nil {
  27. return nil, err
  28. }
  29. switch {
  30. case privKey.Algo.Algorithm.Equal(oidPublicKeyRSA):
  31. key, err = ParsePKCS1PrivateKey(privKey.PrivateKey)
  32. if err != nil {
  33. return nil, errors.New("x509: failed to parse RSA private key embedded in PKCS#8: " + err.Error())
  34. }
  35. return key, nil
  36. case privKey.Algo.Algorithm.Equal(oidPublicKeyECDSA):
  37. bytes := privKey.Algo.Parameters.FullBytes
  38. namedCurveOID := new(asn1.ObjectIdentifier)
  39. if _, err := asn1.Unmarshal(bytes, namedCurveOID); err != nil {
  40. namedCurveOID = nil
  41. }
  42. key, err = parseECPrivateKey(namedCurveOID, privKey.PrivateKey)
  43. if err != nil {
  44. return nil, errors.New("x509: failed to parse EC private key embedded in PKCS#8: " + err.Error())
  45. }
  46. return key, nil
  47. default:
  48. return nil, fmt.Errorf("x509: PKCS#8 wrapping contained private key with unknown algorithm: %v", privKey.Algo.Algorithm)
  49. }
  50. }