Commit af867ce

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 66ee479 commit af867ce

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
structCipherParams {
509509
int padding;
510510
Digest digest;
511+
Digest mgf1_digest;
511512
const Buffer<constvoid> 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
constpadding=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
returnmethod(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<unsignedchar>& oaep_label,
805806
const ArrayBufferOrViewContents<unsignedchar>& 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
returnTHROW_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) returnTHROW_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
returnThrowCryptoError(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<unsignedchar>& oaep_label,
110111
const ArrayBufferOrViewContents<unsignedchar>& 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+
constcommon=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+
constassert=require('assert');
13+
constcrypto=require('crypto');
14+
constfixtures=require('../common/fixtures');
15+
const{ hasFIPS }=require('../common/crypto');
16+
17+
constconstants=crypto.constants;
18+
19+
constpublicKey=fixtures.readKey('rsa_public.pem','ascii');
20+
constprivateKey=fixtures.readKey('rsa_private.pem','ascii');
21+
22+
constinput=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+
constencrypted=crypto.publicEncrypt({
28+
key: publicKey,
29+
padding: constants.RSA_PKCS1_OAEP_PADDING,
30+
oaepHash: 'sha256',
31+
mgf1Hash: 'sha1',
32+
},input);
33+
34+
constdecrypted=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+
constencrypted=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+
constencrypted=crypto.publicEncrypt({
73+
key: publicKey,
74+
padding: constants.RSA_PKCS1_OAEP_PADDING,
75+
oaepHash: 'sha256',
76+
},input);
77+
78+
constdecrypted=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+
constencrypted=crypto.publicEncrypt({
93+
key: publicKey,
94+
padding: constants.RSA_PKCS1_OAEP_PADDING,
95+
},input);
96+
97+
constdecrypted=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+
constencrypted=crypto.publicEncrypt({
113+
key: publicKey,
114+
padding: constants.RSA_PKCS1_OAEP_PADDING,
115+
oaepHash,
116+
mgf1Hash,
117+
},input);
118+
119+
constdecrypted=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(constmgf1Hashof[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)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Commit af867ce

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 66ee479 commit af867ce

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
structCipherParams {
509509
int padding;
510510
Digest digest;
511+
Digest mgf1_digest;
511512
const Buffer<constvoid> 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
constpadding=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
returnmethod(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<unsignedchar>& oaep_label,
805806
const ArrayBufferOrViewContents<unsignedchar>& 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
returnTHROW_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) returnTHROW_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
returnThrowCryptoError(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<unsignedchar>& oaep_label,
110111
const ArrayBufferOrViewContents<unsignedchar>& 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+
constcommon=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+
constassert=require('assert');
13+
constcrypto=require('crypto');
14+
constfixtures=require('../common/fixtures');
15+
const{ hasFIPS }=require('../common/crypto');
16+
17+
constconstants=crypto.constants;
18+
19+
constpublicKey=fixtures.readKey('rsa_public.pem','ascii');
20+
constprivateKey=fixtures.readKey('rsa_private.pem','ascii');
21+
22+
constinput=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+
constencrypted=crypto.publicEncrypt({
28+
key: publicKey,
29+
padding: constants.RSA_PKCS1_OAEP_PADDING,
30+
oaepHash: 'sha256',
31+
mgf1Hash: 'sha1',
32+
},input);
33+
34+
constdecrypted=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+
constencrypted=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+
constencrypted=crypto.publicEncrypt({
73+
key: publicKey,
74+
padding: constants.RSA_PKCS1_OAEP_PADDING,
75+
oaepHash: 'sha256',
76+
},input);
77+
78+
constdecrypted=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+
constencrypted=crypto.publicEncrypt({
93+
key: publicKey,
94+
padding: constants.RSA_PKCS1_OAEP_PADDING,
95+
},input);
96+
97+
constdecrypted=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+
constencrypted=crypto.publicEncrypt({
113+
key: publicKey,
114+
padding: constants.RSA_PKCS1_OAEP_PADDING,
115+
oaepHash,
116+
mgf1Hash,
117+
},input);
118+
119+
constdecrypted=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(constmgf1Hashof[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)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit af867ce

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 66ee479 commit af867ce

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
structCipherParams {
509509
int padding;
510510
Digest digest;
511+
Digest mgf1_digest;
511512
const Buffer<constvoid> 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
constpadding=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
returnmethod(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<unsignedchar>& oaep_label,
805806
const ArrayBufferOrViewContents<unsignedchar>& 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
returnTHROW_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) returnTHROW_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
returnThrowCryptoError(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<unsignedchar>& oaep_label,
110111
const ArrayBufferOrViewContents<unsignedchar>& 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+
constcommon=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+
constassert=require('assert');
13+
constcrypto=require('crypto');
14+
constfixtures=require('../common/fixtures');
15+
const{ hasFIPS }=require('../common/crypto');
16+
17+
constconstants=crypto.constants;
18+
19+
constpublicKey=fixtures.readKey('rsa_public.pem','ascii');
20+
constprivateKey=fixtures.readKey('rsa_private.pem','ascii');
21+
22+
constinput=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+
constencrypted=crypto.publicEncrypt({
28+
key: publicKey,
29+
padding: constants.RSA_PKCS1_OAEP_PADDING,
30+
oaepHash: 'sha256',
31+
mgf1Hash: 'sha1',
32+
},input);
33+
34+
constdecrypted=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+
constencrypted=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+
constencrypted=crypto.publicEncrypt({
73+
key: publicKey,
74+
padding: constants.RSA_PKCS1_OAEP_PADDING,
75+
oaepHash: 'sha256',
76+
},input);
77+
78+
constdecrypted=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+
constencrypted=crypto.publicEncrypt({
93+
key: publicKey,
94+
padding: constants.RSA_PKCS1_OAEP_PADDING,
95+
},input);
96+
97+
constdecrypted=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+
constencrypted=crypto.publicEncrypt({
113+
key: publicKey,
114+
padding: constants.RSA_PKCS1_OAEP_PADDING,
115+
oaepHash,
116+
mgf1Hash,
117+
},input);
118+
119+
constdecrypted=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(constmgf1Hashof[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)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit af867ce

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 66ee479 commit af867ce

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
structCipherParams {
509509
int padding;
510510
Digest digest;
511+
Digest mgf1_digest;
511512
const Buffer<constvoid> 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
constpadding=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
returnmethod(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<unsignedchar>& oaep_label,
805806
const ArrayBufferOrViewContents<unsignedchar>& 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
returnTHROW_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) returnTHROW_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
returnThrowCryptoError(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<unsignedchar>& oaep_label,
110111
const ArrayBufferOrViewContents<unsignedchar>& 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+
constcommon=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+
constassert=require('assert');
13+
constcrypto=require('crypto');
14+
constfixtures=require('../common/fixtures');
15+
const{ hasFIPS }=require('../common/crypto');
16+
17+
constconstants=crypto.constants;
18+
19+
constpublicKey=fixtures.readKey('rsa_public.pem','ascii');
20+
constprivateKey=fixtures.readKey('rsa_private.pem','ascii');
21+
22+
constinput=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+
constencrypted=crypto.publicEncrypt({
28+
key: publicKey,
29+
padding: constants.RSA_PKCS1_OAEP_PADDING,
30+
oaepHash: 'sha256',
31+
mgf1Hash: 'sha1',
32+
},input);
33+
34+
constdecrypted=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+
constencrypted=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+
constencrypted=crypto.publicEncrypt({
73+
key: publicKey,
74+
padding: constants.RSA_PKCS1_OAEP_PADDING,
75+
oaepHash: 'sha256',
76+
},input);
77+
78+
constdecrypted=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+
constencrypted=crypto.publicEncrypt({
93+
key: publicKey,
94+
padding: constants.RSA_PKCS1_OAEP_PADDING,
95+
},input);
96+
97+
constdecrypted=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+
constencrypted=crypto.publicEncrypt({
113+
key: publicKey,
114+
padding: constants.RSA_PKCS1_OAEP_PADDING,
115+
oaepHash,
116+
mgf1Hash,
117+
},input);
118+
119+
constdecrypted=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(constmgf1Hashof[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)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Commit af867ce

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 66ee479 commit af867ce

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
structCipherParams {
509509
int padding;
510510
Digest digest;
511+
Digest mgf1_digest;
511512
const Buffer<constvoid> 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
constpadding=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
returnmethod(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<unsignedchar>& oaep_label,
805806
const ArrayBufferOrViewContents<unsignedchar>& 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
returnTHROW_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) returnTHROW_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
returnThrowCryptoError(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<unsignedchar>& oaep_label,
110111
const ArrayBufferOrViewContents<unsignedchar>& 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+
constcommon=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+
constassert=require('assert');
13+
constcrypto=require('crypto');
14+
constfixtures=require('../common/fixtures');
15+
const{ hasFIPS }=require('../common/crypto');
16+
17+
constconstants=crypto.constants;
18+
19+
constpublicKey=fixtures.readKey('rsa_public.pem','ascii');
20+
constprivateKey=fixtures.readKey('rsa_private.pem','ascii');
21+
22+
constinput=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+
constencrypted=crypto.publicEncrypt({
28+
key: publicKey,
29+
padding: constants.RSA_PKCS1_OAEP_PADDING,
30+
oaepHash: 'sha256',
31+
mgf1Hash: 'sha1',
32+
},input);
33+
34+
constdecrypted=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+
constencrypted=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+
constencrypted=crypto.publicEncrypt({
73+
key: publicKey,
74+
padding: constants.RSA_PKCS1_OAEP_PADDING,
75+
oaepHash: 'sha256',
76+
},input);
77+
78+
constdecrypted=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+
constencrypted=crypto.publicEncrypt({
93+
key: publicKey,
94+
padding: constants.RSA_PKCS1_OAEP_PADDING,
95+
},input);
96+
97+
constdecrypted=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+
constencrypted=crypto.publicEncrypt({
113+
key: publicKey,
114+
padding: constants.RSA_PKCS1_OAEP_PADDING,
115+
oaepHash,
116+
mgf1Hash,
117+
},input);
118+
119+
constdecrypted=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(constmgf1Hashof[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)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit af867ce

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 66ee479 commit af867ce

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
structCipherParams {
509509
int padding;
510510
Digest digest;
511+
Digest mgf1_digest;
511512
const Buffer<constvoid> 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
constpadding=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
returnmethod(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<unsignedchar>& oaep_label,
805806
const ArrayBufferOrViewContents<unsignedchar>& 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
returnTHROW_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) returnTHROW_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
returnThrowCryptoError(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<unsignedchar>& oaep_label,
110111
const ArrayBufferOrViewContents<unsignedchar>& 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+
constcommon=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+
constassert=require('assert');
13+
constcrypto=require('crypto');
14+
constfixtures=require('../common/fixtures');
15+
const{ hasFIPS }=require('../common/crypto');
16+
17+
constconstants=crypto.constants;
18+
19+
constpublicKey=fixtures.readKey('rsa_public.pem','ascii');
20+
constprivateKey=fixtures.readKey('rsa_private.pem','ascii');
21+
22+
constinput=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+
constencrypted=crypto.publicEncrypt({
28+
key: publicKey,
29+
padding: constants.RSA_PKCS1_OAEP_PADDING,
30+
oaepHash: 'sha256',
31+
mgf1Hash: 'sha1',
32+
},input);
33+
34+
constdecrypted=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+
constencrypted=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+
constencrypted=crypto.publicEncrypt({
73+
key: publicKey,
74+
padding: constants.RSA_PKCS1_OAEP_PADDING,
75+
oaepHash: 'sha256',
76+
},input);
77+
78+
constdecrypted=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+
constencrypted=crypto.publicEncrypt({
93+
key: publicKey,
94+
padding: constants.RSA_PKCS1_OAEP_PADDING,
95+
},input);
96+
97+
constdecrypted=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+
constencrypted=crypto.publicEncrypt({
113+
key: publicKey,
114+
padding: constants.RSA_PKCS1_OAEP_PADDING,
115+
oaepHash,
116+
mgf1Hash,
117+
},input);
118+
119+
constdecrypted=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(constmgf1Hashof[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)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit af867ce

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 66ee479 commit af867ce

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
structCipherParams {
509509
int padding;
510510
Digest digest;
511+
Digest mgf1_digest;
511512
const Buffer<constvoid> 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
constpadding=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
returnmethod(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<unsignedchar>& oaep_label,
805806
const ArrayBufferOrViewContents<unsignedchar>& 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
returnTHROW_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) returnTHROW_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
returnThrowCryptoError(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<unsignedchar>& oaep_label,
110111
const ArrayBufferOrViewContents<unsignedchar>& 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+
constcommon=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+
constassert=require('assert');
13+
constcrypto=require('crypto');
14+
constfixtures=require('../common/fixtures');
15+
const{ hasFIPS }=require('../common/crypto');
16+
17+
constconstants=crypto.constants;
18+
19+
constpublicKey=fixtures.readKey('rsa_public.pem','ascii');
20+
constprivateKey=fixtures.readKey('rsa_private.pem','ascii');
21+
22+
constinput=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+
constencrypted=crypto.publicEncrypt({
28+
key: publicKey,
29+
padding: constants.RSA_PKCS1_OAEP_PADDING,
30+
oaepHash: 'sha256',
31+
mgf1Hash: 'sha1',
32+
},input);
33+
34+
constdecrypted=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+
constencrypted=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+
constencrypted=crypto.publicEncrypt({
73+
key: publicKey,
74+
padding: constants.RSA_PKCS1_OAEP_PADDING,
75+
oaepHash: 'sha256',
76+
},input);
77+
78+
constdecrypted=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+
constencrypted=crypto.publicEncrypt({
93+
key: publicKey,
94+
padding: constants.RSA_PKCS1_OAEP_PADDING,
95+
},input);
96+
97+
constdecrypted=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+
constencrypted=crypto.publicEncrypt({
113+
key: publicKey,
114+
padding: constants.RSA_PKCS1_OAEP_PADDING,
115+
oaepHash,
116+
mgf1Hash,
117+
},input);
118+
119+
constdecrypted=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(constmgf1Hashof[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)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Commit af867ce

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 66ee479 commit af867ce

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
structCipherParams {
509509
int padding;
510510
Digest digest;
511+
Digest mgf1_digest;
511512
const Buffer<constvoid> 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
constpadding=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
returnmethod(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<unsignedchar>& oaep_label,
805806
const ArrayBufferOrViewContents<unsignedchar>& 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
returnTHROW_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) returnTHROW_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
returnThrowCryptoError(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<unsignedchar>& oaep_label,
110111
const ArrayBufferOrViewContents<unsignedchar>& 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+
constcommon=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+
constassert=require('assert');
13+
constcrypto=require('crypto');
14+
constfixtures=require('../common/fixtures');
15+
const{ hasFIPS }=require('../common/crypto');
16+
17+
constconstants=crypto.constants;
18+
19+
constpublicKey=fixtures.readKey('rsa_public.pem','ascii');
20+
constprivateKey=fixtures.readKey('rsa_private.pem','ascii');
21+
22+
constinput=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+
constencrypted=crypto.publicEncrypt({
28+
key: publicKey,
29+
padding: constants.RSA_PKCS1_OAEP_PADDING,
30+
oaepHash: 'sha256',
31+
mgf1Hash: 'sha1',
32+
},input);
33+
34+
constdecrypted=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+
constencrypted=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+
constencrypted=crypto.publicEncrypt({
73+
key: publicKey,
74+
padding: constants.RSA_PKCS1_OAEP_PADDING,
75+
oaepHash: 'sha256',
76+
},input);
77+
78+
constdecrypted=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+
constencrypted=crypto.publicEncrypt({
93+
key: publicKey,
94+
padding: constants.RSA_PKCS1_OAEP_PADDING,
95+
},input);
96+
97+
constdecrypted=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+
constencrypted=crypto.publicEncrypt({
113+
key: publicKey,
114+
padding: constants.RSA_PKCS1_OAEP_PADDING,
115+
oaepHash,
116+
mgf1Hash,
117+
},input);
118+
119+
constdecrypted=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(constmgf1Hashof[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)