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

This commit is contained in:
wpetit 2023-11-21 14:13:32 +01:00
parent ced46bf6eb
commit 1bf8d755ed

View File

@ -9,6 +9,7 @@ import (
jwt "github.com/dgrijalva/jwt-go"
"github.com/pkg/errors"
"golang.org/x/crypto/ssh"
)
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) {
// Parse PEM block
var block *pem.Block
if block, _ = pem.Decode(key); block == nil {
return nil, errors.New("invalid PEM block")
}
var (
rawKey interface{}
err error
)
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 {
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 ok bool
if privateKey, ok = parsedKey.(*rsa.PrivateKey); !ok {
if privateKey, ok = rawKey.(*rsa.PrivateKey); !ok {
return nil, errors.New("invalid RSA private key")
}