Skip to content

Commit 427d209

Browse files
adamjmcgrathaduh95
authored andcommitted
crypto: add mgf1Hash for RSA-OAEP
Signed-off-by: Adam Mcgrath <adam.mcgrath@okta.com> PR-URL: #65073 Reviewed-By: Filip Skokan <panva.ip@gmail.com> Reviewed-By: Aviv Keller <me@aviv.sh>
1 parent d0aa98b commit 427d209

9 files changed

Lines changed: 192 additions & 10 deletions

File tree

deps/ncrypto/ncrypto.cc

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5650,9 +5650,11 @@ DataPointer RSA_Cipher(const EVPKeyPointer& key,
56505650
if (!key) return {};
56515651
EVPKeyCtxPointer ctx = key.newCtx();
56525652

5653+
const Digest& mgf1_digest =
5654+
params.mgf1_digest != nullptr ? params.mgf1_digest : params.digest;
56535655
if (!ctx || init(ctx.get()) <= 0 || !ctx.setRsaPadding(params.padding) ||
5654-
(params.digest != nullptr && (!ctx.setRsaOaepMd(params.digest) ||
5655-
!ctx.setRsaMgf1Md(params.digest)))) {
5656+
(params.digest != nullptr &&
5657+
(!ctx.setRsaOaepMd(params.digest) || !ctx.setRsaMgf1Md(mgf1_digest)))) {
56565658
return {};
56575659
}
56585660

@@ -5691,7 +5693,9 @@ DataPointer CipherImpl(const EVPKeyPointer& key,
56915693
if (!key) return {};
56925694
EVPKeyCtxPointer ctx = key.newCtx();
56935695
if (!ctx || init(ctx.get()) <= 0 || !ctx.setRsaPadding(params.padding) ||
5694-
(params.digest != nullptr && !ctx.setRsaOaepMd(params.digest))) {
5696+
(params.digest != nullptr && !ctx.setRsaOaepMd(params.digest)) ||
5697+
(params.mgf1_digest != nullptr &&
5698+
!ctx.setRsaMgf1Md(params.mgf1_digest))) {
56955699
return {};
56965700
}
56975701

deps/ncrypto/ncrypto.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -508,6 +508,7 @@ class Cipher final {
508508
struct CipherParams {
509509
int padding;
510510
Digest digest;
511+
Digest mgf1_digest;
511512
const Buffer<const void> label;
512513
};
513514

doc/api/crypto.md

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5300,6 +5300,9 @@ An array of supported digest functions can be retrieved using
53005300
<!-- YAML
53015301
added: v0.11.14
53025302
changes:
5303+
- version: REPLACEME
5304+
pr-url: https://github.com/nodejs/node/pull/65073
5305+
description: The `mgf1Hash` option was added.
53035306
- version:
53045307
- v21.6.2
53055308
- v20.11.1
@@ -5327,8 +5330,11 @@ changes:
53275330
<!--lint disable maximum-line-length remark-lint-->
53285331

53295332
* `privateKey` {Object|string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey|URL}
5330-
* `oaepHash` {string} The hash function to use for OAEP padding and MGF1.
5331-
**Default:** `'sha1'`
5333+
* `oaepHash` {string} The hash function to use for OAEP padding and, unless
5334+
`mgf1Hash` is set, MGF1. **Default:** `'sha1'`
5335+
* `mgf1Hash` {string} The hash function to use for the MGF1 mask generation
5336+
function of OAEP padding. If not specified, the value of `oaepHash` is used.
5337+
This allows the OAEP digest and the MGF1 digest to differ.
53325338
* `oaepLabel` {string|ArrayBuffer|Buffer|TypedArray|DataView} The label to
53335339
use for OAEP padding. If not specified, no label is used.
53345340
* `padding` {crypto.constants} An optional padding value defined in
@@ -5442,6 +5448,9 @@ be passed instead of a public key.
54425448
<!-- YAML
54435449
added: v0.11.14
54445450
changes:
5451+
- version: REPLACEME
5452+
pr-url: https://github.com/nodejs/node/pull/65073
5453+
description: The `mgf1Hash` option was added.
54455454
- version: v15.0.0
54465455
pr-url: https://github.com/nodejs/node/pull/35093
54475456
description: Added string, ArrayBuffer, and CryptoKey as allowable key
@@ -5464,8 +5473,11 @@ changes:
54645473
* `key` {Object|string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey}
54655474
* `key` {string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey}
54665475
A PEM encoded public or private key, {KeyObject}, or {CryptoKey}.
5467-
* `oaepHash` {string} The hash function to use for OAEP padding and MGF1.
5468-
**Default:** `'sha1'`
5476+
* `oaepHash` {string} The hash function to use for OAEP padding and, unless
5477+
`mgf1Hash` is set, MGF1. **Default:** `'sha1'`
5478+
* `mgf1Hash` {string} The hash function to use for the MGF1 mask generation
5479+
function of OAEP padding. If not specified, the value of `oaepHash` is used.
5480+
This allows the OAEP digest and the MGF1 digest to differ.
54695481
* `oaepLabel` {string|ArrayBuffer|Buffer|TypedArray|DataView} The label to
54705482
use for OAEP padding. If not specified, no label is used.
54715483
* `passphrase` {string|ArrayBuffer|Buffer|TypedArray|DataView} An optional

lib/internal/crypto/cipher.js

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -68,15 +68,17 @@ function rsaFunctionFor(method, defaultPadding, keyType) {
6868
preparePrivateKey(key, keyName) :
6969
preparePublicOrPrivateKey(key, keyName);
7070
const padding = key.padding || defaultPadding;
71-
const { oaepHash, encoding } = key;
71+
const { oaepHash, mgf1Hash, encoding } = key;
7272
let { oaepLabel } = key;
7373
if (oaepHash !== undefined)
7474
validateString(oaepHash, 'key.oaepHash');
75+
if (mgf1Hash !== undefined)
76+
validateString(mgf1Hash, 'key.mgf1Hash');
7577
if (oaepLabel !== undefined)
7678
oaepLabel = getArrayBufferOrView(oaepLabel, 'key.oaepLabel', encoding);
7779
buffer = getArrayBufferOrView(buffer, 'buffer', encoding);
7880
return method(data, format, type, passphrase, namedCurve, buffer,
79-
padding, oaepHash, oaepLabel);
81+
padding, oaepHash, oaepLabel, mgf1Hash);
8082
};
8183
}
8284

src/crypto/crypto_cipher.cc

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -801,6 +801,7 @@ bool PublicKeyCipher::Cipher(
801801
const EVPKeyPointer& pkey,
802802
int padding,
803803
const Digest& digest,
804+
const Digest& mgf1_digest,
804805
const ArrayBufferOrViewContents<unsigned char>& oaep_label,
805806
const ArrayBufferOrViewContents<unsigned char>& data,
806807
std::unique_ptr<BackingStore>* out) {
@@ -810,6 +811,7 @@ bool PublicKeyCipher::Cipher(
810811
const ncrypto::Cipher::CipherParams params{
811812
.padding = padding,
812813
.digest = digest,
814+
.mgf1_digest = mgf1_digest,
813815
.label = label,
814816
};
815817

@@ -882,8 +884,17 @@ void PublicKeyCipher::Cipher(const FunctionCallbackInfo<Value>& args) {
882884
if (!oaep_label.CheckSizeInt32()) [[unlikely]] {
883885
return THROW_ERR_OUT_OF_RANGE(env, "oaepLabel is too big");
884886
}
887+
888+
Digest mgf1_digest;
889+
if (args[offset + 4]->IsString()) {
890+
Utf8Value mgf1_str(env->isolate(), args[offset + 4]);
891+
mgf1_digest = Digest::FromName(*mgf1_str);
892+
if (!mgf1_digest) return THROW_ERR_OSSL_EVP_INVALID_DIGEST(env);
893+
}
894+
885895
std::unique_ptr<BackingStore> out;
886-
if (!Cipher<cipher>(env, pkey, padding, digest, oaep_label, buf, &out)) {
896+
if (!Cipher<cipher>(
897+
env, pkey, padding, digest, mgf1_digest, oaep_label, buf, &out)) {
887898
return ThrowCryptoError(env, ERR_get_error());
888899
}
889900

src/crypto/crypto_cipher.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@ class PublicKeyCipher {
106106
const ncrypto::EVPKeyPointer& pkey,
107107
int padding,
108108
const ncrypto::Digest& digest,
109+
const ncrypto::Digest& mgf1_digest,
109110
const ArrayBufferOrViewContents<unsigned char>& oaep_label,
110111
const ArrayBufferOrViewContents<unsigned char>& data,
111112
std::unique_ptr<v8::BackingStore>* out);

src/crypto/crypto_rsa.cc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,7 @@ WebCryptoCipherStatus RSA_Cipher(Environment* env,
206206
const ncrypto::Rsa::CipherParams nparams{
207207
.padding = params.padding,
208208
.digest = params.digest,
209+
.mgf1_digest = params.digest,
209210
.label = params.label,
210211
};
211212

Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
'use strict';
2+
const common = require('../common');
3+
if (!common.hasCrypto)
4+
common.skip('missing crypto');
5+
6+
// Tests the `mgf1Hash` option of crypto.publicEncrypt() and
7+
// crypto.privateDecrypt(), which allows the MGF1 digest of RSA-OAEP padding to
8+
// differ from the OAEP message digest (`oaepHash`). This is required for
9+
// interoperability with profiles such as XML Encryption's `rsa-oaep-mgf1p`,
10+
// where the OAEP digest may be changed but MGF1 is fixed to SHA-1.
11+
12+
const assert = require('assert');
13+
const crypto = require('crypto');
14+
const fixtures = require('../common/fixtures');
15+
const { hasFIPS } = require('../common/crypto');
16+
17+
const constants = crypto.constants;
18+
19+
const publicKey = fixtures.readKey('rsa_public.pem', 'ascii');
20+
const privateKey = fixtures.readKey('rsa_private.pem', 'ascii');
21+
22+
const input = Buffer.from('the quick brown fox jumps over the lazy dog');
23+
24+
// A round-trip with mismatched OAEP and MGF1 digests must succeed when both
25+
// sides agree on the digests.
26+
{
27+
const encrypted = crypto.publicEncrypt({
28+
key: publicKey,
29+
padding: constants.RSA_PKCS1_OAEP_PADDING,
30+
oaepHash: 'sha256',
31+
mgf1Hash: 'sha1',
32+
}, input);
33+
34+
const decrypted = crypto.privateDecrypt({
35+
key: privateKey,
36+
padding: constants.RSA_PKCS1_OAEP_PADDING,
37+
oaepHash: 'sha256',
38+
mgf1Hash: 'sha1',
39+
}, encrypted);
40+
41+
assert.deepStrictEqual(decrypted, input);
42+
}
43+
44+
// mgf1Hash actually affects the padding: a ciphertext produced with
45+
// oaepHash=sha256 and mgf1Hash=sha1 must NOT decrypt when MGF1 defaults to the
46+
// OAEP digest (sha256), which is the pre-existing behavior.
47+
{
48+
const encrypted = crypto.publicEncrypt({
49+
key: publicKey,
50+
padding: constants.RSA_PKCS1_OAEP_PADDING,
51+
oaepHash: 'sha256',
52+
mgf1Hash: 'sha1',
53+
}, input);
54+
55+
assert.throws(() => {
56+
crypto.privateDecrypt({
57+
key: privateKey,
58+
padding: constants.RSA_PKCS1_OAEP_PADDING,
59+
oaepHash: 'sha256',
60+
// No mgf1Hash: MGF1 follows oaepHash (sha256) and must fail to unpad.
61+
}, encrypted);
62+
}, {
63+
code: hasFIPS(3, 5) ? 'ERR_OSSL_EVP_PROVIDER_ASYM_CIPHER_FAILURE' :
64+
'ERR_OSSL_RSA_OAEP_DECODING_ERROR'
65+
});
66+
}
67+
68+
// Backward compatibility: omitting mgf1Hash on both sides keeps MGF1 == oaepHash
69+
// (the historical behavior), so this round-trips, and setting mgf1Hash equal to
70+
// oaepHash is equivalent to omitting it.
71+
{
72+
const encrypted = crypto.publicEncrypt({
73+
key: publicKey,
74+
padding: constants.RSA_PKCS1_OAEP_PADDING,
75+
oaepHash: 'sha256',
76+
}, input);
77+
78+
const decrypted = crypto.privateDecrypt({
79+
key: privateKey,
80+
padding: constants.RSA_PKCS1_OAEP_PADDING,
81+
oaepHash: 'sha256',
82+
mgf1Hash: 'sha256',
83+
}, encrypted);
84+
85+
assert.deepStrictEqual(decrypted, input);
86+
}
87+
88+
// The default oaepHash is sha1, so mgf1Hash defaults to sha1 as well. A
89+
// ciphertext encrypted with all defaults must decrypt with an explicit
90+
// mgf1Hash: 'sha1'.
91+
{
92+
const encrypted = crypto.publicEncrypt({
93+
key: publicKey,
94+
padding: constants.RSA_PKCS1_OAEP_PADDING,
95+
}, input);
96+
97+
const decrypted = crypto.privateDecrypt({
98+
key: privateKey,
99+
padding: constants.RSA_PKCS1_OAEP_PADDING,
100+
mgf1Hash: 'sha1',
101+
}, encrypted);
102+
103+
assert.deepStrictEqual(decrypted, input);
104+
}
105+
106+
// A few other digest combinations round-trip.
107+
for (const [oaepHash, mgf1Hash] of [
108+
['sha512', 'sha1'],
109+
['sha384', 'sha256'],
110+
['sha1', 'sha256'],
111+
]) {
112+
const encrypted = crypto.publicEncrypt({
113+
key: publicKey,
114+
padding: constants.RSA_PKCS1_OAEP_PADDING,
115+
oaepHash,
116+
mgf1Hash,
117+
}, input);
118+
119+
const decrypted = crypto.privateDecrypt({
120+
key: privateKey,
121+
padding: constants.RSA_PKCS1_OAEP_PADDING,
122+
oaepHash,
123+
mgf1Hash,
124+
}, encrypted);
125+
126+
assert.deepStrictEqual(decrypted, input);
127+
}
128+
129+
// mgf1Hash must be a string.
130+
for (const mgf1Hash of [1, true, {}, [], null]) {
131+
assert.throws(() => {
132+
crypto.publicEncrypt({
133+
key: publicKey,
134+
padding: constants.RSA_PKCS1_OAEP_PADDING,
135+
oaepHash: 'sha256',
136+
mgf1Hash,
137+
}, input);
138+
}, { code: 'ERR_INVALID_ARG_TYPE' });
139+
}
140+
141+
// An unknown mgf1Hash digest name is rejected.
142+
assert.throws(() => {
143+
crypto.publicEncrypt({
144+
key: publicKey,
145+
padding: constants.RSA_PKCS1_OAEP_PADDING,
146+
oaepHash: 'sha256',
147+
mgf1Hash: 'not-a-real-digest',
148+
}, input);
149+
}, { code: 'ERR_OSSL_EVP_INVALID_DIGEST' });

typings/internalBinding/crypto.d.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -767,6 +767,7 @@ declare namespace InternalCryptoBinding {
767767
padding: number,
768768
oaepHash: string | undefined,
769769
oaepLabel: OptionalByteSource,
770+
mgf1Hash: string | undefined,
770771
]
771772
) => Buffer;
772773
}

0 commit comments

Comments
 (0)