@@ -4,6 +4,7 @@ var ApiException = require('./ApiException');
44var Constants = require ( './Constants' ) ;
55var fs = require ( 'fs' ) ;
66var forge = require ( 'node-forge' ) ;
7+ var jwkToPem = require ( 'jwk-to-pem' ) ;
78
89exports . getResponseCodeMessage = function ( responseCode ) {
910
@@ -277,3 +278,41 @@ exports.readPrivateKeyFromPemFile = function(filePath, password, logger) {
277278 ApiException . AuthException ( `Error loading private key from PEM file: ${ filePath } : ${ error . message } ` ) ;
278279 }
279280} ;
281+
282+ exports . parseAndReturnPem = function ( key , logger ) {
283+ logger . debug ( `Parsing private key to PEM format synchronously, key type: ${ typeof key } ` ) ;
284+
285+ if ( typeof key === 'string' ) {
286+ 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' ) ;
295+ }
296+ } else if ( typeof key === 'object' && key !== null ) {
297+ logger . debug ( 'Processing object key as potential JWK private key' ) ;
298+ try {
299+ // Check if it has the 'd' property which indicates a private key
300+ if ( ! key . d ) {
301+ logger . error ( 'JWK object is not a private key (missing d parameter)' ) ;
302+ throw new Error ( 'JWK object is not a private key' ) ;
303+ }
304+
305+ // Convert JWK to PEM (private key)
306+ logger . debug ( 'Converting JWK to private key PEM' ) ;
307+ const pem = jwkToPem ( key , { private : true } ) ;
308+ logger . debug ( 'Successfully converted JWK to private key PEM format' ) ;
309+ return pem ;
310+ } catch ( error ) {
311+ logger . error ( `Invalid JWK private key object: ${ error . message } ` ) ;
312+ throw new Error ( 'Invalid JWK private key object' ) ;
313+ }
314+ } else {
315+ logger . error ( `Unsupported key format: ${ typeof key } ` ) ;
316+ throw new Error ( 'Unsupported key format' ) ;
317+ }
318+ }
0 commit comments