Skip to content

error:0409806E:rsa routines:RSA_padding_add_PKCS1_PSS_mgf1:data too large for key size #39

@stevendesu

Description

@stevendesu

There may be nothing weird or wrong about this and I just don't understand the underlying algorithms, but my understanding did not match up to the behavior I experienced.

From my understanding, keys as short at 512 bits should be acceptable when writing a JSON Web Token. However I've found experimentally then when signing tokens using the PS512 algorithm, if I create a public/private key pair with a length less than 1034 bits then I get the error in the title.

I'm generating my key like so:

crypto.generateKeyPair(
	"rsa",
	{
		modulusLength: 1033,
		publicKeyEncoding: {type: "pkcs1", format: "pem"},
		privateKeyEncoding: {type: "pkcs8", format: "pem"}
	},
	async (err, pub, priv) => {
		if (err) throw err;
		// ... write pub and priv to a file ...
	}
);

I then utilize the key like so:

jsonwebtoken.sign({
	sub: user.id
}, privateKey, {
	algorithm: "PS512"
}, async (err, encoded) => {
	if (err) throw err;
	// ... return encoded key to user ...
});

This is throwing the following error:

Error: error:0409806E:rsa routines:RSA_padding_add_PKCS1_PSS_mgf1:data too large for key size
    at Sign.sign (internal/crypto/sig.js:112:29)
    at Object.sign (/Users/stevenbarnett/Repos/xxx/auth/node_modules/jwa/index.js:173:45)
    at jwsSign (/Users/stevenbarnett/Repos/xxx/auth/node_modules/jws/lib/sign-stream.js:32:24)
    at SignStream.sign (/Users/stevenbarnett/Repos/xxx/auth/node_modules/jws/lib/sign-stream.js:58:21)
    at SignStream.<anonymous> (/Users/stevenbarnett/Repos/xxx/auth/node_modules/jws/lib/sign-stream.js:46:12)
    at Object.onceWrapper (events.js:421:28)
    at DataStream.emit (events.js:315:20)
    at DataStream.EventEmitter.emit (domain.js:485:12)
    at DataStream.<anonymous> (/Users/stevenbarnett/Repos/xxx/auth/node_modules/jws/lib/data-stream.js:32:12)
    at processTicksAndRejections (internal/process/task_queues.js:79:11)

If I set the modulus length to 1034 or greater, or if I change the algorithm to RS512 or PS256, the error goes away.

I don't understand the internals of the various algorithms well enough to understand why this is the case. I had hoped to utilize a very short key in development (512 bits) and a very large key in production (4096 bits) - but when I ran into this I just grew more and more confused.

I'm posting here because the last (non-internal) line of the stack trace pointed to jwa, but this could very well be an issue with jws, jsonwebtoken, or even with NodeJS itself

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions