jwt/rsa_utils.go

64 lines
1.5 KiB
Go
Raw Permalink Normal View History

2014-08-07 12:00:06 +04:00
package jwt
import (
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
)
// Parse PEM encoded PKCS1 or PKCS8 private key
2014-08-27 01:24:20 +04:00
func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error) {
2014-08-07 12:00:06 +04:00
var err error
// Parse PEM block
var block *pem.Block
if block, _ = pem.Decode(key); block == nil {
return nil, errors.New("Invalid Key: Key must be PEM encoded PKCS1 or PKCS8 private key")
}
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, errors.New("Key is not a valid RSA private key")
}
return pkey, nil
}
// Parse PEM encoded PKCS1 or PKCS8 public key
2014-08-27 01:24:20 +04:00
func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) {
2014-08-07 12:00:06 +04:00
var err error
// Parse PEM block
var block *pem.Block
if block, _ = pem.Decode(key); block == nil {
return nil, errors.New("Invalid Key: Key must be PEM encoded PKCS1 or PKCS8 private key")
}
// Parse the key
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, errors.New("Key is not a valid RSA public key")
}
return pkey, nil
}