Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 1872cc6

Browse files
committedJan 27, 2025·
src: cleanup more of crypto/ncrypto
1 parent 5843486 commit 1872cc6

15 files changed

+368
-351
lines changed
 

‎deps/ncrypto/ncrypto.cc

+45-2
Original file line numberDiff line numberDiff line change
@@ -2402,6 +2402,15 @@ EVPKeyPointer::operator Rsa() const {
24022402
return Rsa(rsa);
24032403
}
24042404

2405+
EVPKeyPointer::operator Dsa() const {
2406+
int type = id();
2407+
if (type != EVP_PKEY_DSA) return {};
2408+
2409+
OSSL3_CONST DSA* dsa = EVP_PKEY_get0_DSA(get());
2410+
if (dsa == nullptr) return {};
2411+
return Dsa(dsa);
2412+
}
2413+
24052414
bool EVPKeyPointer::validateDsaParameters() const {
24062415
if (!pkey_) return false;
24072416
/* Validate DSA2 parameters from FIPS 186-4 */
@@ -2660,8 +2669,8 @@ bool SSLCtxPointer::setGroups(const char* groups) {
26602669

26612670
// ============================================================================
26622671

2663-
const Cipher Cipher::FromName(const char* name) {
2664-
return Cipher(EVP_get_cipherbyname(name));
2672+
const Cipher Cipher::FromName(std::string_view name) {
2673+
return Cipher(EVP_get_cipherbyname(name.data()));
26652674
}
26662675

26672676
const Cipher Cipher::FromNid(int nid) {
@@ -2748,6 +2757,10 @@ bool Cipher::isSupportedAuthenticatedMode() const {
27482757
}
27492758
}
27502759

2760+
bool Cipher::IsValidGCMTagLength(unsigned int tag_len) {
2761+
return tag_len == 4 || tag_len == 8 || (tag_len >= 12 && tag_len <= 16);
2762+
}
2763+
27512764
// ============================================================================
27522765

27532766
CipherCtxPointer CipherCtxPointer::New() {
@@ -3902,4 +3915,34 @@ std::pair<std::string, std::string> X509Name::Iterator::operator*() const {
39023915
std::string(reinterpret_cast<const char*>(value_str), value_str_size)};
39033916
}
39043917

3918+
// ============================================================================
3919+
3920+
Dsa::Dsa() : dsa_(nullptr) {}
3921+
3922+
Dsa::Dsa(OSSL3_CONST DSA* dsa) : dsa_(dsa) {}
3923+
3924+
const BIGNUM* Dsa::getP() const {
3925+
if (dsa_ == nullptr) return nullptr;
3926+
const BIGNUM* p;
3927+
DSA_get0_pqg(dsa_, &p, nullptr, nullptr);
3928+
return p;
3929+
}
3930+
3931+
const BIGNUM* Dsa::getQ() const {
3932+
if (dsa_ == nullptr) return nullptr;
3933+
const BIGNUM* q;
3934+
DSA_get0_pqg(dsa_, nullptr, &q, nullptr);
3935+
return q;
3936+
}
3937+
3938+
size_t Dsa::getModulusLength() const {
3939+
if (dsa_ == nullptr) return 0;
3940+
return BignumPointer::GetBitCount(getP());
3941+
}
3942+
3943+
size_t Dsa::getDivisorLength() const {
3944+
if (dsa_ == nullptr) return 0;
3945+
return BignumPointer::GetBitCount(getQ());
3946+
}
3947+
39053948
} // namespace ncrypto

‎deps/ncrypto/ncrypto.h

+26-1
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,7 @@ class ECDSASigPointer;
221221
class ECGroupPointer;
222222
class ECPointPointer;
223223
class ECKeyPointer;
224+
class Dsa;
224225
class Rsa;
225226
class Ec;
226227

@@ -267,7 +268,7 @@ class Cipher final {
267268

268269
bool isSupportedAuthenticatedMode() const;
269270

270-
static const Cipher FromName(const char* name);
271+
static const Cipher FromName(std::string_view name);
271272
static const Cipher FromNid(int nid);
272273
static const Cipher FromCtx(const CipherCtxPointer& ctx);
273274

@@ -292,10 +293,33 @@ class Cipher final {
292293
const CipherParams& params,
293294
const Buffer<const void> in);
294295

296+
static bool IsValidGCMTagLength(unsigned int tag_len);
297+
295298
private:
296299
const EVP_CIPHER* cipher_ = nullptr;
297300
};
298301

302+
// ============================================================================
303+
// DSA
304+
305+
class Dsa final {
306+
public:
307+
Dsa();
308+
Dsa(OSSL3_CONST DSA* dsa);
309+
NCRYPTO_DISALLOW_COPY_AND_MOVE(Dsa)
310+
311+
inline operator bool() const { return dsa_ != nullptr; }
312+
inline operator OSSL3_CONST DSA*() const { return dsa_; }
313+
314+
const BIGNUM* getP() const;
315+
const BIGNUM* getQ() const;
316+
size_t getModulusLength() const;
317+
size_t getDivisorLength() const;
318+
319+
private:
320+
OSSL3_CONST DSA* dsa_;
321+
};
322+
299323
// ============================================================================
300324
// RSA
301325

@@ -767,6 +791,7 @@ class EVPKeyPointer final {
767791
std::optional<uint32_t> getBytesOfRS() const;
768792
int getDefaultSignPadding() const;
769793
operator Rsa() const;
794+
operator Dsa() const;
770795

771796
bool isRsaVariant() const;
772797
bool isOneShotVariant() const;

‎src/crypto/crypto_cipher.cc

+68-56
Original file line numberDiff line numberDiff line change
@@ -35,10 +35,6 @@ using v8::Value;
3535

3636
namespace crypto {
3737
namespace {
38-
bool IsValidGCMTagLength(unsigned int tag_len) {
39-
return tag_len == 4 || tag_len == 8 || (tag_len >= 12 && tag_len <= 16);
40-
}
41-
4238
// Collects and returns information on the given cipher
4339
void GetCipherInfo(const FunctionCallbackInfo<Value>& args) {
4440
Environment* env = Environment::GetCurrent(args);
@@ -50,7 +46,7 @@ void GetCipherInfo(const FunctionCallbackInfo<Value>& args) {
5046
const auto cipher = ([&] {
5147
if (args[1]->IsString()) {
5248
Utf8Value name(env->isolate(), args[1]);
53-
return Cipher::FromName(*name);
49+
return Cipher::FromName(name.ToStringView());
5450
} else {
5551
int nid = args[1].As<Int32>()->Value();
5652
return Cipher::FromNid(nid);
@@ -166,16 +162,19 @@ void GetCipherInfo(const FunctionCallbackInfo<Value>& args) {
166162
} // namespace
167163

168164
void CipherBase::GetSSLCiphers(const FunctionCallbackInfo<Value>& args) {
165+
MarkPopErrorOnReturn mark_pop_error_on_return;
169166
Environment* env = Environment::GetCurrent(args);
170167

171168
auto ctx = SSLCtxPointer::New();
172169
if (!ctx) {
173-
return ThrowCryptoError(env, ERR_get_error(), "SSL_CTX_new");
170+
return ThrowCryptoError(
171+
env, mark_pop_error_on_return.peekError(), "SSL_CTX_new");
174172
}
175173

176174
auto ssl = SSLPointer::New(ctx);
177175
if (!ssl) {
178-
return ThrowCryptoError(env, ERR_get_error(), "SSL_new");
176+
return ThrowCryptoError(
177+
env, mark_pop_error_on_return.peekError(), "SSL_new");
179178
}
180179

181180
LocalVector<Value> arr(env->isolate());
@@ -309,6 +308,7 @@ void CipherBase::CommonInit(const char* cipher_type,
309308
const unsigned char* iv,
310309
int iv_len,
311310
unsigned int auth_tag_len) {
311+
MarkPopErrorOnReturn mark_pop_error_on_return;
312312
CHECK(!ctx_);
313313
ctx_ = CipherCtxPointer::New();
314314
CHECK(ctx_);
@@ -319,14 +319,16 @@ void CipherBase::CommonInit(const char* cipher_type,
319319

320320
const bool encrypt = (kind_ == kCipher);
321321
if (!ctx_.init(cipher, encrypt)) {
322-
return ThrowCryptoError(env(), ERR_get_error(),
322+
return ThrowCryptoError(env(),
323+
mark_pop_error_on_return.peekError(),
323324
"Failed to initialize cipher");
324325
}
325326

326327
if (cipher.isSupportedAuthenticatedMode()) {
327328
CHECK_GE(iv_len, 0);
328-
if (!InitAuthenticated(cipher_type, iv_len, auth_tag_len))
329+
if (!InitAuthenticated(cipher_type, iv_len, auth_tag_len)) {
329330
return;
331+
}
330332
}
331333

332334
if (!ctx_.setKeyLength(key_len)) {
@@ -335,7 +337,8 @@ void CipherBase::CommonInit(const char* cipher_type,
335337
}
336338

337339
if (!ctx_.init(Cipher(), encrypt, key, iv)) {
338-
return ThrowCryptoError(env(), ERR_get_error(),
340+
return ThrowCryptoError(env(),
341+
mark_pop_error_on_return.peekError(),
339342
"Failed to initialize cipher");
340343
}
341344
}
@@ -422,8 +425,9 @@ void CipherBase::InitIv(const char* cipher_type,
422425
const bool has_iv = iv_buf.size() > 0;
423426

424427
// Throw if no IV was passed and the cipher requires an IV
425-
if (!has_iv && expected_iv_len != 0)
428+
if (!has_iv && expected_iv_len != 0) {
426429
return THROW_ERR_CRYPTO_INVALID_IV(env());
430+
}
427431

428432
// Throw if an IV was passed which does not match the cipher's fixed IV length
429433
// static_cast<int> for the iv_buf.size() is safe because we've verified
@@ -438,8 +442,9 @@ void CipherBase::InitIv(const char* cipher_type,
438442
// Check for invalid IV lengths, since OpenSSL does not under some
439443
// conditions:
440444
// https://www.openssl.org/news/secadv/20190306.txt.
441-
if (iv_buf.size() > 12)
445+
if (iv_buf.size() > 12) {
442446
return THROW_ERR_CRYPTO_INVALID_IV(env());
447+
}
443448
}
444449

445450
CommonInit(
@@ -504,7 +509,7 @@ bool CipherBase::InitAuthenticated(
504509
const int mode = ctx_.getMode();
505510
if (mode == EVP_CIPH_GCM_MODE) {
506511
if (auth_tag_len != kNoAuthTagLength) {
507-
if (!IsValidGCMTagLength(auth_tag_len)) {
512+
if (!Cipher::IsValidGCMTagLength(auth_tag_len)) {
508513
THROW_ERR_CRYPTO_INVALID_AUTH_TAG(
509514
env(),
510515
"Invalid authentication tag length: %u",
@@ -595,9 +600,11 @@ void CipherBase::GetAuthTag(const FunctionCallbackInfo<Value>& args) {
595600
return;
596601
}
597602

598-
args.GetReturnValue().Set(
599-
Buffer::Copy(env, cipher->auth_tag_, cipher->auth_tag_len_)
600-
.FromMaybe(Local<Value>()));
603+
Local<Value> ret;
604+
if (Buffer::Copy(env, cipher->auth_tag_, cipher->auth_tag_len_)
605+
.ToLocal(&ret)) {
606+
args.GetReturnValue().Set(ret);
607+
}
601608
}
602609

603610
void CipherBase::SetAuthTag(const FunctionCallbackInfo<Value>& args) {
@@ -624,7 +631,7 @@ void CipherBase::SetAuthTag(const FunctionCallbackInfo<Value>& args) {
624631
// Restrict GCM tag lengths according to NIST 800-38d, page 9.
625632
is_valid = (cipher->auth_tag_len_ == kNoAuthTagLength ||
626633
cipher->auth_tag_len_ == tag_len) &&
627-
IsValidGCMTagLength(tag_len);
634+
Cipher::IsValidGCMTagLength(tag_len);
628635
} else {
629636
// At this point, the tag length is already known and must match the
630637
// length of the given authentication tag.
@@ -693,12 +700,12 @@ bool CipherBase::SetAAD(
693700
return false;
694701
}
695702

696-
if (!CheckCCMMessageLength(plaintext_len))
703+
if (!CheckCCMMessageLength(plaintext_len)) {
697704
return false;
705+
}
698706

699-
if (kind_ == kDecipher) {
700-
if (!MaybePassAuthTagToOpenSSL())
701-
return false;
707+
if (kind_ == kDecipher && !MaybePassAuthTagToOpenSSL()) {
708+
return false;
702709
}
703710

704711
ncrypto::Buffer<const unsigned char> buffer{
@@ -738,19 +745,20 @@ CipherBase::UpdateResult CipherBase::Update(
738745
const char* data,
739746
size_t len,
740747
std::unique_ptr<BackingStore>* out) {
741-
if (!ctx_ || len > INT_MAX)
742-
return kErrorState;
748+
if (!ctx_ || len > INT_MAX) return kErrorState;
743749
MarkPopErrorOnReturn mark_pop_error_on_return;
744750

745751
const int mode = ctx_.getMode();
746752

747-
if (mode == EVP_CIPH_CCM_MODE && !CheckCCMMessageLength(len))
753+
if (mode == EVP_CIPH_CCM_MODE && !CheckCCMMessageLength(len)) {
748754
return kErrorMessageSize;
755+
}
749756

750757
// Pass the authentication tag to OpenSSL if possible. This will only happen
751758
// once, usually on the first update.
752-
if (kind_ == kDecipher && IsAuthenticatedMode())
759+
if (kind_ == kDecipher && IsAuthenticatedMode()) {
753760
CHECK(MaybePassAuthTagToOpenSSL());
761+
}
754762

755763
const int block_size = ctx_.getBlockSize();
756764
CHECK_GT(block_size, 0);
@@ -800,34 +808,38 @@ CipherBase::UpdateResult CipherBase::Update(
800808
}
801809

802810
void CipherBase::Update(const FunctionCallbackInfo<Value>& args) {
803-
Decode<CipherBase>(args, [](CipherBase* cipher,
804-
const FunctionCallbackInfo<Value>& args,
805-
const char* data, size_t size) {
806-
std::unique_ptr<BackingStore> out;
807-
Environment* env = Environment::GetCurrent(args);
808-
809-
if (size > INT_MAX) [[unlikely]] {
810-
return THROW_ERR_OUT_OF_RANGE(env, "data is too long");
811-
}
812-
UpdateResult r = cipher->Update(data, size, &out);
813-
814-
if (r != kSuccess) {
815-
if (r == kErrorState) {
816-
ThrowCryptoError(env, ERR_get_error(),
817-
"Trying to add data in unsupported state");
818-
}
819-
return;
820-
}
811+
Decode<CipherBase>(
812+
args,
813+
[](CipherBase* cipher,
814+
const FunctionCallbackInfo<Value>& args,
815+
const char* data,
816+
size_t size) {
817+
MarkPopErrorOnReturn mark_pop_error_on_return;
818+
std::unique_ptr<BackingStore> out;
819+
Environment* env = Environment::GetCurrent(args);
820+
821+
if (size > INT_MAX) [[unlikely]] {
822+
return THROW_ERR_OUT_OF_RANGE(env, "data is too long");
823+
}
824+
UpdateResult r = cipher->Update(data, size, &out);
825+
826+
if (r != kSuccess) {
827+
if (r == kErrorState) {
828+
ThrowCryptoError(env,
829+
mark_pop_error_on_return.peekError(),
830+
"Trying to add data in unsupported state");
831+
}
832+
return;
833+
}
821834

822-
Local<ArrayBuffer> ab = ArrayBuffer::New(env->isolate(), std::move(out));
823-
args.GetReturnValue().Set(
824-
Buffer::New(env, ab, 0, ab->ByteLength()).FromMaybe(Local<Value>()));
825-
});
835+
auto ab = ArrayBuffer::New(env->isolate(), std::move(out));
836+
args.GetReturnValue().Set(Buffer::New(env, ab, 0, ab->ByteLength())
837+
.FromMaybe(Local<Value>()));
838+
});
826839
}
827840

828841
bool CipherBase::SetAutoPadding(bool auto_padding) {
829-
if (!ctx_)
830-
return false;
842+
if (!ctx_) return false;
831843
MarkPopErrorOnReturn mark_pop_error_on_return;
832844
return ctx_.setPadding(auto_padding);
833845
}
@@ -841,8 +853,7 @@ void CipherBase::SetAutoPadding(const FunctionCallbackInfo<Value>& args) {
841853
}
842854

843855
bool CipherBase::Final(std::unique_ptr<BackingStore>* out) {
844-
if (!ctx_)
845-
return false;
856+
if (!ctx_) return false;
846857

847858
const int mode = ctx_.getMode();
848859

@@ -906,11 +917,13 @@ bool CipherBase::Final(std::unique_ptr<BackingStore>* out) {
906917

907918
void CipherBase::Final(const FunctionCallbackInfo<Value>& args) {
908919
Environment* env = Environment::GetCurrent(args);
920+
MarkPopErrorOnReturn mark_pop_error_on_return;
909921

910922
CipherBase* cipher;
911923
ASSIGN_OR_RETURN_UNWRAP(&cipher, args.This());
912-
if (cipher->ctx_ == nullptr)
924+
if (cipher->ctx_ == nullptr) {
913925
return THROW_ERR_CRYPTO_INVALID_STATE(env);
926+
}
914927

915928
std::unique_ptr<BackingStore> out;
916929

@@ -923,10 +936,10 @@ void CipherBase::Final(const FunctionCallbackInfo<Value>& args) {
923936
? "Unsupported state or unable to authenticate data"
924937
: "Unsupported state";
925938

926-
return ThrowCryptoError(env, ERR_get_error(), msg);
939+
return ThrowCryptoError(env, mark_pop_error_on_return.peekError(), msg);
927940
}
928941

929-
Local<ArrayBuffer> ab = ArrayBuffer::New(env->isolate(), std::move(out));
942+
auto ab = ArrayBuffer::New(env->isolate(), std::move(out));
930943
args.GetReturnValue().Set(
931944
Buffer::New(env, ab, 0, ab->ByteLength()).FromMaybe(Local<Value>()));
932945
}
@@ -974,8 +987,7 @@ void PublicKeyCipher::Cipher(const FunctionCallbackInfo<Value>& args) {
974987
auto data = KeyObjectData::GetPublicOrPrivateKeyFromJs(args, &offset);
975988
if (!data) return;
976989
const auto& pkey = data.GetAsymmetricKey();
977-
if (!pkey)
978-
return;
990+
if (!pkey) return;
979991

980992
ArrayBufferOrViewContents<unsigned char> buf(args[offset]);
981993
if (!buf.CheckSizeInt32()) [[unlikely]] {

‎src/crypto/crypto_dh.cc

+4-4
Original file line numberDiff line numberDiff line change
@@ -524,11 +524,11 @@ bool DHBitsTraits::DeriveBits(
524524
return true;
525525
}
526526

527-
Maybe<void> GetDhKeyDetail(Environment* env,
528-
const KeyObjectData& key,
529-
Local<Object> target) {
527+
bool GetDhKeyDetail(Environment* env,
528+
const KeyObjectData& key,
529+
Local<Object> target) {
530530
CHECK_EQ(key.GetAsymmetricKey().id(), EVP_PKEY_DH);
531-
return JustVoid();
531+
return true;
532532
}
533533

534534
void DiffieHellman::Initialize(Environment* env, Local<Object> target) {

‎src/crypto/crypto_dh.h

+3-3
Original file line numberDiff line numberDiff line change
@@ -115,9 +115,9 @@ struct DHBitsTraits final {
115115

116116
using DHBitsJob = DeriveBitsJob<DHBitsTraits>;
117117

118-
v8::Maybe<void> GetDhKeyDetail(Environment* env,
119-
const KeyObjectData& key,
120-
v8::Local<v8::Object> target);
118+
bool GetDhKeyDetail(Environment* env,
119+
const KeyObjectData& key,
120+
v8::Local<v8::Object> target);
121121

122122
} // namespace crypto
123123
} // namespace node

‎src/crypto/crypto_dsa.cc

+23-37
Original file line numberDiff line numberDiff line change
@@ -14,14 +14,13 @@
1414

1515
namespace node {
1616

17-
using ncrypto::BignumPointer;
17+
using ncrypto::Dsa;
1818
using ncrypto::EVPKeyCtxPointer;
1919
using v8::FunctionCallbackInfo;
2020
using v8::Int32;
2121
using v8::JustVoid;
2222
using v8::Local;
2323
using v8::Maybe;
24-
using v8::Nothing;
2524
using v8::Number;
2625
using v8::Object;
2726
using v8::Uint32;
@@ -106,41 +105,28 @@ WebCryptoKeyExportStatus DSAKeyExportTraits::DoExport(
106105
}
107106
}
108107

109-
Maybe<void> GetDsaKeyDetail(Environment* env,
110-
const KeyObjectData& key,
111-
Local<Object> target) {
112-
const BIGNUM* p; // Modulus length
113-
const BIGNUM* q; // Divisor length
114-
115-
Mutex::ScopedLock lock(key.mutex());
116-
const auto& m_pkey = key.GetAsymmetricKey();
117-
int type = m_pkey.id();
118-
CHECK(type == EVP_PKEY_DSA);
119-
120-
const DSA* dsa = EVP_PKEY_get0_DSA(m_pkey.get());
121-
CHECK_NOT_NULL(dsa);
122-
123-
DSA_get0_pqg(dsa, &p, &q, nullptr);
124-
125-
size_t modulus_length = BignumPointer::GetBitCount(p);
126-
size_t divisor_length = BignumPointer::GetBitCount(q);
127-
128-
if (target
129-
->Set(
130-
env->context(),
131-
env->modulus_length_string(),
132-
Number::New(env->isolate(), static_cast<double>(modulus_length)))
133-
.IsNothing() ||
134-
target
135-
->Set(
136-
env->context(),
137-
env->divisor_length_string(),
138-
Number::New(env->isolate(), static_cast<double>(divisor_length)))
139-
.IsNothing()) {
140-
return Nothing<void>();
141-
}
142-
143-
return JustVoid();
108+
bool GetDsaKeyDetail(Environment* env,
109+
const KeyObjectData& key,
110+
Local<Object> target) {
111+
if (!key) return false;
112+
Dsa dsa = key.GetAsymmetricKey();
113+
if (!dsa) return false;
114+
115+
size_t modulus_length = dsa.getModulusLength();
116+
size_t divisor_length = dsa.getDivisorLength();
117+
118+
return target
119+
->Set(env->context(),
120+
env->modulus_length_string(),
121+
Number::New(env->isolate(),
122+
static_cast<double>(modulus_length)))
123+
.IsJust() &&
124+
target
125+
->Set(env->context(),
126+
env->divisor_length_string(),
127+
Number::New(env->isolate(),
128+
static_cast<double>(divisor_length)))
129+
.IsJust();
144130
}
145131

146132
namespace DSAAlg {

‎src/crypto/crypto_dsa.h

+5-7
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,7 @@
1010
#include "memory_tracker.h"
1111
#include "v8.h"
1212

13-
namespace node {
14-
namespace crypto {
13+
namespace node::crypto {
1514
struct DsaKeyPairParams final : public MemoryRetainer {
1615
unsigned int modulus_bits;
1716
int divisor_bits;
@@ -60,16 +59,15 @@ struct DSAKeyExportTraits final {
6059

6160
using DSAKeyExportJob = KeyExportJob<DSAKeyExportTraits>;
6261

63-
v8::Maybe<void> GetDsaKeyDetail(Environment* env,
64-
const KeyObjectData& key,
65-
v8::Local<v8::Object> target);
62+
bool GetDsaKeyDetail(Environment* env,
63+
const KeyObjectData& key,
64+
v8::Local<v8::Object> target);
6665

6766
namespace DSAAlg {
6867
void Initialize(Environment* env, v8::Local<v8::Object> target);
6968
void RegisterExternalReferences(ExternalReferenceRegistry* registry);
7069
} // namespace DSAAlg
71-
} // namespace crypto
72-
} // namespace node
70+
} // namespace node::crypto
7371

7472
#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
7573
#endif // SRC_CRYPTO_CRYPTO_DSA_H_

‎src/crypto/crypto_ec.cc

+25-30
Original file line numberDiff line numberDiff line change
@@ -697,9 +697,9 @@ WebCryptoKeyExportStatus ECKeyExportTraits::DoExport(
697697
}
698698
}
699699

700-
Maybe<void> ExportJWKEcKey(Environment* env,
701-
const KeyObjectData& key,
702-
Local<Object> target) {
700+
bool ExportJWKEcKey(Environment* env,
701+
const KeyObjectData& key,
702+
Local<Object> target) {
703703
Mutex::ScopedLock lock(key.mutex());
704704
const auto& m_pkey = key.GetAsymmetricKey();
705705
CHECK_EQ(m_pkey.id(), EVP_PKEY_EC);
@@ -720,14 +720,14 @@ Maybe<void> ExportJWKEcKey(Environment* env,
720720
if (!EC_POINT_get_affine_coordinates(group, pub, x.get(), y.get(), nullptr)) {
721721
ThrowCryptoError(env, ERR_get_error(),
722722
"Failed to get elliptic-curve point coordinates");
723-
return Nothing<void>();
723+
return false;
724724
}
725725

726726
if (target->Set(
727727
env->context(),
728728
env->jwk_kty_string(),
729729
env->jwk_ec_string()).IsNothing()) {
730-
return Nothing<void>();
730+
return false;
731731
}
732732

733733
if (SetEncodedValue(
@@ -742,7 +742,7 @@ Maybe<void> ExportJWKEcKey(Environment* env,
742742
env->jwk_y_string(),
743743
y.get(),
744744
degree_bytes).IsNothing()) {
745-
return Nothing<void>();
745+
return false;
746746
}
747747

748748
Local<String> crv_name;
@@ -763,27 +763,28 @@ Maybe<void> ExportJWKEcKey(Environment* env,
763763
default: {
764764
THROW_ERR_CRYPTO_JWK_UNSUPPORTED_CURVE(
765765
env, "Unsupported JWK EC curve: %s.", OBJ_nid2sn(nid));
766-
return Nothing<void>();
766+
return false;
767767
}
768768
}
769769
if (target->Set(
770770
env->context(),
771771
env->jwk_crv_string(),
772772
crv_name).IsNothing()) {
773-
return Nothing<void>();
773+
return false;
774774
}
775775

776776
if (key.GetKeyType() == kKeyTypePrivate) {
777777
auto pvt = ECKeyPointer::GetPrivateKey(ec);
778-
return SetEncodedValue(env, target, env->jwk_d_string(), pvt, degree_bytes);
778+
return SetEncodedValue(env, target, env->jwk_d_string(), pvt, degree_bytes)
779+
.IsJust();
779780
}
780781

781-
return JustVoid();
782+
return true;
782783
}
783784

784-
Maybe<void> ExportJWKEdKey(Environment* env,
785-
const KeyObjectData& key,
786-
Local<Object> target) {
785+
bool ExportJWKEdKey(Environment* env,
786+
const KeyObjectData& key,
787+
Local<Object> target) {
787788
Mutex::ScopedLock lock(key.mutex());
788789
const auto& pkey = key.GetAsymmetricKey();
789790

@@ -820,7 +821,8 @@ Maybe<void> ExportJWKEdKey(Environment* env,
820821
return true;
821822
};
822823

823-
if (target
824+
return !(
825+
target
824826
->Set(env->context(),
825827
env->jwk_crv_string(),
826828
OneByteString(env->isolate(), curve))
@@ -829,11 +831,7 @@ Maybe<void> ExportJWKEdKey(Environment* env,
829831
!trySetKey(env, pkey.rawPrivateKey(), target, env->jwk_d_string())) ||
830832
!trySetKey(env, pkey.rawPublicKey(), target, env->jwk_x_string()) ||
831833
target->Set(env->context(), env->jwk_kty_string(), env->jwk_okp_string())
832-
.IsNothing()) {
833-
return Nothing<void>();
834-
}
835-
836-
return JustVoid();
834+
.IsNothing());
837835
}
838836

839837
KeyObjectData ImportJWKEcKey(Environment* env,
@@ -897,9 +895,9 @@ KeyObjectData ImportJWKEcKey(Environment* env,
897895
return KeyObjectData::CreateAsymmetric(type, std::move(pkey));
898896
}
899897

900-
Maybe<void> GetEcKeyDetail(Environment* env,
901-
const KeyObjectData& key,
902-
Local<Object> target) {
898+
bool GetEcKeyDetail(Environment* env,
899+
const KeyObjectData& key,
900+
Local<Object> target) {
903901
Mutex::ScopedLock lock(key.mutex());
904902
const auto& m_pkey = key.GetAsymmetricKey();
905903
CHECK_EQ(m_pkey.id(), EVP_PKEY_EC);
@@ -910,14 +908,11 @@ Maybe<void> GetEcKeyDetail(Environment* env,
910908
const auto group = ECKeyPointer::GetGroup(ec);
911909
int nid = EC_GROUP_get_curve_name(group);
912910

913-
if (target
914-
->Set(env->context(),
915-
env->named_curve_string(),
916-
OneByteString(env->isolate(), OBJ_nid2sn(nid)))
917-
.IsNothing()) {
918-
return Nothing<void>();
919-
}
920-
return JustVoid();
911+
return target
912+
->Set(env->context(),
913+
env->named_curve_string(),
914+
OneByteString(env->isolate(), OBJ_nid2sn(nid)))
915+
.IsJust();
921916
}
922917

923918
// WebCrypto requires a different format for ECDSA signatures than

‎src/crypto/crypto_ec.h

+9-9
Original file line numberDiff line numberDiff line change
@@ -141,22 +141,22 @@ struct ECKeyExportTraits final {
141141

142142
using ECKeyExportJob = KeyExportJob<ECKeyExportTraits>;
143143

144-
v8::Maybe<void> ExportJWKEcKey(Environment* env,
145-
const KeyObjectData& key,
146-
v8::Local<v8::Object> target);
144+
bool ExportJWKEcKey(Environment* env,
145+
const KeyObjectData& key,
146+
v8::Local<v8::Object> target);
147147

148-
v8::Maybe<void> ExportJWKEdKey(Environment* env,
149-
const KeyObjectData& key,
150-
v8::Local<v8::Object> target);
148+
bool ExportJWKEdKey(Environment* env,
149+
const KeyObjectData& key,
150+
v8::Local<v8::Object> target);
151151

152152
KeyObjectData ImportJWKEcKey(Environment* env,
153153
v8::Local<v8::Object> jwk,
154154
const v8::FunctionCallbackInfo<v8::Value>& args,
155155
unsigned int offset);
156156

157-
v8::Maybe<void> GetEcKeyDetail(Environment* env,
158-
const KeyObjectData& key,
159-
v8::Local<v8::Object> target);
157+
bool GetEcKeyDetail(Environment* env,
158+
const KeyObjectData& key,
159+
v8::Local<v8::Object> target);
160160
} // namespace crypto
161161
} // namespace node
162162

‎src/crypto/crypto_keygen.cc

+3-7
Original file line numberDiff line numberDiff line change
@@ -73,20 +73,17 @@ KeyGenJobStatus SecretKeyGenTraits::DoKeyGen(Environment* env,
7373
SecretKeyGenConfig* params) {
7474
auto bytes = DataPointer::Alloc(params->length);
7575
if (!ncrypto::CSPRNG(static_cast<unsigned char*>(bytes.get()),
76-
params->length))
76+
params->length)) {
7777
return KeyGenJobStatus::FAILED;
78+
}
7879
params->out = ByteSource::Allocated(bytes.release());
7980
return KeyGenJobStatus::OK;
8081
}
8182

8283
MaybeLocal<Value> SecretKeyGenTraits::EncodeKey(Environment* env,
8384
SecretKeyGenConfig* params) {
8485
auto data = KeyObjectData::CreateSecret(std::move(params->out));
85-
Local<Value> ret;
86-
if (!KeyObjectHandle::Create(env, data).ToLocal(&ret)) {
87-
return MaybeLocal<Value>();
88-
}
89-
return ret;
86+
return KeyObjectHandle::Create(env, data).FromMaybe(Local<Value>());
9087
}
9188

9289
namespace Keygen {
@@ -99,7 +96,6 @@ void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
9996
NidKeyPairGenJob::RegisterExternalReferences(registry);
10097
SecretKeyGenJob::RegisterExternalReferences(registry);
10198
}
102-
10399
} // namespace Keygen
104100
} // namespace crypto
105101
} // namespace node

‎src/crypto/crypto_keygen.h

+7-16
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,7 @@
1111
#include "memory_tracker.h"
1212
#include "v8.h"
1313

14-
namespace node {
15-
namespace crypto {
14+
namespace node::crypto {
1615
namespace Keygen {
1716
void Initialize(Environment* env, v8::Local<v8::Object> target);
1817
void RegisterExternalReferences(ExternalReferenceRegistry* registry);
@@ -184,13 +183,11 @@ struct KeyPairGenTraits final {
184183
static v8::MaybeLocal<v8::Value> EncodeKey(Environment* env,
185184
AdditionalParameters* params) {
186185
v8::Local<v8::Value> keys[2];
187-
if (params->key
188-
.ToEncodedPublicKey(env, params->public_key_encoding, &keys[0])
189-
.IsNothing() ||
190-
params->key
191-
.ToEncodedPrivateKey(env, params->private_key_encoding, &keys[1])
192-
.IsNothing()) {
193-
return v8::MaybeLocal<v8::Value>();
186+
if (!params->key.ToEncodedPublicKey(
187+
env, params->public_key_encoding, &keys[0]) ||
188+
!params->key.ToEncodedPrivateKey(
189+
env, params->private_key_encoding, &keys[1])) {
190+
return {};
194191
}
195192
return v8::Array::New(env->isolate(), keys, arraysize(keys));
196193
}
@@ -233,11 +230,6 @@ struct KeyPairGenConfig final : public MemoryRetainer {
233230
AlgorithmParams params;
234231

235232
KeyPairGenConfig() = default;
236-
~KeyPairGenConfig() {
237-
if (key) {
238-
Mutex::ScopedLock priv_lock(key.mutex());
239-
}
240-
}
241233

242234
explicit KeyPairGenConfig(KeyPairGenConfig&& other) noexcept
243235
: public_key_encoding(other.public_key_encoding),
@@ -291,8 +283,7 @@ struct NidKeyPairGenTraits final {
291283

292284
using NidKeyPairGenJob = KeyGenJob<KeyPairGenTraits<NidKeyPairGenTraits>>;
293285
using SecretKeyGenJob = KeyGenJob<SecretKeyGenTraits>;
294-
} // namespace crypto
295-
} // namespace node
286+
} // namespace node::crypto
296287

297288
#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
298289
#endif // SRC_CRYPTO_CRYPTO_KEYGEN_H_

‎src/crypto/crypto_keys.cc

+123-146
Large diffs are not rendered by default.

‎src/crypto/crypto_keys.h

+4-10
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,7 @@
1616
#include <memory>
1717
#include <string>
1818

19-
namespace node {
20-
namespace crypto {
21-
19+
namespace node::crypto {
2220
enum KeyType {
2321
kKeyTypeSecret,
2422
kKeyTypePublic,
@@ -85,12 +83,12 @@ class KeyObjectData final : public MemoryRetainer {
8583
unsigned int* offset,
8684
KeyEncodingContext context);
8785

88-
v8::Maybe<void> ToEncodedPublicKey(
86+
bool ToEncodedPublicKey(
8987
Environment* env,
9088
const ncrypto::EVPKeyPointer::PublicKeyEncodingConfig& config,
9189
v8::Local<v8::Value>* out);
9290

93-
v8::Maybe<void> ToEncodedPrivateKey(
91+
bool ToEncodedPrivateKey(
9492
Environment* env,
9593
const ncrypto::EVPKeyPointer::PrivateKeyEncodingConfig& config,
9694
v8::Local<v8::Value>* out);
@@ -378,15 +376,11 @@ WebCryptoKeyExportStatus PKEY_SPKI_Export(const KeyObjectData& key_data,
378376
WebCryptoKeyExportStatus PKEY_PKCS8_Export(const KeyObjectData& key_data,
379377
ByteSource* out);
380378

381-
int GetOKPCurveFromName(const char* name);
382-
383379
namespace Keys {
384380
void Initialize(Environment* env, v8::Local<v8::Object> target);
385381
void RegisterExternalReferences(ExternalReferenceRegistry* registry);
386382
} // namespace Keys
387-
388-
} // namespace crypto
389-
} // namespace node
383+
} // namespace node::crypto
390384

391385
#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
392386
#endif // SRC_CRYPTO_CRYPTO_KEYS_H_

‎src/crypto/crypto_rsa.cc

+17-17
Original file line numberDiff line numberDiff line change
@@ -318,17 +318,17 @@ WebCryptoCipherStatus RSACipherTraits::DoCipher(Environment* env,
318318
return WebCryptoCipherStatus::FAILED;
319319
}
320320

321-
Maybe<void> ExportJWKRsaKey(Environment* env,
322-
const KeyObjectData& key,
323-
Local<Object> target) {
321+
bool ExportJWKRsaKey(Environment* env,
322+
const KeyObjectData& key,
323+
Local<Object> target) {
324324
Mutex::ScopedLock lock(key.mutex());
325325
const auto& m_pkey = key.GetAsymmetricKey();
326326

327327
const ncrypto::Rsa rsa = m_pkey;
328328
if (!rsa ||
329329
target->Set(env->context(), env->jwk_kty_string(), env->jwk_rsa_string())
330330
.IsNothing()) {
331-
return Nothing<void>();
331+
return false;
332332
}
333333

334334
auto pub_key = rsa.getPublicKey();
@@ -337,7 +337,7 @@ Maybe<void> ExportJWKRsaKey(Environment* env,
337337
.IsNothing() ||
338338
SetEncodedValue(env, target, env->jwk_e_string(), pub_key.e)
339339
.IsNothing()) {
340-
return Nothing<void>();
340+
return false;
341341
}
342342

343343
if (key.GetKeyType() == kKeyTypePrivate) {
@@ -354,11 +354,11 @@ Maybe<void> ExportJWKRsaKey(Environment* env,
354354
.IsNothing() ||
355355
SetEncodedValue(env, target, env->jwk_qi_string(), pvt_key.qi)
356356
.IsNothing()) {
357-
return Nothing<void>();
357+
return false;
358358
}
359359
}
360360

361-
return JustVoid();
361+
return true;
362362
}
363363

364364
KeyObjectData ImportJWKRsaKey(Environment* env,
@@ -441,16 +441,16 @@ KeyObjectData ImportJWKRsaKey(Environment* env,
441441
return KeyObjectData::CreateAsymmetric(type, std::move(pkey));
442442
}
443443

444-
Maybe<void> GetRsaKeyDetail(Environment* env,
445-
const KeyObjectData& key,
446-
Local<Object> target) {
444+
bool GetRsaKeyDetail(Environment* env,
445+
const KeyObjectData& key,
446+
Local<Object> target) {
447447
Mutex::ScopedLock lock(key.mutex());
448448
const auto& m_pkey = key.GetAsymmetricKey();
449449

450450
// TODO(tniessen): Remove the "else" branch once we drop support for OpenSSL
451451
// versions older than 1.1.1e via FIPS / dynamic linking.
452452
const ncrypto::Rsa rsa = m_pkey;
453-
if (!rsa) return Nothing<void>();
453+
if (!rsa) return false;
454454

455455
auto pub_key = rsa.getPublicKey();
456456

@@ -461,7 +461,7 @@ Maybe<void> GetRsaKeyDetail(Environment* env,
461461
env->isolate(),
462462
static_cast<double>(BignumPointer::GetBitCount(pub_key.n))))
463463
.IsNothing()) {
464-
return Nothing<void>();
464+
return false;
465465
}
466466

467467
auto public_exponent = ArrayBuffer::NewBackingStore(
@@ -479,7 +479,7 @@ Maybe<void> GetRsaKeyDetail(Environment* env,
479479
env->public_exponent_string(),
480480
ArrayBuffer::New(env->isolate(), std::move(public_exponent)))
481481
.IsNothing()) {
482-
return Nothing<void>();
482+
return false;
483483
}
484484

485485
if (m_pkey.id() == EVP_PKEY_RSA_PSS) {
@@ -500,7 +500,7 @@ Maybe<void> GetRsaKeyDetail(Environment* env,
500500
env->hash_algorithm_string(),
501501
OneByteString(env->isolate(), params.digest))
502502
.IsNothing()) {
503-
return Nothing<void>();
503+
return false;
504504
}
505505

506506
// If, for some reason, the MGF is not MGF1, then the MGF1 hash function
@@ -512,7 +512,7 @@ Maybe<void> GetRsaKeyDetail(Environment* env,
512512
env->mgf1_hash_algorithm_string(),
513513
OneByteString(env->isolate(), digest))
514514
.IsNothing()) {
515-
return Nothing<void>();
515+
return false;
516516
}
517517
}
518518

@@ -521,12 +521,12 @@ Maybe<void> GetRsaKeyDetail(Environment* env,
521521
env->salt_length_string(),
522522
Integer::New(env->isolate(), params.salt_length))
523523
.IsNothing()) {
524-
return Nothing<void>();
524+
return false;
525525
}
526526
}
527527
}
528528

529-
return JustVoid();
529+
return true;
530530
}
531531

532532
namespace RSAAlg {

‎src/crypto/crypto_rsa.h

+6-6
Original file line numberDiff line numberDiff line change
@@ -112,18 +112,18 @@ struct RSACipherTraits final {
112112

113113
using RSACipherJob = CipherJob<RSACipherTraits>;
114114

115-
v8::Maybe<void> ExportJWKRsaKey(Environment* env,
116-
const KeyObjectData& key,
117-
v8::Local<v8::Object> target);
115+
bool ExportJWKRsaKey(Environment* env,
116+
const KeyObjectData& key,
117+
v8::Local<v8::Object> target);
118118

119119
KeyObjectData ImportJWKRsaKey(Environment* env,
120120
v8::Local<v8::Object> jwk,
121121
const v8::FunctionCallbackInfo<v8::Value>& args,
122122
unsigned int offset);
123123

124-
v8::Maybe<void> GetRsaKeyDetail(Environment* env,
125-
const KeyObjectData& key,
126-
v8::Local<v8::Object> target);
124+
bool GetRsaKeyDetail(Environment* env,
125+
const KeyObjectData& key,
126+
v8::Local<v8::Object> target);
127127

128128
namespace RSAAlg {
129129
void Initialize(Environment* env, v8::Local<v8::Object> target);

0 commit comments

Comments
 (0)
Please sign in to comment.