From 256619602f85c887ec7ddbfaee9cdefbf447cef2 Mon Sep 17 00:00:00 2001 From: Filip Skokan Date: Tue, 28 Apr 2026 17:15:22 +0200 Subject: [PATCH] crypto: reject unintended raw key format string input MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Filip Skokan PR-URL: https://github.com/nodejs/node/pull/62974 Reviewed-By: Сковорода Никита Андреевич Reviewed-By: Tobias Nießen Reviewed-By: Luigi Pinca --- lib/internal/crypto/keys.js | 2 +- test/parallel/test-crypto-key-objects-raw.js | 44 ++++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/lib/internal/crypto/keys.js b/lib/internal/crypto/keys.js index 6a10107da4cd02..f26faaa0899ada 100644 --- a/lib/internal/crypto/keys.js +++ b/lib/internal/crypto/keys.js @@ -765,7 +765,7 @@ function getKeyObjectHandleFromJwk(key, ctx) { function getKeyObjectHandleFromRaw(options, data, format) { - if (!isStringOrBuffer(data)) { + if (!isArrayBufferView(data) && !isAnyArrayBuffer(data)) { throw new ERR_INVALID_ARG_TYPE( 'key.key', ['ArrayBuffer', 'Buffer', 'TypedArray', 'DataView'], diff --git a/test/parallel/test-crypto-key-objects-raw.js b/test/parallel/test-crypto-key-objects-raw.js index f301cc1942fd9a..5658be6825823f 100644 --- a/test/parallel/test-crypto-key-objects-raw.js +++ b/test/parallel/test-crypto-key-objects-raw.js @@ -32,6 +32,50 @@ const { hasOpenSSL } = require('../common/crypto'); } } +// Raw key imports do not support strings. +{ + const pubKeyObj = crypto.createPublicKey( + fixtures.readKey('ed25519_public.pem', 'ascii')); + const privKeyObj = crypto.createPrivateKey( + fixtures.readKey('ed25519_private.pem', 'ascii')); + + const rawPub = pubKeyObj.export({ format: 'raw-public' }); + const rawPriv = privKeyObj.export({ format: 'raw-private' }); + + for (const encoding of ['hex', 'base64', 'utf8', 'latin1', 'ascii']) { + assert.throws(() => crypto.createPublicKey({ + key: rawPub.toString(encoding), + encoding, + format: 'raw-public', + asymmetricKeyType: 'ed25519', + }), { code: 'ERR_INVALID_ARG_TYPE' }); + + assert.throws(() => crypto.createPrivateKey({ + key: rawPriv.toString(encoding), + encoding, + format: 'raw-private', + asymmetricKeyType: 'ed25519', + }), { code: 'ERR_INVALID_ARG_TYPE' }); + } +} + +// Raw seed imports do not support strings. +if (hasOpenSSL(3, 5)) { + const privKeyObj = crypto.createPrivateKey( + fixtures.readKey('ml_dsa_44_private.pem', 'ascii')); + + const rawSeed = privKeyObj.export({ format: 'raw-seed' }); + + for (const encoding of ['hex', 'base64']) { + assert.throws(() => crypto.createPrivateKey({ + key: rawSeed.toString(encoding), + encoding, + format: 'raw-seed', + asymmetricKeyType: 'ml-dsa-44', + }), { code: 'ERR_INVALID_ARG_TYPE' }); + } +} + // Key types that don't support raw-* formats { for (const [type, pub, priv] of [