From 2dfbda2f9d02586d8b172dcaaef46953deee8c3f Mon Sep 17 00:00:00 2001 From: Artur Troian Date: Mon, 28 Aug 2023 19:30:08 -0400 Subject: [PATCH] fix: try parse private key instead of checking for error DecryptPEMBlock may not return error due to format quirks Try parse key instead, and if fail use legacy passowrd to open it Signed-off-by: Artur Troian --- x/cert/utils/key_pair_manager.go | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/x/cert/utils/key_pair_manager.go b/x/cert/utils/key_pair_manager.go index e7892e8790..d51cde592e 100644 --- a/x/cert/utils/key_pair_manager.go +++ b/x/cert/utils/key_pair_manager.go @@ -264,6 +264,7 @@ func (kpm *keyPairManager) readImpl(fin io.Reader) ([]byte, []byte, []byte, erro } var privKeyPlaintext []byte + var privKeyI interface{} // PKCS#8 header defined in RFC7468 section 11 // nolint: gocritic @@ -272,21 +273,26 @@ func (kpm *keyPairManager) readImpl(fin io.Reader) ([]byte, []byte, []byte, erro } else if block.Headers["Proc-Type"] == "4,ENCRYPTED" { // nolint: staticcheck privKeyPlaintext, err = x509.DecryptPEMBlock(block, kpm.passwordBytes) - if errors.Is(err, x509.IncorrectPasswordError) { + + // DecryptPEMBlock may not return IncorrectPasswordError. + // Try parse private key instead and if it fails give another try with legacy password + privKeyI, err = x509.ParsePKCS8PrivateKey(privKeyPlaintext) + + if err != nil { // nolint: staticcheck privKeyPlaintext, err = x509.DecryptPEMBlock(block, kpm.passwordLegacy) } } else { return nil, nil, nil, errUnsupportedEncryptedPEM } - if err != nil { return nil, nil, nil, fmt.Errorf("%w: failed decrypting x509 block with private key", err) } - var privKeyI interface{} - if privKeyI, err = x509.ParsePKCS8PrivateKey(privKeyPlaintext); err != nil { - return nil, nil, nil, fmt.Errorf("%w: failed parsing private key data", err) + if privKeyI == nil { + if privKeyI, err = x509.ParsePKCS8PrivateKey(privKeyPlaintext); err != nil { + return nil, nil, nil, fmt.Errorf("%w: failed parsing private key data", err) + } } eckey, valid := privKeyI.(*ecdsa.PrivateKey)