package jwt
import (
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
)
var (
ErrKeyMustBePEMEncoded = errors .New ("invalid key: Key must be a PEM encoded PKCS1 or PKCS8 key" )
ErrNotRSAPrivateKey = errors .New ("key is not a valid RSA private key" )
ErrNotRSAPublicKey = errors .New ("key is not a valid RSA public key" )
)
func ParseRSAPrivateKeyFromPEM (key []byte ) (*rsa .PrivateKey , error ) {
var err error
var block *pem .Block
if block , _ = pem .Decode (key ); block == nil {
return nil , ErrKeyMustBePEMEncoded
}
var parsedKey interface {}
if parsedKey , err = x509 .ParsePKCS1PrivateKey (block .Bytes ); err != nil {
if parsedKey , err = x509 .ParsePKCS8PrivateKey (block .Bytes ); err != nil {
return nil , err
}
}
var pkey *rsa .PrivateKey
var ok bool
if pkey , ok = parsedKey .(*rsa .PrivateKey ); !ok {
return nil , ErrNotRSAPrivateKey
}
return pkey , nil
}
func ParseRSAPrivateKeyFromPEMWithPassword (key []byte , password string ) (*rsa .PrivateKey , error ) {
var err error
var block *pem .Block
if block , _ = pem .Decode (key ); block == nil {
return nil , ErrKeyMustBePEMEncoded
}
var parsedKey interface {}
var blockDecrypted []byte
if blockDecrypted , err = x509 .DecryptPEMBlock (block , []byte (password )); err != nil {
return nil , err
}
if parsedKey , err = x509 .ParsePKCS1PrivateKey (blockDecrypted ); err != nil {
if parsedKey , err = x509 .ParsePKCS8PrivateKey (blockDecrypted ); err != nil {
return nil , err
}
}
var pkey *rsa .PrivateKey
var ok bool
if pkey , ok = parsedKey .(*rsa .PrivateKey ); !ok {
return nil , ErrNotRSAPrivateKey
}
return pkey , nil
}
func ParseRSAPublicKeyFromPEM (key []byte ) (*rsa .PublicKey , error ) {
var err error
var block *pem .Block
if block , _ = pem .Decode (key ); block == nil {
return nil , ErrKeyMustBePEMEncoded
}
var parsedKey interface {}
if parsedKey , err = x509 .ParsePKIXPublicKey (block .Bytes ); err != nil {
if cert , err := x509 .ParseCertificate (block .Bytes ); err == nil {
parsedKey = cert .PublicKey
} else {
return nil , err
}
}
var pkey *rsa .PublicKey
var ok bool
if pkey , ok = parsedKey .(*rsa .PublicKey ); !ok {
return nil , ErrNotRSAPublicKey
}
return pkey , nil
}
The pages are generated with Golds v0.6.7 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @Go100and1 (reachable from the left QR code) to get the latest news of Golds .