Skip to content

Commit 857dc2b

Browse files
committed
fix: fail to import invalid PEM formatted strings and buffers
1 parent 23b874c commit 857dc2b

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

lib/jwk/import.js

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,11 @@ const importKey = (key, parameters) => {
6767
publicKey = createPublicKey(key)
6868
} catch (err) {}
6969
try {
70-
secret = createSecretKey(Buffer.isBuffer(key) ? key : Buffer.from(key))
70+
// this is to filter out invalid PEM keys and certs, i'll rather have them fail import then
71+
// have them imported as symmetric "oct" keys
72+
if (!key.includes('-----BEGIN')) {
73+
secret = createSecretKey(Buffer.isBuffer(key) ? key : Buffer.from(key))
74+
}
7175
} catch (err) {}
7276
}
7377

test/jwk/import.test.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,16 @@ test('parameters must be a plain object', t => {
3737
})
3838

3939
Object.entries(fixtures.PEM).forEach(([type, { private: priv, public: pub }]) => {
40+
test(`fails to import ${type} as invalid string`, t => {
41+
t.throws(() => {
42+
importKey(priv.toString('ascii').replace(/\n/g, ''))
43+
}, { instanceOf: errors.JWKImportFailed, code: 'ERR_JWK_IMPORT_FAILED' })
44+
})
45+
test(`fails to import ${type} as invalid buffer`, t => {
46+
t.throws(() => {
47+
importKey(Buffer.from(priv.toString('ascii').replace(/\n/g, '')))
48+
}, { instanceOf: errors.JWKImportFailed, code: 'ERR_JWK_IMPORT_FAILED' })
49+
})
4050
test(`${type} private can be imported as a string`, t => {
4151
const k = importKey(priv.toString('ascii'))
4252
t.true(k.private)

0 commit comments

Comments
 (0)