Skip to content

Commit f85501f

Browse files
adamjmcgrathpanva
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> Assisted-by: Codex Signed-off-by: Filip Skokan <panva.ip@gmail.com>
1 parent 30280e7 commit f85501f

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
@@ -6096,9 +6096,11 @@ DataPointer RSA_Cipher(const EVPKeyPointer& key,
60966096
if (!key) return {};
60976097
EVPKeyCtxPointer ctx = key.newCtx();
60986098

6099+
const Digest& mgf1_digest =
6100+
params.mgf1_digest != nullptr ? params.mgf1_digest : params.digest;
60996101
if (!ctx || init(ctx.get()) <= 0 || !ctx.setRsaPadding(params.padding) ||
6100-
(params.digest != nullptr && (!ctx.setRsaOaepMd(params.digest) ||
6101-
!ctx.setRsaMgf1Md(params.digest)))) {
6102+
(params.digest != nullptr &&
6103+
(!ctx.setRsaOaepMd(params.digest) || !ctx.setRsaMgf1Md(mgf1_digest)))) {
61026104
return {};
61036105
}
61046106

@@ -6137,7 +6139,9 @@ DataPointer CipherImpl(const EVPKeyPointer& key,
61376139
if (!key) return {};
61386140
EVPKeyCtxPointer ctx = key.newCtx();
61396141
if (!ctx || init(ctx.get()) <= 0 || !ctx.setRsaPadding(params.padding) ||
6140-
(params.digest != nullptr && !ctx.setRsaOaepMd(params.digest))) {
6142+
(params.digest != nullptr && !ctx.setRsaOaepMd(params.digest)) ||
6143+
(params.mgf1_digest != nullptr &&
6144+
!ctx.setRsaMgf1Md(params.mgf1_digest))) {
61416145
return {};
61426146
}
61436147

‎deps/ncrypto/ncrypto.h‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -618,6 +618,7 @@ class Cipher final {
618618
struct CipherParams {
619619
int padding;
620620
Digest digest;
621+
Digest mgf1_digest;
621622
const Buffer<const void> label;
622623
};
623624

‎doc/api/crypto.md‎

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5621,6 +5621,9 @@ suitable for HMAC or PBKDF2.
56215621
<!-- YAML
56225622
added: v0.11.14
56235623
changes:
5624+
- version: REPLACEME
5625+
pr-url: https://github.com/nodejs/node/pull/65073
5626+
description: The `mgf1Hash` option was added.
56245627
- version:
56255628
- v21.6.2
56265629
- v20.11.1
@@ -5648,8 +5651,11 @@ changes:
56485651
<!--lint disable maximum-line-length remark-lint-->
56495652

56505653
* `privateKey` {Object|string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey|URL}
5651-
* `oaepHash` {string} The hash function to use for OAEP padding and MGF1.
5652-
**Default:** `'sha1'`
5654+
* `oaepHash` {string} The hash function to use for OAEP padding and, unless
5655+
`mgf1Hash` is set, MGF1. **Default:** `'sha1'`
5656+
* `mgf1Hash` {string} The hash function to use for the MGF1 mask generation
5657+
function of OAEP padding. If not specified, the value of `oaepHash` is used.
5658+
This allows the OAEP digest and the MGF1 digest to differ.
56535659
* `oaepLabel` {string|ArrayBuffer|Buffer|TypedArray|DataView} The label to
56545660
use for OAEP padding. If not specified, no label is used.
56555661
* `padding` {crypto.constants} An optional padding value defined in
@@ -5767,6 +5773,9 @@ be passed instead of a public key.
57675773
<!-- YAML
57685774
added: v0.11.14
57695775
changes:
5776+
- version: REPLACEME
5777+
pr-url: https://github.com/nodejs/node/pull/65073
5778+
description: The `mgf1Hash` option was added.
57705779
- version: v15.0.0
57715780
pr-url: https://github.com/nodejs/node/pull/35093
57725781
description: Added string, ArrayBuffer, and CryptoKey as allowable key
@@ -5789,8 +5798,11 @@ changes:
57895798
* `key` {Object|string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey}
57905799
* `key` {string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey}
57915800
A PEM encoded public or private key, {KeyObject}, or {CryptoKey}.
5792-
* `oaepHash` {string} The hash function to use for OAEP padding and MGF1.
5793-
**Default:** `'sha1'`
5801+
* `oaepHash` {string} The hash function to use for OAEP padding and, unless
5802+
`mgf1Hash` is set, MGF1. **Default:** `'sha1'`
5803+
* `mgf1Hash` {string} The hash function to use for the MGF1 mask generation
5804+
function of OAEP padding. If not specified, the value of `oaepHash` is used.
5805+
This allows the OAEP digest and the MGF1 digest to differ.
57945806
* `oaepLabel` {string|ArrayBuffer|Buffer|TypedArray|DataView} The label to
57955807
use for OAEP padding. If not specified, no label is used.
57965808
* `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
@@ -72,15 +72,17 @@ function rsaFunctionFor(method, defaultPadding, keyType) {
7272
preparePrivateKey(key, keyName) :
7373
preparePublicOrPrivateKey(key, keyName);
7474
const padding = key.padding || defaultPadding;
75-
const { oaepHash, encoding } = key;
75+
const { oaepHash, mgf1Hash, encoding } = key;
7676
let { oaepLabel } = key;
7777
if (oaepHash !== undefined)
7878
validateString(oaepHash, 'key.oaepHash');
79+
if (mgf1Hash !== undefined)
80+
validateString(mgf1Hash, 'key.mgf1Hash');
7981
if (oaepLabel !== undefined)
8082
oaepLabel = getArrayBufferOrView(oaepLabel, 'key.oaepLabel', encoding);
8183
buffer = getArrayBufferOrView(buffer, 'buffer', encoding);
8284
return method(data, format, type, passphrase, namedCurve, buffer,
83-
padding, oaepHash, oaepLabel);
85+
padding, oaepHash, oaepLabel, mgf1Hash);
8486
};
8587
}
8688

‎src/crypto/crypto_cipher.cc‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -947,6 +947,7 @@ bool PublicKeyCipher::Cipher(
947947
const EVPKeyPointer& pkey,
948948
int padding,
949949
const Digest& digest,
950+
const Digest& mgf1_digest,
950951
const ArrayBufferOrViewContents<unsigned char>& oaep_label,
951952
const ArrayBufferOrViewContents<unsigned char>& data,
952953
std::unique_ptr<BackingStore>* out) {
@@ -956,6 +957,7 @@ bool PublicKeyCipher::Cipher(
956957
const ncrypto::Cipher::CipherParams params{
957958
.padding = padding,
958959
.digest = digest,
960+
.mgf1_digest = mgf1_digest,
959961
.label = label,
960962
};
961963

@@ -1028,8 +1030,17 @@ void PublicKeyCipher::Cipher(const FunctionCallbackInfo<Value>& args) {
10281030
if (!oaep_label.CheckSizeInt32()) [[unlikely]] {
10291031
return THROW_ERR_OUT_OF_RANGE(env, "oaepLabel is too big");
10301032
}
1033+
1034+
Digest mgf1_digest;
1035+
if (args[offset + 4]->IsString()) {
1036+
Utf8Value mgf1_str(env->isolate(), args[offset + 4]);
1037+
mgf1_digest = Digest::FromName(*mgf1_str);
1038+
if (!mgf1_digest) return THROW_ERR_OSSL_EVP_INVALID_DIGEST(env);
1039+
}
1040+
10311041
std::unique_ptr<BackingStore> out;
1032-
if (!Cipher<cipher>(env, pkey, padding, digest, oaep_label, buf, &out)) {
1042+
if (!Cipher<cipher>(
1043+
env, pkey, padding, digest, mgf1_digest, oaep_label, buf, &out)) {
10331044
return ThrowCryptoError(env, ERR_get_error());
10341045
}
10351046

‎src/crypto/crypto_cipher.h‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,7 @@ class PublicKeyCipher {
113113
const ncrypto::EVPKeyPointer& pkey,
114114
int padding,
115115
const ncrypto::Digest& digest,
116+
const ncrypto::Digest& mgf1_digest,
116117
const ArrayBufferOrViewContents<unsigned char>& oaep_label,
117118
const ArrayBufferOrViewContents<unsigned char>& data,
118119
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
@@ -220,6 +220,7 @@ WebCryptoCipherStatus RSA_Cipher(Environment* env,
220220
const ncrypto::Rsa::CipherParams nparams{
221221
.padding = params.padding,
222222
.digest = params.digest,
223+
.mgf1_digest = params.digest,
223224
.label = params.label,
224225
};
225226

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
@@ -797,6 +797,7 @@ declare namespace InternalCryptoBinding {
797797
padding: number,
798798
oaepHash: string | undefined,
799799
oaepLabel: OptionalByteSource,
800+
mgf1Hash: string | undefined,
800801
]
801802
) => Buffer;
802803
}

0 commit comments

Comments
 (0)