fix: load dek header-less private keys
Cadoles/go-http-peering/pipeline/head This commit is unstable Details

This commit is contained in:
wpetit 2023-11-21 14:13:32 +01:00
parent ced46bf6eb
commit 1bf8d755ed
1 changed files with 11 additions and 12 deletions

View File

@ -9,6 +9,7 @@ import (
jwt "github.com/dgrijalva/jwt-go" jwt "github.com/dgrijalva/jwt-go"
"github.com/pkg/errors" "github.com/pkg/errors"
"golang.org/x/crypto/ssh"
) )
func EncodePublicKeyToPEM(key crypto.PublicKey) ([]byte, error) { func EncodePublicKeyToPEM(key crypto.PublicKey) ([]byte, error) {
@ -28,25 +29,23 @@ func DecodePEMToPublicKey(pem []byte) (crypto.PublicKey, error) {
} }
func DecodePEMEncryptedPrivateKey(key []byte, passphrase []byte) (*rsa.PrivateKey, error) { func DecodePEMEncryptedPrivateKey(key []byte, passphrase []byte) (*rsa.PrivateKey, error) {
// Parse PEM block var (
var block *pem.Block rawKey interface{}
if block, _ = pem.Decode(key); block == nil { err error
return nil, errors.New("invalid PEM block") )
}
decryptedBlock, err := x509.DecryptPEMBlock(block, passphrase) if len(passphrase) == 0 {
rawKey, err = ssh.ParseRawPrivateKey(key)
} else {
rawKey, err = ssh.ParseRawPrivateKeyWithPassphrase(key, passphrase)
}
if err != nil { if err != nil {
return nil, errors.WithStack(err) return nil, errors.WithStack(err)
} }
var parsedKey interface{}
if parsedKey, err = x509.ParsePKCS1PrivateKey(decryptedBlock); err != nil {
return nil, errors.WithStack(err)
}
var privateKey *rsa.PrivateKey var privateKey *rsa.PrivateKey
var ok bool var ok bool
if privateKey, ok = parsedKey.(*rsa.PrivateKey); !ok { if privateKey, ok = rawKey.(*rsa.PrivateKey); !ok {
return nil, errors.New("invalid RSA private key") return nil, errors.New("invalid RSA private key")
} }