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

96 lines
1.4 KiB
Go
Raw Normal View History

2024-02-18 10:42:21 +00:00
package jwt
import (
"crypto"
"crypto/ed25519"
"crypto/x509"
"encoding/pem"
"errors"
)
var (
ErrNotEdPrivateKey = errors.New("key is not a valid Ed25519 private key")
ErrNotEdPublicKey = errors.New("key is not a valid Ed25519 public key")
2024-02-18 10:42:21 +00:00
)
// ParseEdPrivateKeyFromPEM parses a PEM-encoded Edwards curve private key
2024-02-18 10:42:21 +00:00
func ParseEdPrivateKeyFromPEM(key []byte) (crypto.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.ParsePKCS8PrivateKey(block.Bytes); err != nil {
2024-02-18 10:42:21 +00:00
return nil, err
2024-02-18 10:42:21 +00:00
}
var pkey ed25519.PrivateKey
2024-02-18 10:42:21 +00:00
var ok bool
2024-02-18 10:42:21 +00:00
if pkey, ok = parsedKey.(ed25519.PrivateKey); !ok {
2024-02-18 10:42:21 +00:00
return nil, ErrNotEdPrivateKey
2024-02-18 10:42:21 +00:00
}
return pkey, nil
2024-02-18 10:42:21 +00:00
}
// ParseEdPublicKeyFromPEM parses a PEM-encoded Edwards curve public key
2024-02-18 10:42:21 +00:00
func ParseEdPublicKeyFromPEM(key []byte) (crypto.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
return nil, err
2024-02-18 10:42:21 +00:00
}
var pkey ed25519.PublicKey
2024-02-18 10:42:21 +00:00
var ok bool
2024-02-18 10:42:21 +00:00
if pkey, ok = parsedKey.(ed25519.PublicKey); !ok {
2024-02-18 10:42:21 +00:00
return nil, ErrNotEdPublicKey
2024-02-18 10:42:21 +00:00
}
return pkey, nil
2024-02-18 10:42:21 +00:00
}