diff --git a/lib/jwk/import.js b/lib/jwk/import.js index bcba412a9e..7b1583c23e 100644 --- a/lib/jwk/import.js +++ b/lib/jwk/import.js @@ -67,7 +67,11 @@ const importKey = (key, parameters) => { publicKey = createPublicKey(key) } catch (err) {} try { - secret = createSecretKey(Buffer.isBuffer(key) ? key : Buffer.from(key)) + // this is to filter out invalid PEM keys and certs, i'll rather have them fail import then + // have them imported as symmetric "oct" keys + if (!key.includes('-----BEGIN')) { + secret = createSecretKey(Buffer.isBuffer(key) ? key : Buffer.from(key)) + } } catch (err) {} } diff --git a/test/jwk/import.test.js b/test/jwk/import.test.js index cdd29dd01a..ce01ff6b73 100644 --- a/test/jwk/import.test.js +++ b/test/jwk/import.test.js @@ -37,6 +37,16 @@ test('parameters must be a plain object', t => { }) Object.entries(fixtures.PEM).forEach(([type, { private: priv, public: pub }]) => { + test(`fails to import ${type} as invalid string`, t => { + t.throws(() => { + importKey(priv.toString('ascii').replace(/\n/g, '')) + }, { instanceOf: errors.JWKImportFailed, code: 'ERR_JWK_IMPORT_FAILED' }) + }) + test(`fails to import ${type} as invalid buffer`, t => { + t.throws(() => { + importKey(Buffer.from(priv.toString('ascii').replace(/\n/g, ''))) + }, { instanceOf: errors.JWKImportFailed, code: 'ERR_JWK_IMPORT_FAILED' }) + }) test(`${type} private can be imported as a string`, t => { const k = importKey(priv.toString('ascii')) t.true(k.private)