@@ -279,19 +279,53 @@ exports.readPrivateKeyFromPemFile = function(filePath, password, logger) {
279279 }
280280} ;
281281
282- exports . parseAndReturnPem = function ( key , logger ) {
282+ exports . parseAndReturnPem = function ( key , logger , password ) {
283283 logger . debug ( `Parsing private key to PEM format synchronously, key type: ${ typeof key } ` ) ;
284284
285285 if ( typeof key === 'string' ) {
286286 logger . debug ( 'Processing string key as potential PEM private key' ) ;
287- try {
288- // Validate it's a valid private key PEM
289- forge . pki . privateKeyFromPem ( key ) ;
290- logger . debug ( 'Successfully validated private key PEM format' ) ;
291- return key ;
292- } catch ( error ) {
293- logger . error ( `Invalid private key PEM format: ${ error . message } ` ) ;
294- throw new Error ( 'Invalid private key PEM format' ) ;
287+
288+ // Check if the key is encrypted
289+ const isEncrypted = key . includes ( 'ENCRYPTED' ) ;
290+
291+ if ( isEncrypted ) {
292+ logger . debug ( 'Detected encrypted private key' ) ;
293+
294+ // Check if password is provided for encrypted key
295+ if ( ! password || password . trim ( ) === '' ) {
296+ logger . error ( 'Password is required for encrypted private key' ) ;
297+ throw new Error ( 'Password is required for encrypted private key' ) ;
298+ }
299+
300+ try {
301+ // Decrypt the private key using the provided password
302+ logger . debug ( 'Attempting to decrypt private key with provided password' ) ;
303+ const privateKey = forge . pki . decryptRsaPrivateKey ( key , password ) ;
304+
305+ if ( ! privateKey ) {
306+ logger . error ( 'Failed to decrypt private key. Incorrect password or invalid key format.' ) ;
307+ throw new Error ( 'Failed to decrypt private key. Incorrect password or invalid key format.' ) ;
308+ }
309+
310+ // Convert the decrypted key back to PEM format
311+ const pemKey = forge . pki . privateKeyToPem ( privateKey ) ;
312+ logger . debug ( 'Successfully decrypted and converted private key to PEM format' ) ;
313+ return pemKey ;
314+ } catch ( error ) {
315+ logger . error ( `Error decrypting private key: ${ error . message } ` ) ;
316+ throw new Error ( `Error decrypting private key: ${ error . message } ` ) ;
317+ }
318+ } else {
319+ // Not encrypted, proceed with normal validation
320+ try {
321+ // Validate it's a valid private key PEM
322+ forge . pki . privateKeyFromPem ( key ) ;
323+ logger . debug ( 'Successfully validated private key PEM format' ) ;
324+ return key ;
325+ } catch ( error ) {
326+ logger . error ( `Invalid private key PEM format: ${ error . message } ` ) ;
327+ throw new Error ( 'Invalid private key PEM format' ) ;
328+ }
295329 }
296330 } else if ( typeof key === 'object' && key !== null ) {
297331 logger . debug ( 'Processing object key as potential JWK private key' ) ;
0 commit comments