derhelpers.go 1.2 KB

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