forked from ebhomengo/niki
1
0
Fork 0
niki/vendor/github.com/golang-jwt/jwt/ecdsa_utils.go

107 lines
1.5 KiB
Go
Raw Normal View History

2024-02-18 10:42:21 +00:00
package jwt
import (
"crypto/ecdsa"
"crypto/x509"
"encoding/pem"
"errors"
)
var (
ErrNotECPublicKey = errors.New("Key is not a valid ECDSA public key")
2024-02-18 10:42:21 +00:00
ErrNotECPrivateKey = errors.New("Key is not a valid ECDSA private key")
)
// Parse PEM encoded Elliptic Curve Private Key Structure
2024-02-18 10:42:21 +00:00
func ParseECPrivateKeyFromPEM(key []byte) (*ecdsa.PrivateKey, error) {
2024-02-18 10:42:21 +00:00
var err error
// Parse PEM block
2024-02-18 10:42:21 +00:00
var block *pem.Block
2024-02-18 10:42:21 +00:00
if block, _ = pem.Decode(key); block == nil {
2024-02-18 10:42:21 +00:00
return nil, ErrKeyMustBePEMEncoded
2024-02-18 10:42:21 +00:00
}
// Parse the key
2024-02-18 10:42:21 +00:00
var parsedKey interface{}
2024-02-18 10:42:21 +00:00
if parsedKey, err = x509.ParseECPrivateKey(block.Bytes); err != nil {
2024-02-18 10:42:21 +00:00
if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil {
2024-02-18 10:42:21 +00:00
return nil, err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
var pkey *ecdsa.PrivateKey
2024-02-18 10:42:21 +00:00
var ok bool
2024-02-18 10:42:21 +00:00
if pkey, ok = parsedKey.(*ecdsa.PrivateKey); !ok {
2024-02-18 10:42:21 +00:00
return nil, ErrNotECPrivateKey
2024-02-18 10:42:21 +00:00
}
return pkey, nil
2024-02-18 10:42:21 +00:00
}
// Parse PEM encoded PKCS1 or PKCS8 public key
2024-02-18 10:42:21 +00:00
func ParseECPublicKeyFromPEM(key []byte) (*ecdsa.PublicKey, error) {
2024-02-18 10:42:21 +00:00
var err error
// Parse PEM block
2024-02-18 10:42:21 +00:00
var block *pem.Block
2024-02-18 10:42:21 +00:00
if block, _ = pem.Decode(key); block == nil {
2024-02-18 10:42:21 +00:00
return nil, ErrKeyMustBePEMEncoded
2024-02-18 10:42:21 +00:00
}
// Parse the key
2024-02-18 10:42:21 +00:00
var parsedKey interface{}
2024-02-18 10:42:21 +00:00
if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil {
2024-02-18 10:42:21 +00:00
if cert, err := x509.ParseCertificate(block.Bytes); err == nil {
2024-02-18 10:42:21 +00:00
parsedKey = cert.PublicKey
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
return nil, err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
var pkey *ecdsa.PublicKey
2024-02-18 10:42:21 +00:00
var ok bool
2024-02-18 10:42:21 +00:00
if pkey, ok = parsedKey.(*ecdsa.PublicKey); !ok {
2024-02-18 10:42:21 +00:00
return nil, ErrNotECPublicKey
2024-02-18 10:42:21 +00:00
}
return pkey, nil
2024-02-18 10:42:21 +00:00
}