From 1bf8d755ed32785355ee627b52b6eb2c98042eb4 Mon Sep 17 00:00:00 2001 From: William Petit Date: Tue, 21 Nov 2023 14:13:32 +0100 Subject: [PATCH] fix: load dek header-less private keys --- crypto/pem.go | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/crypto/pem.go b/crypto/pem.go index 48119f9..83c37e1 100644 --- a/crypto/pem.go +++ b/crypto/pem.go @@ -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") }