From 1604caf56b8ca33420af07f0b8c4fefce458b49e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tobias=20Nie=C3=9Fen?= Date: Sun, 13 Aug 2023 17:13:25 +0000 Subject: [PATCH] crypto: remove default encoding from sign/verify getDefaultEncoding() always returns 'buffer' in Node.js 20. It requires some careful justification but the default encoding can be eliminated from sig.js entirely. In Sign.prototype.update, we can safely remove the conditional assignment of getDefaultEncoding() to encoding. This is because SignUpdate() in crypto_sig.cc internally calls node::crypto::Decode, which returns UTF8 for falsy encoding values. In other words, with the conditional assignment, StringBytes::Write() ultimately receives the encoding BUFFER, and without the conditional assignment, it receives the encoding UTF8. However, StringBytes::Write() treats both encodings identically, so there is no need to deviate from the internal default encoding UTF8. In Sign.prototype.sign, we can also safely remove the conditional assignment of getDefaultEncoding() to encoding. Whether encoding is falsy or 'buffer' makes no difference. In Verify.prototype.verify, we can also safely remove the conditional assignment of getDefaultEncoding() to sigEncoding. This is because the function passes the sigEncoding to getArrayBufferOrView(), which passes it to Buffer.from(). If sigEncoding is 'buffer', getArrayBufferOrView() instead passes 'utf8' to Buffer.from(). Because the default encoding of Buffer.from() is 'utf8', passing a falsy encoding to getArrayBufferOrView() instead of 'buffer' results in the same behavior. Refs: https://github.com/nodejs/node/pull/47182 --- lib/internal/crypto/sig.js | 6 ------ 1 file changed, 6 deletions(-) diff --git a/lib/internal/crypto/sig.js b/lib/internal/crypto/sig.js index 71e8fbadaa84d7..9b3895646c7929 100644 --- a/lib/internal/crypto/sig.js +++ b/lib/internal/crypto/sig.js @@ -34,7 +34,6 @@ const { const { getArrayBufferOrView, - getDefaultEncoding, kHandle, } = require('internal/crypto/util'); @@ -70,8 +69,6 @@ Sign.prototype._write = function _write(chunk, encoding, callback) { }; Sign.prototype.update = function update(data, encoding) { - encoding = encoding || getDefaultEncoding(); - if (typeof data === 'string') { validateEncoding(data, encoding); } else if (!isArrayBufferView(data)) { @@ -131,7 +128,6 @@ Sign.prototype.sign = function sign(options, encoding) { const ret = this[kHandle].sign(data, format, type, passphrase, rsaPadding, pssSaltLength, dsaSigEnc); - encoding = encoding || getDefaultEncoding(); if (encoding && encoding !== 'buffer') return ret.toString(encoding); @@ -216,8 +212,6 @@ Verify.prototype.verify = function verify(options, signature, sigEncoding) { passphrase, } = preparePublicOrPrivateKey(options, true); - sigEncoding = sigEncoding || getDefaultEncoding(); - // Options specific to RSA const rsaPadding = getPadding(options); const pssSaltLength = getSaltLength(options);