ecdsa_utils.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package jwt
  2. import (
  3. "crypto/ecdsa"
  4. "crypto/x509"
  5. "encoding/pem"
  6. "errors"
  7. )
  8. var (
  9. ErrNotECPublicKey = errors.New("Key is not a valid ECDSA public key")
  10. ErrNotECPrivateKey = errors.New("Key is not a valid ECDSA private key")
  11. )
  12. // Parse PEM encoded Elliptic Curve Private Key Structure
  13. func ParseECPrivateKeyFromPEM(key []byte) (*ecdsa.PrivateKey, error) {
  14. var err error
  15. // Parse PEM block
  16. var block *pem.Block
  17. if block, _ = pem.Decode(key); block == nil {
  18. return nil, ErrKeyMustBePEMEncoded
  19. }
  20. // Parse the key
  21. var parsedKey interface{}
  22. if parsedKey, err = x509.ParseECPrivateKey(block.Bytes); err != nil {
  23. return nil, err
  24. }
  25. var pkey *ecdsa.PrivateKey
  26. var ok bool
  27. if pkey, ok = parsedKey.(*ecdsa.PrivateKey); !ok {
  28. return nil, ErrNotECPrivateKey
  29. }
  30. return pkey, nil
  31. }
  32. // Parse PEM encoded PKCS1 or PKCS8 public key
  33. func ParseECPublicKeyFromPEM(key []byte) (*ecdsa.PublicKey, error) {
  34. var err error
  35. // Parse PEM block
  36. var block *pem.Block
  37. if block, _ = pem.Decode(key); block == nil {
  38. return nil, ErrKeyMustBePEMEncoded
  39. }
  40. // Parse the key
  41. var parsedKey interface{}
  42. if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil {
  43. if cert, err := x509.ParseCertificate(block.Bytes); err == nil {
  44. parsedKey = cert.PublicKey
  45. } else {
  46. return nil, err
  47. }
  48. }
  49. var pkey *ecdsa.PublicKey
  50. var ok bool
  51. if pkey, ok = parsedKey.(*ecdsa.PublicKey); !ok {
  52. return nil, ErrNotECPublicKey
  53. }
  54. return pkey, nil
  55. }