ed25519_utils.go (1359B)
1 package jwt 2 3 import ( 4 "crypto" 5 "crypto/ed25519" 6 "crypto/x509" 7 "encoding/pem" 8 "errors" 9 ) 10 11 var ( 12 ErrNotEdPrivateKey = errors.New("Key is not a valid Ed25519 private key") 13 ErrNotEdPublicKey = errors.New("Key is not a valid Ed25519 public key") 14 ) 15 16 // Parse PEM-encoded Edwards curve private key 17 func ParseEdPrivateKeyFromPEM(key []byte) (crypto.PrivateKey, error) { 18 var err error 19 20 // Parse PEM block 21 var block *pem.Block 22 if block, _ = pem.Decode(key); block == nil { 23 return nil, ErrKeyMustBePEMEncoded 24 } 25 26 // Parse the key 27 var parsedKey interface{} 28 if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil { 29 return nil, err 30 } 31 32 var pkey ed25519.PrivateKey 33 var ok bool 34 if pkey, ok = parsedKey.(ed25519.PrivateKey); !ok { 35 return nil, ErrNotEdPrivateKey 36 } 37 38 return pkey, nil 39 } 40 41 // Parse PEM-encoded Edwards curve public key 42 func ParseEdPublicKeyFromPEM(key []byte) (crypto.PublicKey, error) { 43 var err error 44 45 // Parse PEM block 46 var block *pem.Block 47 if block, _ = pem.Decode(key); block == nil { 48 return nil, ErrKeyMustBePEMEncoded 49 } 50 51 // Parse the key 52 var parsedKey interface{} 53 if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { 54 return nil, err 55 } 56 57 var pkey ed25519.PublicKey 58 var ok bool 59 if pkey, ok = parsedKey.(ed25519.PublicKey); !ok { 60 return nil, ErrNotEdPublicKey 61 } 62 63 return pkey, nil 64 }