derhelpers.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // +build go1.13
  2. // Package derhelpers implements common functionality
  3. // on DER encoded data
  4. package derhelpers
  5. import (
  6. "crypto"
  7. "crypto/ecdsa"
  8. "crypto/ed25519"
  9. "crypto/rsa"
  10. "crypto/x509"
  11. cferr "github.com/cloudflare/cfssl/errors"
  12. )
  13. // ParsePrivateKeyDER parses a PKCS #1, PKCS #8, ECDSA, or Ed25519 DER-encoded
  14. // private key. The key must not be in PEM format.
  15. func ParsePrivateKeyDER(keyDER []byte) (key crypto.Signer, err error) {
  16. generalKey, err := x509.ParsePKCS8PrivateKey(keyDER)
  17. if err != nil {
  18. generalKey, err = x509.ParsePKCS1PrivateKey(keyDER)
  19. if err != nil {
  20. generalKey, err = x509.ParseECPrivateKey(keyDER)
  21. if err != nil {
  22. generalKey, err = ParseEd25519PrivateKey(keyDER)
  23. if err != nil {
  24. // We don't include the actual error into
  25. // the final error. The reason might be
  26. // we don't want to leak any info about
  27. // the private key.
  28. return nil, cferr.New(cferr.PrivateKeyError,
  29. cferr.ParseFailed)
  30. }
  31. }
  32. }
  33. }
  34. switch generalKey.(type) {
  35. case *rsa.PrivateKey:
  36. return generalKey.(*rsa.PrivateKey), nil
  37. case *ecdsa.PrivateKey:
  38. return generalKey.(*ecdsa.PrivateKey), nil
  39. case ed25519.PrivateKey:
  40. return generalKey.(ed25519.PrivateKey), nil
  41. }
  42. // should never reach here
  43. return nil, cferr.New(cferr.PrivateKeyError, cferr.ParseFailed)
  44. }