-
Notifications
You must be signed in to change notification settings - Fork 119
Expand file tree
/
Copy pathHybridKeyObjectHandle.cpp
More file actions
1519 lines (1319 loc) · 52.2 KB
/
Copy pathHybridKeyObjectHandle.cpp
File metadata and controls
1519 lines (1319 loc) · 52.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <cstdio>
#include <mutex>
#include <stdexcept>
#include "../utils/base64.h"
#include "HybridKeyObjectHandle.hpp"
#include "QuickCryptoUtils.hpp"
#include <openssl/bn.h>
#include <openssl/core_names.h>
#include <openssl/crypto.h>
#include <openssl/ec.h>
#include <openssl/evp.h>
#include <openssl/obj_mac.h>
#include <openssl/provider.h>
#include <openssl/rsa.h>
namespace margelo::nitro::crypto {
#if OPENSSL_VERSION_NUMBER >= 0x30600000L
// Configure loaded providers to prefer seed-only PKCS#8 output for ML-DSA /
// ML-KEM, falling back to priv-only when no seed is available. Without this,
// OpenSSL defaults to "seed-priv" — a longer encoding that bundles both —
// which breaks interop with Node and the exact-length export check in subtle.ts.
// Mirrors src/crypto/crypto_util.cc in Node.
static void configurePqcOutputFormats() {
static std::once_flag once;
std::call_once(once, []() {
OSSL_PROVIDER_do_all(
nullptr,
[](OSSL_PROVIDER* provider, void*) -> int {
OSSL_PROVIDER_add_conf_parameter(provider, "ml-kem.output_formats", "seed-only,priv-only");
OSSL_PROVIDER_add_conf_parameter(provider, "ml-dsa.output_formats", "seed-only,priv-only");
OSSL_PROVIDER_add_conf_parameter(provider, "slh-dsa.output_formats", "seed-only,priv-only");
return 1;
},
nullptr);
});
}
#endif
HybridKeyObjectHandle::HybridKeyObjectHandle() : HybridObject(TAG) {
#if OPENSSL_VERSION_NUMBER >= 0x30600000L
// Configure once on first handle construction. Providers are guaranteed
// loaded by this point (any prior crypto op routed through ncrypto), and
// the call_once flag makes subsequent constructions cheap.
configurePqcOutputFormats();
#endif
}
// Helper functions for base64url encoding/decoding with BIGNUMs
static std::string bn_to_base64url(const BIGNUM* bn, size_t expected_size = 0) {
if (!bn)
return "";
int num_bytes = BN_num_bytes(bn);
if (num_bytes == 0)
return "";
// If expected_size is provided and larger than num_bytes, pad with leading zeros
size_t buffer_size =
(expected_size > 0 && expected_size > static_cast<size_t>(num_bytes)) ? expected_size : static_cast<size_t>(num_bytes);
std::vector<unsigned char> buffer(buffer_size, 0);
// BN_bn2bin writes to the end of the buffer if it's larger than needed
size_t offset = buffer_size - num_bytes;
BN_bn2bin(bn, buffer.data() + offset);
// Return clean base64url - RFC 7517 compliant (no padding characters)
return base64_encode<std::string>(buffer.data(), buffer.size(), true);
}
// Helper to add padding to base64url strings
static std::string add_base64_padding(const std::string& b64) {
std::string padded = b64;
// Base64 strings should be a multiple of 4 characters
// Add '=' padding to make it so
while (padded.length() % 4 != 0) {
padded += '=';
}
return padded;
}
static BIGNUM* base64url_to_bn(const std::string& b64) {
if (b64.empty())
return nullptr;
try {
// Strip trailing periods (some JWK implementations use '.' as padding)
std::string cleaned = b64;
while (!cleaned.empty() && cleaned.back() == '.') {
cleaned.pop_back();
}
// Add padding if needed for base64url
std::string padded = add_base64_padding(cleaned);
std::string decoded = base64_decode<std::string>(padded, false);
if (decoded.empty())
return nullptr;
return BN_bin2bn(reinterpret_cast<const unsigned char*>(decoded.data()), static_cast<int>(decoded.size()), nullptr);
} catch (const std::exception& e) {
throw std::runtime_error(std::string("Input is not valid base64-encoded data."));
}
}
static std::string base64url_encode(const unsigned char* data, size_t len) {
return base64_encode<std::string>(data, len, true);
}
static std::string base64url_decode(const std::string& input) {
// Strip trailing periods (some JWK implementations use '.' as padding)
std::string cleaned = input;
while (!cleaned.empty() && cleaned.back() == '.') {
cleaned.pop_back();
}
// Add padding if needed for base64url
std::string padded = add_base64_padding(cleaned);
return base64_decode<std::string>(padded, false);
}
std::shared_ptr<ArrayBuffer> HybridKeyObjectHandle::exportKey(std::optional<KFormatType> format, std::optional<KeyEncoding> type,
const std::optional<std::string>& cipher,
const std::optional<std::shared_ptr<ArrayBuffer>>& passphrase) {
auto keyType = data_.GetKeyType();
// Copy to avoid JSI ArrayBuffer GC issues. See #645.
if (keyType == KeyType::SECRET) {
return ToNativeArrayBuffer(data_.GetSymmetricKey());
}
// Handle asymmetric keys (public/private)
if (keyType == KeyType::PUBLIC || keyType == KeyType::PRIVATE) {
const auto& pkey = data_.GetAsymmetricKey();
if (!pkey) {
throw std::runtime_error("Invalid asymmetric key");
}
int keyId = EVP_PKEY_id(pkey.get());
// For curve keys (X25519, X448, Ed25519, Ed448), use raw format if no format specified
bool isCurveKey = (keyId == EVP_PKEY_X25519 || keyId == EVP_PKEY_X448 || keyId == EVP_PKEY_ED25519 || keyId == EVP_PKEY_ED448);
// If no format specified and it's a curve key, export as raw
if (!format.has_value() && !type.has_value() && isCurveKey) {
if (keyType == KeyType::PUBLIC) {
auto rawData = pkey.rawPublicKey();
if (!rawData) {
throw std::runtime_error("Failed to get raw public key");
}
return ToNativeArrayBuffer(std::string(reinterpret_cast<const char*>(rawData.get()), rawData.size()));
} else {
auto rawData = pkey.rawPrivateKey();
if (!rawData) {
throw std::runtime_error("Failed to get raw private key");
}
return ToNativeArrayBuffer(std::string(reinterpret_cast<const char*>(rawData.get()), rawData.size()));
}
}
// For EC keys, handle raw format (uncompressed point)
if (!format.has_value() && !type.has_value() && keyId == EVP_PKEY_EC && keyType == KeyType::PUBLIC) {
size_t len = 0;
if (EVP_PKEY_get_octet_string_param(pkey.get(), OSSL_PKEY_PARAM_PUB_KEY, nullptr, 0, &len) != 1 || len == 0)
throw std::runtime_error("Failed to get EC public key size");
std::vector<uint8_t> buf(len);
if (EVP_PKEY_get_octet_string_param(pkey.get(), OSSL_PKEY_PARAM_PUB_KEY, buf.data(), buf.size(), &len) != 1)
throw std::runtime_error("Failed to get EC public key");
return ToNativeArrayBuffer(std::string(reinterpret_cast<const char*>(buf.data()), len));
}
#if OPENSSL_VERSION_NUMBER >= 0x30500000L
if (!format.has_value() && !type.has_value()) {
const char* typeName = EVP_PKEY_get0_type_name(pkey.get());
if (typeName != nullptr) {
std::string name(typeName);
bool isPqcKey = (name.starts_with("ML-KEM-") || name.starts_with("ML-DSA-") || name.starts_with("SLH-DSA-"));
if (isPqcKey) {
if (keyType == KeyType::PUBLIC) {
auto rawData = pkey.rawPublicKey();
if (!rawData) {
throw std::runtime_error("Failed to get raw PQC public key");
}
return ToNativeArrayBuffer(std::string(reinterpret_cast<const char*>(rawData.get()), rawData.size()));
} else {
auto rawData = pkey.rawSeed();
if (!rawData) {
throw std::runtime_error("Failed to get raw PQC seed");
}
return ToNativeArrayBuffer(std::string(reinterpret_cast<const char*>(rawData.get()), rawData.size()));
}
}
}
}
#endif
// Set default format and type if not provided
auto exportFormat = format.value_or(KFormatType::DER);
auto exportType = type.value_or(keyType == KeyType::PUBLIC ? KeyEncoding::SPKI : KeyEncoding::PKCS8);
// If SPKI is requested, export as public key (works for both public and private keys)
// This allows extracting the public key from a private key
bool exportAsPublic = (exportType == KeyEncoding::SPKI) || (keyType == KeyType::PUBLIC);
// Create encoding config
if (exportAsPublic) {
ncrypto::EVPKeyPointer::PublicKeyEncodingConfig config(false, static_cast<ncrypto::EVPKeyPointer::PKFormatType>(exportFormat),
static_cast<ncrypto::EVPKeyPointer::PKEncodingType>(exportType));
auto result = pkey.writePublicKey(config);
if (!result) {
throw std::runtime_error("Failed to export public key");
}
auto bio = std::move(result.value);
BUF_MEM* bptr = bio;
return ToNativeArrayBuffer(std::string(bptr->data, bptr->length));
} else {
ncrypto::EVPKeyPointer::PrivateKeyEncodingConfig config(false, static_cast<ncrypto::EVPKeyPointer::PKFormatType>(exportFormat),
static_cast<ncrypto::EVPKeyPointer::PKEncodingType>(exportType));
// Handle cipher and passphrase for encrypted private keys
if (cipher.has_value()) {
const EVP_CIPHER* evp_cipher = EVP_get_cipherbyname(cipher.value().c_str());
if (!evp_cipher) {
throw std::runtime_error("Unknown cipher: " + cipher.value());
}
config.cipher = evp_cipher;
}
if (passphrase.has_value()) {
auto& passphrase_ptr = passphrase.value();
config.passphrase =
std::make_optional(ncrypto::DataPointer::Copy(ncrypto::Buffer<const void>{passphrase_ptr->data(), passphrase_ptr->size()}));
}
auto result = pkey.writePrivateKey(config);
if (!result) {
throw std::runtime_error("Failed to export private key");
}
auto bio = std::move(result.value);
BUF_MEM* bptr = bio;
return ToNativeArrayBuffer(std::string(bptr->data, bptr->length));
}
}
throw std::runtime_error("Unsupported key type for export");
}
JWK HybridKeyObjectHandle::exportJwk(const JWK& key, bool handleRsaPss) {
JWK result = key;
auto keyType = data_.GetKeyType();
// Handle secret keys (AES, HMAC)
if (keyType == KeyType::SECRET) {
auto symKey = data_.GetSymmetricKey();
result.kty = JWKkty::OCT;
// RFC 7517 compliant base64url encoding (no padding characters)
result.k = base64url_encode(reinterpret_cast<const unsigned char*>(symKey->data()), symKey->size());
return result;
}
// Handle asymmetric keys (RSA, EC)
const auto& pkey = data_.GetAsymmetricKey();
if (!pkey) {
throw std::runtime_error("Invalid key for JWK export");
}
int keyId = EVP_PKEY_id(pkey.get());
// Export RSA keys
if (keyId == EVP_PKEY_RSA || keyId == EVP_PKEY_RSA_PSS) {
const RSA* rsa = EVP_PKEY_get0_RSA(pkey.get());
if (!rsa)
throw std::runtime_error("Failed to get RSA key");
result.kty = JWKkty::RSA;
const BIGNUM *n_bn, *e_bn, *d_bn, *p_bn, *q_bn, *dmp1_bn, *dmq1_bn, *iqmp_bn;
RSA_get0_key(rsa, &n_bn, &e_bn, &d_bn);
RSA_get0_factors(rsa, &p_bn, &q_bn);
RSA_get0_crt_params(rsa, &dmp1_bn, &dmq1_bn, &iqmp_bn);
// Public components (always present)
if (n_bn)
result.n = bn_to_base64url(n_bn);
if (e_bn)
result.e = bn_to_base64url(e_bn);
// Private components (only for private keys)
if (keyType == KeyType::PRIVATE) {
if (d_bn)
result.d = bn_to_base64url(d_bn);
if (p_bn)
result.p = bn_to_base64url(p_bn);
if (q_bn)
result.q = bn_to_base64url(q_bn);
if (dmp1_bn)
result.dp = bn_to_base64url(dmp1_bn);
if (dmq1_bn)
result.dq = bn_to_base64url(dmq1_bn);
if (iqmp_bn)
result.qi = bn_to_base64url(iqmp_bn);
}
return result;
}
// Export EC keys
if (keyId == EVP_PKEY_EC) {
char curve_name_buf[64];
size_t name_len = 0;
if (EVP_PKEY_get_utf8_string_param(pkey.get(), OSSL_PKEY_PARAM_GROUP_NAME, curve_name_buf, sizeof(curve_name_buf), &name_len) != 1)
throw std::runtime_error("Failed to get EC group name");
std::string curve_name(curve_name_buf, name_len);
int bits = EVP_PKEY_bits(pkey.get());
if (bits <= 0)
throw std::runtime_error("Failed to get EC key size");
size_t field_size = (static_cast<size_t>(bits) + 7) / 8;
result.kty = JWKkty::EC;
// Map OpenSSL curve names to JWK curve names
if (curve_name == "prime256v1") {
result.crv = "P-256";
} else if (curve_name == "secp384r1") {
result.crv = "P-384";
} else if (curve_name == "secp521r1") {
result.crv = "P-521";
} else {
result.crv = curve_name;
}
BIGNUM* x_bn = nullptr;
BIGNUM* y_bn = nullptr;
if (EVP_PKEY_get_bn_param(pkey.get(), OSSL_PKEY_PARAM_EC_PUB_X, &x_bn) != 1 ||
EVP_PKEY_get_bn_param(pkey.get(), OSSL_PKEY_PARAM_EC_PUB_Y, &y_bn) != 1) {
BN_free(x_bn);
BN_free(y_bn);
throw std::runtime_error("Failed to get EC public key coordinates");
}
result.x = bn_to_base64url(x_bn, field_size);
result.y = bn_to_base64url(y_bn, field_size);
BN_free(x_bn);
BN_free(y_bn);
// Export private key if this is a private key
if (keyType == KeyType::PRIVATE) {
BIGNUM* priv_bn = nullptr;
if (EVP_PKEY_get_bn_param(pkey.get(), OSSL_PKEY_PARAM_PRIV_KEY, &priv_bn) == 1 && priv_bn) {
result.d = bn_to_base64url(priv_bn, field_size);
BN_free(priv_bn);
}
}
return result;
}
// Export OKP keys (Ed25519, Ed448, X25519, X448) per RFC 8037
if (keyId == EVP_PKEY_ED25519 || keyId == EVP_PKEY_ED448 || keyId == EVP_PKEY_X25519 || keyId == EVP_PKEY_X448) {
result.kty = JWKkty::OKP;
switch (keyId) {
case EVP_PKEY_ED25519:
result.crv = "Ed25519";
break;
case EVP_PKEY_ED448:
result.crv = "Ed448";
break;
case EVP_PKEY_X25519:
result.crv = "X25519";
break;
case EVP_PKEY_X448:
result.crv = "X448";
break;
default:
break;
}
auto pubKey = pkey.rawPublicKey();
if (!pubKey) {
throw std::runtime_error("Failed to get raw public key for OKP JWK export");
}
result.x = base64url_encode(reinterpret_cast<const unsigned char*>(pubKey.get()), pubKey.size());
if (keyType == KeyType::PRIVATE) {
auto privKey = pkey.rawPrivateKey();
if (!privKey) {
throw std::runtime_error("Failed to get raw private key for OKP JWK export");
}
result.d = base64url_encode(reinterpret_cast<const unsigned char*>(privKey.get()), privKey.size());
}
return result;
}
#if OPENSSL_VERSION_NUMBER >= 0x30500000L
// Export AKP keys (ML-DSA, ML-KEM)
{
const char* typeName = EVP_PKEY_get0_type_name(pkey.get());
if (typeName != nullptr) {
std::string name(typeName);
bool isPqcKey = (name.starts_with("ML-DSA-") || name.starts_with("ML-KEM-") || name.starts_with("SLH-DSA-"));
if (isPqcKey) {
result.kty = JWKkty::AKP;
result.alg = name;
auto pubKey = pkey.rawPublicKey();
if (!pubKey) {
throw std::runtime_error("Failed to get raw public key for AKP JWK export");
}
result.pub = base64url_encode(reinterpret_cast<const unsigned char*>(pubKey.get()), pubKey.size());
if (keyType == KeyType::PRIVATE) {
auto seed = pkey.rawSeed();
if (!seed) {
throw std::runtime_error("Key does not have an available seed");
}
result.priv = base64url_encode(reinterpret_cast<const unsigned char*>(seed.get()), seed.size());
}
return result;
}
}
}
#endif
throw std::runtime_error("Unsupported key type for JWK export");
}
// Returns true if the EVP_PKEY type supports raw public key export
// (CFRG keys: Ed25519, Ed448, X25519, X448; PQC keys: ML-DSA, ML-KEM, SLH-DSA).
static bool supportsRawPublic(int keyId, const char* typeName) {
if (keyId == EVP_PKEY_ED25519 || keyId == EVP_PKEY_ED448 || keyId == EVP_PKEY_X25519 || keyId == EVP_PKEY_X448) {
return true;
}
#if OPENSSL_VERSION_NUMBER >= 0x30500000L
if (keyId == EVP_PKEY_ML_DSA_44 || keyId == EVP_PKEY_ML_DSA_65 || keyId == EVP_PKEY_ML_DSA_87) {
return true;
}
if (typeName != nullptr) {
std::string name(typeName);
if (name.starts_with("ML-KEM-") || name.starts_with("ML-DSA-") || name.starts_with("SLH-DSA-")) {
return true;
}
}
#else
(void)typeName;
#endif
return false;
}
// Returns true if the EVP_PKEY type supports raw private key export
// (CFRG keys: Ed25519, Ed448, X25519, X448; SLH-DSA private keys).
static bool supportsRawPrivate(int keyId, const char* typeName) {
if (keyId == EVP_PKEY_ED25519 || keyId == EVP_PKEY_ED448 || keyId == EVP_PKEY_X25519 || keyId == EVP_PKEY_X448) {
return true;
}
#if OPENSSL_VERSION_NUMBER >= 0x30500000L
if (typeName != nullptr) {
std::string name(typeName);
if (name.starts_with("SLH-DSA-")) {
return true;
}
}
#else
(void)typeName;
#endif
return false;
}
// Returns true if the EVP_PKEY type supports raw seed export
// (PQC keys: ML-DSA, ML-KEM, SLH-DSA).
static bool supportsRawSeed(int keyId, const char* typeName) {
#if OPENSSL_VERSION_NUMBER >= 0x30500000L
if (keyId == EVP_PKEY_ML_DSA_44 || keyId == EVP_PKEY_ML_DSA_65 || keyId == EVP_PKEY_ML_DSA_87) {
return true;
}
if (typeName != nullptr) {
std::string name(typeName);
if (name.starts_with("ML-KEM-") || name.starts_with("ML-DSA-") || name.starts_with("SLH-DSA-")) {
return true;
}
}
#else
(void)keyId;
(void)typeName;
#endif
return false;
}
std::shared_ptr<ArrayBuffer> HybridKeyObjectHandle::exportRawPublic() {
auto keyType = data_.GetKeyType();
if (keyType == KeyType::SECRET) {
throw std::runtime_error("Raw public key export is not supported for secret keys");
}
const auto& pkey = data_.GetAsymmetricKey();
if (!pkey) {
throw std::runtime_error("Invalid asymmetric key");
}
int keyId = EVP_PKEY_id(pkey.get());
const char* typeName = EVP_PKEY_get0_type_name(pkey.get());
if (!supportsRawPublic(keyId, typeName)) {
throw std::runtime_error("The key type does not support raw public key export");
}
auto rawData = pkey.rawPublicKey();
if (!rawData) {
throw std::runtime_error("Failed to get raw public key");
}
return ToNativeArrayBuffer(reinterpret_cast<const uint8_t*>(rawData.get()), rawData.size());
}
std::shared_ptr<ArrayBuffer> HybridKeyObjectHandle::exportRawPrivate() {
auto keyType = data_.GetKeyType();
if (keyType != KeyType::PRIVATE) {
throw std::runtime_error("Raw private key export requires a private key");
}
const auto& pkey = data_.GetAsymmetricKey();
if (!pkey) {
throw std::runtime_error("Invalid asymmetric key");
}
int keyId = EVP_PKEY_id(pkey.get());
const char* typeName = EVP_PKEY_get0_type_name(pkey.get());
if (!supportsRawPrivate(keyId, typeName)) {
throw std::runtime_error("The key type does not support raw private key export");
}
auto rawData = pkey.rawPrivateKey();
if (!rawData) {
throw std::runtime_error("Failed to get raw private key");
}
return ToNativeArrayBuffer(reinterpret_cast<const uint8_t*>(rawData.get()), rawData.size());
}
std::shared_ptr<ArrayBuffer> HybridKeyObjectHandle::exportRawSeed() {
#if OPENSSL_VERSION_NUMBER >= 0x30500000L
auto keyType = data_.GetKeyType();
if (keyType != KeyType::PRIVATE) {
throw std::runtime_error("Raw seed export requires a private key");
}
const auto& pkey = data_.GetAsymmetricKey();
if (!pkey) {
throw std::runtime_error("Invalid asymmetric key");
}
int keyId = EVP_PKEY_id(pkey.get());
const char* typeName = EVP_PKEY_get0_type_name(pkey.get());
if (!supportsRawSeed(keyId, typeName)) {
throw std::runtime_error("The key type does not support raw seed export");
}
auto rawData = pkey.rawSeed();
if (!rawData) {
throw std::runtime_error("Key does not have an available seed");
}
return ToNativeArrayBuffer(reinterpret_cast<const uint8_t*>(rawData.get()), rawData.size());
#else
throw std::runtime_error("Raw seed export requires OpenSSL 3.5+");
#endif
}
std::shared_ptr<ArrayBuffer> HybridKeyObjectHandle::exportECPublicRaw(bool compressed) {
auto keyType = data_.GetKeyType();
if (keyType == KeyType::SECRET) {
throw std::runtime_error("EC raw public key export is not supported for secret keys");
}
const auto& pkey = data_.GetAsymmetricKey();
if (!pkey) {
throw std::runtime_error("Invalid asymmetric key");
}
if (EVP_PKEY_id(pkey.get()) != EVP_PKEY_EC) {
throw std::runtime_error("Key is not an EC key");
}
const EC_KEY* ec_key = EVP_PKEY_get0_EC_KEY(pkey.get());
if (!ec_key) {
throw std::runtime_error("Failed to get EC key");
}
const EC_GROUP* group = EC_KEY_get0_group(ec_key);
const EC_POINT* point = EC_KEY_get0_public_key(ec_key);
if (!group || !point) {
throw std::runtime_error("Failed to get EC public key point");
}
point_conversion_form_t form = compressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED;
size_t len = EC_POINT_point2oct(group, point, form, nullptr, 0, nullptr);
if (len == 0) {
throw std::runtime_error("Failed to compute EC point size");
}
std::vector<uint8_t> buf(len);
if (EC_POINT_point2oct(group, point, form, buf.data(), buf.size(), nullptr) != len) {
throw std::runtime_error("Failed to encode EC public key point");
}
return ToNativeArrayBuffer(buf.data(), buf.size());
}
std::shared_ptr<ArrayBuffer> HybridKeyObjectHandle::exportECPrivateRaw() {
auto keyType = data_.GetKeyType();
if (keyType != KeyType::PRIVATE) {
throw std::runtime_error("EC raw private key export requires a private key");
}
const auto& pkey = data_.GetAsymmetricKey();
if (!pkey) {
throw std::runtime_error("Invalid asymmetric key");
}
if (EVP_PKEY_id(pkey.get()) != EVP_PKEY_EC) {
throw std::runtime_error("Key is not an EC key");
}
const EC_KEY* ec_key = EVP_PKEY_get0_EC_KEY(pkey.get());
if (!ec_key) {
throw std::runtime_error("Failed to get EC key");
}
const BIGNUM* priv_bn = EC_KEY_get0_private_key(ec_key);
if (!priv_bn) {
throw std::runtime_error("EC key has no private component");
}
const EC_GROUP* group = EC_KEY_get0_group(ec_key);
if (!group) {
throw std::runtime_error("Failed to get EC group");
}
BIGNUM* order = BN_new();
if (!order) {
throw std::runtime_error("Failed to allocate BIGNUM");
}
if (EC_GROUP_get_order(group, order, nullptr) != 1) {
BN_free(order);
throw std::runtime_error("Failed to get EC group order");
}
size_t order_size = (BN_num_bits(order) + 7) / 8;
BN_free(order);
std::vector<uint8_t> buf(order_size, 0);
if (BN_bn2binpad(priv_bn, buf.data(), static_cast<int>(order_size)) < 0) {
throw std::runtime_error("Failed to encode EC private key");
}
return ToNativeArrayBuffer(buf.data(), buf.size());
}
AsymmetricKeyType HybridKeyObjectHandle::getAsymmetricKeyType() {
const auto& pkey = data_.GetAsymmetricKey();
if (!pkey) {
throw std::runtime_error("Key is not an asymmetric key");
}
int keyType = EVP_PKEY_id(pkey.get());
switch (keyType) {
case EVP_PKEY_RSA:
return AsymmetricKeyType::RSA;
case EVP_PKEY_RSA_PSS:
return AsymmetricKeyType::RSA_PSS;
case EVP_PKEY_DSA:
return AsymmetricKeyType::DSA;
case EVP_PKEY_EC:
return AsymmetricKeyType::EC;
case EVP_PKEY_DH:
return AsymmetricKeyType::DH;
case EVP_PKEY_X25519:
return AsymmetricKeyType::X25519;
case EVP_PKEY_X448:
return AsymmetricKeyType::X448;
case EVP_PKEY_ED25519:
return AsymmetricKeyType::ED25519;
case EVP_PKEY_ED448:
return AsymmetricKeyType::ED448;
#if OPENSSL_VERSION_NUMBER >= 0x30500000L
case EVP_PKEY_ML_DSA_44:
return AsymmetricKeyType::ML_DSA_44;
case EVP_PKEY_ML_DSA_65:
return AsymmetricKeyType::ML_DSA_65;
case EVP_PKEY_ML_DSA_87:
return AsymmetricKeyType::ML_DSA_87;
#endif
default:
break;
}
#if OPENSSL_VERSION_NUMBER >= 0x30500000L
// EVP_PKEY_id returns -1 for provider-only key types (e.g. ML-KEM, SLH-DSA)
// Fall back to string-based type name comparison
const char* typeName = EVP_PKEY_get0_type_name(pkey.get());
if (typeName != nullptr) {
std::string name(typeName);
if (name == "ML-KEM-512")
return AsymmetricKeyType::ML_KEM_512;
if (name == "ML-KEM-768")
return AsymmetricKeyType::ML_KEM_768;
if (name == "ML-KEM-1024")
return AsymmetricKeyType::ML_KEM_1024;
if (name == "SLH-DSA-SHA2-128s")
return AsymmetricKeyType::SLH_DSA_SHA2_128S;
if (name == "SLH-DSA-SHA2-128f")
return AsymmetricKeyType::SLH_DSA_SHA2_128F;
if (name == "SLH-DSA-SHA2-192s")
return AsymmetricKeyType::SLH_DSA_SHA2_192S;
if (name == "SLH-DSA-SHA2-192f")
return AsymmetricKeyType::SLH_DSA_SHA2_192F;
if (name == "SLH-DSA-SHA2-256s")
return AsymmetricKeyType::SLH_DSA_SHA2_256S;
if (name == "SLH-DSA-SHA2-256f")
return AsymmetricKeyType::SLH_DSA_SHA2_256F;
if (name == "SLH-DSA-SHAKE-128s")
return AsymmetricKeyType::SLH_DSA_SHAKE_128S;
if (name == "SLH-DSA-SHAKE-128f")
return AsymmetricKeyType::SLH_DSA_SHAKE_128F;
if (name == "SLH-DSA-SHAKE-192s")
return AsymmetricKeyType::SLH_DSA_SHAKE_192S;
if (name == "SLH-DSA-SHAKE-192f")
return AsymmetricKeyType::SLH_DSA_SHAKE_192F;
if (name == "SLH-DSA-SHAKE-256s")
return AsymmetricKeyType::SLH_DSA_SHAKE_256S;
if (name == "SLH-DSA-SHAKE-256f")
return AsymmetricKeyType::SLH_DSA_SHAKE_256F;
}
#endif
throw std::runtime_error("Unsupported asymmetric key type");
}
bool HybridKeyObjectHandle::init(KeyType keyType, const std::variant<std::shared_ptr<ArrayBuffer>, std::string>& key,
std::optional<KFormatType> format, std::optional<KeyEncoding> type,
const std::optional<std::shared_ptr<ArrayBuffer>>& passphrase) {
// Reset any existing data to prevent state leakage
data_ = KeyObjectData();
// get ArrayBuffer from key - always copy to ensure we own the data
std::shared_ptr<ArrayBuffer> ab;
if (std::holds_alternative<std::string>(key)) {
ab = ToNativeArrayBuffer(std::get<std::string>(key));
} else {
const auto& abPtr = std::get<std::shared_ptr<ArrayBuffer>>(key);
ab = ToNativeArrayBuffer(abPtr);
}
// Handle raw asymmetric key material - only for special curves with known raw sizes
std::optional<KFormatType> actualFormat = format;
if (!actualFormat.has_value() && !type.has_value() && (keyType == KeyType::PUBLIC || keyType == KeyType::PRIVATE)) {
size_t keySize = ab->size();
// Only route to initRawKey for exact special curve sizes:
// X25519/Ed25519: 32 bytes, X448: 56 bytes, Ed448: 57 bytes
// DER-encoded keys will be much larger and should use standard parsing
if ((keySize == 32) || (keySize == 56) || (keySize == 57)) {
return initRawKey(keyType, ab);
}
// For larger sizes (DER-encoded keys), fall through to standard parsing
}
switch (keyType) {
case KeyType::SECRET: {
this->data_ = KeyObjectData::CreateSecret(ab);
break;
}
case KeyType::PUBLIC: {
auto data = KeyObjectData::GetPublicOrPrivateKey(ab, actualFormat, type, passphrase);
if (!data)
return false;
this->data_ = data.addRefWithType(KeyType::PUBLIC);
break;
}
case KeyType::PRIVATE: {
if (auto data = KeyObjectData::GetPrivateKey(ab, actualFormat, type, passphrase, false)) {
this->data_ = std::move(data);
}
break;
}
}
return true;
}
std::optional<KeyType> HybridKeyObjectHandle::initJwk(const JWK& keyData, std::optional<NamedCurve> namedCurve) {
// Reset any existing data
data_ = KeyObjectData();
if (!keyData.kty.has_value()) {
throw std::runtime_error("JWK missing required 'kty' field");
}
JWKkty kty = keyData.kty.value();
// Handle symmetric keys (AES, HMAC)
if (kty == JWKkty::OCT) {
if (!keyData.k.has_value()) {
throw std::runtime_error("JWK oct key missing 'k' field");
}
std::string decoded = base64url_decode(keyData.k.value());
auto keyBuffer = ToNativeArrayBuffer(decoded);
data_ = KeyObjectData::CreateSecret(keyBuffer);
return KeyType::SECRET;
}
// Handle RSA keys
if (kty == JWKkty::RSA) {
bool isPrivate = keyData.d.has_value();
if (!keyData.n.has_value() || !keyData.e.has_value()) {
throw std::runtime_error("JWK RSA key missing required 'n' or 'e' fields");
}
RSA* rsa = RSA_new();
if (!rsa)
throw std::runtime_error("Failed to create RSA key");
// Set public components
BIGNUM* n = base64url_to_bn(keyData.n.value());
BIGNUM* e = base64url_to_bn(keyData.e.value());
if (!n || !e) {
RSA_free(rsa);
throw std::runtime_error("Failed to decode RSA public components");
}
if (isPrivate) {
// Private key
if (!keyData.d.has_value()) {
BN_free(n);
BN_free(e);
RSA_free(rsa);
throw std::runtime_error("JWK RSA private key missing 'd' field");
}
BIGNUM* d = base64url_to_bn(keyData.d.value());
if (!d) {
BN_free(n);
BN_free(e);
RSA_free(rsa);
throw std::runtime_error("Failed to decode RSA 'd' component");
}
// Set key components (RSA_set0_key takes ownership)
if (RSA_set0_key(rsa, n, e, d) != 1) {
BN_free(n);
BN_free(e);
BN_free(d);
RSA_free(rsa);
throw std::runtime_error("Failed to set RSA key components");
}
// Set optional CRT parameters if present
if (keyData.p.has_value() && keyData.q.has_value()) {
BIGNUM* p = base64url_to_bn(keyData.p.value());
BIGNUM* q = base64url_to_bn(keyData.q.value());
if (p && q) {
RSA_set0_factors(rsa, p, q);
}
}
if (keyData.dp.has_value() && keyData.dq.has_value() && keyData.qi.has_value()) {
BIGNUM* dmp1 = base64url_to_bn(keyData.dp.value());
BIGNUM* dmq1 = base64url_to_bn(keyData.dq.value());
BIGNUM* iqmp = base64url_to_bn(keyData.qi.value());
if (dmp1 && dmq1 && iqmp) {
RSA_set0_crt_params(rsa, dmp1, dmq1, iqmp);
}
}
// Create EVP_PKEY from RSA
EVP_PKEY* pkey = EVP_PKEY_new();
if (!pkey || EVP_PKEY_assign_RSA(pkey, rsa) != 1) {
RSA_free(rsa);
if (pkey)
EVP_PKEY_free(pkey);
throw std::runtime_error("Failed to create EVP_PKEY from RSA");
}
data_ = KeyObjectData::CreateAsymmetric(KeyType::PRIVATE, ncrypto::EVPKeyPointer(pkey));
return KeyType::PRIVATE;
} else {
// Public key
if (RSA_set0_key(rsa, n, e, nullptr) != 1) {
BN_free(n);
BN_free(e);
RSA_free(rsa);
throw std::runtime_error("Failed to set RSA public key components");
}
EVP_PKEY* pkey = EVP_PKEY_new();
if (!pkey || EVP_PKEY_assign_RSA(pkey, rsa) != 1) {
RSA_free(rsa);
if (pkey)
EVP_PKEY_free(pkey);
throw std::runtime_error("Failed to create EVP_PKEY from RSA");
}
data_ = KeyObjectData::CreateAsymmetric(KeyType::PUBLIC, ncrypto::EVPKeyPointer(pkey));
return KeyType::PUBLIC;
}
}
// Handle EC keys
if (kty == JWKkty::EC) {
bool isPrivate = keyData.d.has_value();
if (!keyData.crv.has_value() || !keyData.x.has_value() || !keyData.y.has_value()) {
throw std::runtime_error("JWK EC key missing required fields (crv, x, y)");
}
std::string crv = keyData.crv.value();
// Map JWK curve names to OpenSSL group names and field sizes
const char* group_name;
size_t field_size;
if (crv == "P-256") {
group_name = "prime256v1";
field_size = 32;
} else if (crv == "P-384") {
group_name = "secp384r1";
field_size = 48;
} else if (crv == "P-521") {
group_name = "secp521r1";
field_size = 66;
} else {
throw std::runtime_error("Unsupported EC curve: " + crv);
}
// Decode public key coordinates
BIGNUM* x_bn = base64url_to_bn(keyData.x.value());
BIGNUM* y_bn = base64url_to_bn(keyData.y.value());
if (!x_bn || !y_bn) {
BN_free(x_bn);
BN_free(y_bn);
throw std::runtime_error("Failed to decode EC public key coordinates");
}
// Build uncompressed point: 0x04 || x_padded || y_padded
std::vector<uint8_t> pub_oct(1 + 2 * field_size, 0);
pub_oct[0] = 0x04;
BN_bn2binpad(x_bn, pub_oct.data() + 1, static_cast<int>(field_size));
BN_bn2binpad(y_bn, pub_oct.data() + 1 + field_size, static_cast<int>(field_size));
BN_free(x_bn);
BN_free(y_bn);
BIGNUM* d_bn = nullptr;
if (isPrivate) {
d_bn = base64url_to_bn(keyData.d.value());
if (!d_bn)
throw std::runtime_error("Failed to decode EC private key");
}
EVP_PKEY* pkey = nullptr;
try {
pkey = createEcEvpPkey(group_name, pub_oct.data(), pub_oct.size(), d_bn);
} catch (...) {
BN_free(d_bn);
throw;
}
BN_free(d_bn);
KeyType type = isPrivate ? KeyType::PRIVATE : KeyType::PUBLIC;
data_ = KeyObjectData::CreateAsymmetric(type, ncrypto::EVPKeyPointer(pkey));
return type;
}
// Handle OKP keys (Ed25519, Ed448, X25519, X448) per RFC 8037
if (kty == JWKkty::OKP) {
bool isPrivate = keyData.d.has_value();
if (!keyData.crv.has_value() || !keyData.x.has_value()) {
throw std::runtime_error("JWK OKP key missing required fields (crv, x)");
}
std::string crv = keyData.crv.value();
int evpType;
if (crv == "Ed25519") {
evpType = EVP_PKEY_ED25519;
} else if (crv == "Ed448") {
evpType = EVP_PKEY_ED448;
} else if (crv == "X25519") {
evpType = EVP_PKEY_X25519;
} else if (crv == "X448") {
evpType = EVP_PKEY_X448;
} else {
throw std::runtime_error("Unsupported OKP curve: " + crv);
}