diff --git a/docs/content/docs/api/pqc.mdx b/docs/content/docs/api/pqc.mdx index add455f83..5aa55a575 100644 --- a/docs/content/docs/api/pqc.mdx +++ b/docs/content/docs/api/pqc.mdx @@ -378,3 +378,33 @@ let decrypted = decipher.update(encrypted, 'base64', 'utf8'); decrypted += decipher.final('utf8'); console.log(decrypted); // "secret message" ``` + +## Import a complete SLH-DSA private key + +`createPrivateKeyAsync()` is an RNQC extension for importing a complete raw SLH-DSA private key. Unlike Node's synchronous `createPrivateKey()`, it performs provider pairwise validation on a worker thread and returns a `PrivateKeyObject` containing the same validated native key. Synchronous SLH-DSA `raw-private` imports reject with an instruction to use this method. Other synchronous key imports are unchanged. + +```ts +import { createPrivateKeyAsync, createPublicKey } from 'react-native-quick-crypto'; + +const pending = createPrivateKeyAsync({ + key: rawPrivateKey, // ArrayBuffer only + format: 'raw-private', + asymmetricKeyType: 'slh-dsa-shake-128s', +}); +new Uint8Array(rawPrivateKey).fill(0); +const privateKey = await pending; +let publicKey; +try { + publicKey = createPublicKey(privateKey); + const rawPublicKey = publicKey.export({ format: 'raw-public' }); +} finally { + publicKey?.handle.dispose(); + privateKey.handle.dispose(); +} +``` + +All twelve SLH-DSA variants are supported, using lowercase `SlhDsaKeyPairType` names. The private input contains four `n`-byte fields (`SK.seed`, `SK.prf`, `PK.seed`, `PK.root`) and must be exactly 64, 96 or 128 bytes for the selected variant. Inconsistent `SK.seed`, `PK.seed` or `PK.root` reject with `SLH-DSA raw private key validation failed`. `SK.prf` is independent randomness: changing only that field remains valid and preserves the public key, as specified in FIPS 205 Algorithms 18–20. Validation does not authenticate a key's provenance. + +One raw-key import may be queued or running process-wide. An overlapping call rejects with `SLH-DSA raw private key import busy`; await the current import before retrying. OpenSSL 3.6 or newer is required. + +The raw native method checks the ArrayBuffer brand, variant and length, synchronously copies at most 128 bytes, and attaches Promise callbacks before queuing work. It erases the owned input and releases admission before settling. The native key is moved into a fresh handle; the factory retains no key. Call `handle.dispose()` when a key is no longer needed, including after cancellation that occurs while awaiting an import. This drops that handle's reference immediately even when a resolved native Promise retains the handle; independent native owners keep their own references. diff --git a/example/ios/Podfile b/example/ios/Podfile index ccc91cbdf..803480edb 100644 --- a/example/ios/Podfile +++ b/example/ios/Podfile @@ -26,6 +26,14 @@ target 'QuickCryptoExample' do :app_path => "#{Pod::Config.instance.installation_root}/..", ) + # Codegen otherwise embeds Bun's versioned peer-directory in its pod checksum. + codegen_path = File.join(__dir__, 'build/generated/ios/ReactCodegen.podspec') + codegen = File.read(codegen_path) + rn_export = /^export RCT_SCRIPT_RN_DIR="[^"\n]+"$/ + raise 'Unexpected ReactCodegen script path' unless codegen.scan(rn_export).length == 1 + File.write(codegen_path, codegen.sub(rn_export, + 'export RCT_SCRIPT_RN_DIR="$RCT_SCRIPT_POD_INSTALLATION_ROOT/../node_modules/react-native"')) + post_install do |installer| # https://github.com/facebook/react-native/blob/main/packages/react-native/scripts/react_native_pods.rb#L197-L202 react_native_post_install( diff --git a/example/ios/Podfile.lock b/example/ios/Podfile.lock index c28228376..a3f34f66f 100644 --- a/example/ios/Podfile.lock +++ b/example/ios/Podfile.lock @@ -2902,13 +2902,13 @@ SPEC CHECKSUMS: React-timing: 97ada2c47b4c5932e7f773c7d239c52b90d6ca68 React-utils: f0949d247a46b4c09f03e5a3cb1167602d0b729a ReactAppDependencyProvider: 3eb9096cb139eb433965693bbe541d96eb3d3ec9 - ReactCodegen: 6cf215132a21a6f00ca4d1507a7a78ecbceccf59 + ReactCodegen: 4d203eddf6f977caa324640a20f92e70408d648b ReactCommon: ce5d4226dfaf9d5dacbef57b4528819e39d3a120 RNScreens: d821082c6dd1cb397cc0c98b026eeafaa68be479 RNVectorIcons: 791f13226ec4a3fd13062eda9e892159f0981fae SocketRocket: d4aabe649be1e368d1318fdf28a022d714d65748 Yoga: 11c9686a21e2cd82a094a723649d9f4507200fb0 -PODFILE CHECKSUM: 2b1fa12c2fb50678fff8af81d9e99e04de1f3032 +PODFILE CHECKSUM: f389ff1cb5a41b2da19b5a4151e479a481490bca COCOAPODS: 1.15.2 diff --git a/example/metro.config.cjs b/example/metro.config.cjs index 1c81dec6d..5c1491a3e 100644 --- a/example/metro.config.cjs +++ b/example/metro.config.cjs @@ -3,6 +3,9 @@ const path = require('path'); const root = path.resolve(__dirname, '..'); const packagesDir = path.join(root, 'packages'); +const nitroRoot = path.dirname( + require.resolve('react-native-nitro-modules/package.json'), +); /** * Metro configuration @@ -14,6 +17,13 @@ const config = { watchFolders: [root], resolver: { + // Bun's peer layouts can expose two copies of this native singleton. + resolveRequest(context, moduleName, platform) { + if (moduleName === 'react-native-nitro-modules') { + return context.resolveRequest(context, nitroRoot, platform); + } + return context.resolveRequest(context, moduleName, platform); + }, nodeModulesPaths: [ path.join(__dirname, 'node_modules'), path.join(root, 'node_modules'), diff --git a/example/src/hooks/useTestsList.ts b/example/src/hooks/useTestsList.ts index dde9985f9..18157bf0d 100644 --- a/example/src/hooks/useTestsList.ts +++ b/example/src/hooks/useTestsList.ts @@ -35,6 +35,7 @@ import '../tests/pbkdf2/pbkdf2_tests'; import '../tests/prime/prime_tests'; import '../tests/random/random_tests'; import '../tests/scrypt/scrypt_tests'; +import '../tests/slhdsa/raw_private_validation'; import '../tests/subtle/argon2_deriveBits'; import '../tests/subtle/deriveBits'; import '../tests/subtle/derive_key'; diff --git a/example/src/tests/slhdsa/raw_private_validation.ts b/example/src/tests/slhdsa/raw_private_validation.ts new file mode 100644 index 000000000..07ba674a4 --- /dev/null +++ b/example/src/tests/slhdsa/raw_private_validation.ts @@ -0,0 +1,265 @@ +import { + Buffer, + createPrivateKey, + createPrivateKeyAsync, + createPublicKey, + sign, + verify, + type SlhDsaKeyPairType, + type KeyObjectHandle, + type SlhDsaPrivateKeyFactoryHandle, +} from 'react-native-quick-crypto'; +import { NitroModules } from 'react-native-nitro-modules'; +import { expect } from 'chai'; +import { assertThrowsAsync, test } from '../util'; + +const SUITE = 'SLH-DSA raw private key validation'; +const error = 'SLH-DSA raw private key validation failed'; + +// First test in each NIST ACVP keyGen FIPS 205 group, commit 975de31eb83d87039ec88934fdc47d8c312b892d. +// https://github.com/usnistgov/ACVP-Server/blob/975de31eb83d87039ec88934fdc47d8c312b892d/gen-val/json-files/SLH-DSA-keyGen-FIPS205/internalProjection.json +// Source SHA-256 d7c53a1b6450087047b57aae83a5a51a0ac89ecdb23ebe071e83fbb69ae9d920. +const vectors = [ + { + variant: 'SLH-DSA-SHA2-128s', + testCase: 1, + privateKey: + '173d04c938c1c36bf289c3c022d04b1463ae23c41aa546da589774ac20b745c40d794777914c99766827f0f09ca972be0162c10219d422adba1359e6aa65299c', + publicKey: + '0d794777914c99766827f0f09ca972be0162c10219d422adba1359e6aa65299c', + }, + { + variant: 'SLH-DSA-SHAKE-128s', + testCase: 11, + privateKey: + 'c151951f3811029239b74add24c506afdd30363e156e6fe936ec6ed0231feb5c529ffe86200d1f32c2b60d0cd909f1900761f9b727afa724b47223016bb5b2ba', + publicKey: + '529ffe86200d1f32c2b60d0cd909f1900761f9b727afa724b47223016bb5b2ba', + }, + { + variant: 'SLH-DSA-SHA2-128f', + testCase: 21, + privateKey: + 'c42bcb3b5a6f331f5cce899253c6d9e29ff2b7ead7a04bab1794db8cc659c3b4a868f1bd5debc12d4c9fad66aabd0a94b546df247be4c457f3d467cdfcfabd39', + publicKey: + 'a868f1bd5debc12d4c9fad66aabd0a94b546df247be4c457f3d467cdfcfabd39', + }, + { + variant: 'SLH-DSA-SHAKE-128f', + testCase: 31, + privateKey: + '3956ab391b4d22fc907af0740326d061ab0eb206436f2b86ebe086d77739b3e456505c229f4e7fa6b201714c7dcc9da366578f1f24c3fe371c97c14ce0e79cdc', + publicKey: + '56505c229f4e7fa6b201714c7dcc9da366578f1f24c3fe371c97c14ce0e79cdc', + }, + { + variant: 'SLH-DSA-SHA2-192s', + testCase: 41, + privateKey: + '040266529c1864088925506c20a624a2b6d50cd77c1c6f0d2841150ae8157512ef34a343ffea77ff7d9e814b45a8b41464462665f4202886206a8f632267186ca6a1cad08a2b9a862c6a7bc4ac4aaa84accef60d529f0311274f205e8da642c9', + publicKey: + '64462665f4202886206a8f632267186ca6a1cad08a2b9a862c6a7bc4ac4aaa84accef60d529f0311274f205e8da642c9', + }, + { + variant: 'SLH-DSA-SHAKE-192s', + testCase: 51, + privateKey: + '8732621860e9a6e1887be55f7af692b98eb4c10b2599f94ad5cc9d6470d8b21136158e8b1710f1fbe03eced37ed4ac6853fc64d46d7e1653ebbb36ed5fbc12c6e7cef3cb756482c8c620452e864e8497e1b38a7b04449219acd9e4393f9c88ef', + publicKey: + '53fc64d46d7e1653ebbb36ed5fbc12c6e7cef3cb756482c8c620452e864e8497e1b38a7b04449219acd9e4393f9c88ef', + }, + { + variant: 'SLH-DSA-SHA2-192f', + testCase: 61, + privateKey: + 'a021b4b9d6dee168722bc10225e50a946642af630c3c7c7d69e3a40ba09df2ac165b792a07f064ac5fc28d8c99a580f4ee4823d09e79854706daa80ae3179b5bc8c2e9409d6328a33577fd584bc0784c559cdb2437a46f7f753c336369419acf', + publicKey: + 'ee4823d09e79854706daa80ae3179b5bc8c2e9409d6328a33577fd584bc0784c559cdb2437a46f7f753c336369419acf', + }, + { + variant: 'SLH-DSA-SHAKE-192f', + testCase: 71, + privateKey: + 'fb7a2c2c75ce6c96b5f4328e0ab300476fc6f864cb5b0b99990ecb726ca822a4e3652dd92ec0aab7637ea41c0482ae2868dcc671e3534f81a352c275b6a25f906d2ed0ff62b8b4e398f1a9876cb082a48e9ae2c862b289486a3925cefc6ff4be', + publicKey: + '68dcc671e3534f81a352c275b6a25f906d2ed0ff62b8b4e398f1a9876cb082a48e9ae2c862b289486a3925cefc6ff4be', + }, + { + variant: 'SLH-DSA-SHA2-256s', + testCase: 81, + privateKey: + 'fcbf36a9807b30697be063a5105e091b412a391dd39e1326eba23cbd4096ca77ef4121c08dd71be913572f1f91e57d0acbcd5cec28539ac275832bbaa6c11081a0b4f5549ebcadb951dc2e512c76b0620d8fb8100b4ee886ef8784780d52a2543e57ab494d47068ffee4b8244aad6f19cdf94a2172bd134a15a6b5f298d5a80e', + publicKey: + 'a0b4f5549ebcadb951dc2e512c76b0620d8fb8100b4ee886ef8784780d52a2543e57ab494d47068ffee4b8244aad6f19cdf94a2172bd134a15a6b5f298d5a80e', + }, + { + variant: 'SLH-DSA-SHAKE-256s', + testCase: 91, + privateKey: + 'e440e39644a11a6a58e850c09c8f03c273e465237f3bef7c58de62281e676cea99c199c00db30f8499a61b5b9dc8a361725f6ae80e97037176f408c30b38844dd7b5e755b4879fde3288a21af3e32fbb006fd9b8bc2b180eb9b0d82c9f3157af02acd6b3198ee1c9fe9afe61fd86d1e0877ad9061980b57b178ce27191d8eb1b', + publicKey: + 'd7b5e755b4879fde3288a21af3e32fbb006fd9b8bc2b180eb9b0d82c9f3157af02acd6b3198ee1c9fe9afe61fd86d1e0877ad9061980b57b178ce27191d8eb1b', + }, + { + variant: 'SLH-DSA-SHA2-256f', + testCase: 101, + privateKey: + '18523702a0fe2c9e488948b127185bab93d3f02c3d7c23a1b379f762de0509e56ab0d9f93540bd809d1d2e8a050440aa81e853750470e2b00c959dbd3be40e2bd7125f5d00ba47f1fc8d4c32c2f57c444bd384d7ce770bc50dd5980c1d1264d00ad5197ffcbaafe11b1e413f26adb1504ce1c3f5c40c1dcda14e99fd126d5b81', + publicKey: + 'd7125f5d00ba47f1fc8d4c32c2f57c444bd384d7ce770bc50dd5980c1d1264d00ad5197ffcbaafe11b1e413f26adb1504ce1c3f5c40c1dcda14e99fd126d5b81', + }, + { + variant: 'SLH-DSA-SHAKE-256f', + testCase: 111, + privateKey: + '2ac9403858d186b172edd8df9c78a11449893681487d3af0dad0ec341e8aca48afa2771bae6c17dd6f77b4e3808b05f56f31b8f4128df2ccb677f0283cfb18da559bc883105e8ba0264648b532626155f87edb4bedcfc12a24204d3b696d53707a158ff5d30e3428183a3b3a96a0e4a341a2a16e5a6226af374d1efb39a35df6', + publicKey: + '559bc883105e8ba0264648b532626155f87edb4bedcfc12a24204d3b696d53707a158ff5d30e3428183a3b3a96a0e4a341a2a16e5a6226af374d1efb39a35df6', + }, +] as const; +const reference = vectors[1]; + +function fixture(privateKey: string = reference.privateKey): ArrayBuffer { + return Uint8Array.from(Buffer.from(privateKey, 'hex')).buffer; +} + +function importKey(raw: ArrayBuffer, variant: string = reference.variant) { + return createPrivateKeyAsync({ + key: raw, + format: 'raw-private', + asymmetricKeyType: variant.toLowerCase() as SlhDsaKeyPairType, + }); +} + +// Keep process-wide admission tests sequential even with the concurrent runner. +test(SUITE, 'imports validated handles with bounded admission', async () => { + for (const vector of vectors) { + const raw = fixture(vector.privateKey); + const pending = importKey(raw, vector.variant); + new Uint8Array(raw).fill(0); + const key = await pending; + try { + const publicKey = createPublicKey(key); + try { + expect( + publicKey.export({ format: 'raw-public' }).toString('hex'), + `${vector.variant} NIST case ${vector.testCase}`, + ).to.equal(vector.publicKey); + } finally { + publicKey.handle.dispose(); + } + } finally { + key.handle.dispose(); + } + } + const n = fixture().byteLength / 4; + // SK.prf is independent randomness, not a function of the public key (FIPS 205). + const changedPrf = fixture(); + const changedPrfBytes = new Uint8Array(changedPrf); + changedPrfBytes[n] = changedPrfBytes[n]! ^ 1; + const key = await importKey(changedPrf); + try { + const pub = createPublicKey(key); + try { + expect(pub.export({ format: 'raw-public' }).toString('hex')).to.equal( + reference.publicKey, + ); + const message = Buffer.from('SLH-DSA independent SK.prf'); + expect(verify(null, message, pub, sign(null, message, key))).to.equal( + true, + ); + } finally { + pub.handle.dispose(); + } + } finally { + key.handle.dispose(); + } + + for (const offset of [0, 2 * n, 3 * n]) { + const raw = fixture(); + const bytes = new Uint8Array(raw); + bytes[offset] = bytes[offset]! ^ 1; + await assertThrowsAsync(() => importKey(raw), error); + } + for (const value of [null, 1, {}, new Uint8Array(64)]) { + await assertThrowsAsync(() => importKey(value as ArrayBuffer), error); + } + for (const size of [0, 63, 65, 129]) { + await assertThrowsAsync(() => importKey(new ArrayBuffer(size)), error); + } + await assertThrowsAsync(() => importKey(fixture(), 'unknown'), error); + await assertThrowsAsync( + async () => + createPrivateKey({ + key: fixture(), + format: 'raw-private', + asymmetricKeyType: reference.variant.toLowerCase(), + }), + 'SLH-DSA raw private keys require createPrivateKeyAsync()', + ); + + const factory = + NitroModules.createHybridObject( + 'KeyObjectHandle', + ); + try { + for (const value of [null, 1, {}, new Uint8Array(64)]) { + await assertThrowsAsync( + async () => + factory.importSlhDsaRawPrivateKey( + reference.variant, + value as ArrayBuffer, + ), + error, + ); + } + await assertThrowsAsync( + async () => factory.importSlhDsaRawPrivateKey('unknown', fixture()), + error, + ); + const pending = factory.importSlhDsaRawPrivateKey( + reference.variant, + fixture(), + ); + let overlapping: Promise; + try { + overlapping = factory.importSlhDsaRawPrivateKey( + reference.variant, + fixture(), + ); + } catch (err) { + overlapping = Promise.reject(err); + } + const results = await Promise.allSettled([pending, overlapping]); + for (const result of results) { + if (result.status === 'fulfilled') { + expect( + Buffer.from(result.value.exportRawPublic()).toString('hex'), + ).to.equal(reference.publicKey); + result.value.dispose(); + } else { + expect(result.reason).to.be.instanceOf(Error); + expect((result.reason as Error).message).to.equal( + 'SLH-DSA raw private key import busy', + ); + } + } + // Worker scheduling can complete between calls; the native helper test + // holds admission explicitly to exercise deterministic busy rejection. + const reused = await factory.importSlhDsaRawPrivateKey( + reference.variant, + fixture(), + ); + expect(Buffer.from(reused.exportRawPublic()).toString('hex')).to.equal( + reference.publicKey, + ); + reused.dispose(); + // The factory never receives a copy of the imported secret. + await assertThrowsAsync( + async () => factory.exportRawPrivate(), + 'Invalid key object: no key data available', + ); + } finally { + factory.dispose(); + } +}); diff --git a/packages/react-native-quick-crypto/cpp/keys/HybridKeyObjectHandle.cpp b/packages/react-native-quick-crypto/cpp/keys/HybridKeyObjectHandle.cpp index 1b635bc1a..b562acdcb 100644 --- a/packages/react-native-quick-crypto/cpp/keys/HybridKeyObjectHandle.cpp +++ b/packages/react-native-quick-crypto/cpp/keys/HybridKeyObjectHandle.cpp @@ -1,3 +1,7 @@ +#include "../slhdsa/SlhDsaRawPrivateKeyValidation.hpp" +#include +#include +#include #include #include #include @@ -47,6 +51,110 @@ HybridKeyObjectHandle::HybridKeyObjectHandle() : HybridObject(TAG) { #endif } +facebook::jsi::Value HybridKeyObjectHandle::importSlhDsaRawPrivateKey(facebook::jsi::Runtime& runtime, const facebook::jsi::Value&, + const facebook::jsi::Value* args, size_t argCount) { + constexpr const char* error = "SLH-DSA raw private key validation failed"; + if (argCount != 2 || !args[0].isString() || !args[1].isObject()) { + throw facebook::jsi::JSError(runtime, error); + } + + try { + auto object = args[1].getObject(runtime); + // The typed Nitro converter checks the ArrayBuffer brand only in debug builds. + if (!object.isArrayBuffer(runtime)) { + throw std::invalid_argument(error); + } + auto buffer = std::move(object).getArrayBuffer(runtime); + const auto size = buffer.size(runtime); + const auto variant = args[0].getString(runtime).utf8(runtime); + const auto expectedSize = slhDsaRawPrivateKeySize(variant); + if (expectedSize == 0 || size != expectedSize) { + throw std::invalid_argument(error); + } + + // Fail before copying if this runtime cannot dispatch Promise callbacks. + Dispatcher::getRuntimeGlobalDispatcher(runtime); + auto validation = std::make_shared(variant, buffer.data(runtime), size); + using Result = std::shared_ptr; + using ValidationPromise = Promise; + using Resolve = JSIConverter>; + using Reject = JSIConverter>; + enum class Attachment { pending, failed, ready }; + auto attachment = std::make_shared(Attachment::pending); + auto promise = ValidationPromise::create(); + auto jsPromise = CommonGlobals::Promise::callConstructor( + runtime, [promise, attachment, error](facebook::jsi::Runtime& js, const facebook::jsi::Value&, + const facebook::jsi::Value* callbacks, size_t count) { + const bool first = *attachment == Attachment::pending; + *attachment = Attachment::failed; + if (!first || count != 2 || !Resolve::canConvert(js, callbacks[0]) || !Reject::canConvert(js, callbacks[1])) { + throw facebook::jsi::JSError(js, error); + } + auto resolve = Resolve::fromJSI(js, callbacks[0]); + auto reject = Reject::fromJSI(js, callbacks[1]); + promise->addOnResolvedListener(std::move(resolve)); + promise->addOnRejectedListener(std::move(reject)); + *attachment = Attachment::ready; + return facebook::jsi::Value::undefined(); + }); + // The JS constructor catches executor errors. A returned Promise by + // itself does not establish that a resolver and rejecter were attached. + if (*attachment != Attachment::ready) { + if (*attachment == Attachment::failed) + return jsPromise; + throw std::runtime_error(error); + } + + try { + ThreadPool::shared().run([validation = std::move(validation), promise]() mutable { + Result output; + try { + // The worker owns a synchronous copy, never a JS-backed buffer. + auto active = std::move(validation); + auto key = active->validate(); + auto handle = std::make_shared(); + handle->setKeyObjectData(KeyObjectData::CreateAsymmetric(KeyType::PRIVATE, ncrypto::EVPKeyPointer(key.release()))); + output = std::move(handle); + } catch (...) { + // The owned input has unwound before either callback can run. + promise->reject(std::current_exception()); + return; + } + promise->resolve(std::move(output)); + }); + } catch (...) { + validation.reset(); + try { + throw std::runtime_error(error); + } catch (...) { + promise->reject(std::current_exception()); + } + } + return jsPromise; + } catch (const SlhDsaRawPrivateKeyBusy& busy) { + throw facebook::jsi::JSError(runtime, busy.what()); + } catch (...) { + throw facebook::jsi::JSError(runtime, error); + } +} + +// Generated conversion omits release-mode ArrayBuffer brand checks and converts +// the returned Promise after entering native code. Admit work only after both +// the input and the JavaScript Promise callbacks have been checked. +void HybridKeyObjectHandle::loadHybridMethods() { + HybridKeyObjectHandleSpec::loadHybridMethods(); + registerHybrids(this, [](Prototype& prototype) { + prototype.registerRawHybridMethod("importSlhDsaRawPrivateKey", 2, &HybridKeyObjectHandle::importSlhDsaRawPrivateKey); + }); +} + +// All current operations on a key handle run synchronously on the JS thread. +// EVP contexts and KeyObjectData copies retain their own references; dropping +// this handle's reference must not invalidate those independent owners. +void HybridKeyObjectHandle::dispose() { + data_ = KeyObjectData(); +} + // Helper functions for base64url encoding/decoding with BIGNUMs static std::string bn_to_base64url(const BIGNUM* bn, size_t expected_size = 0) { if (!bn) @@ -1274,6 +1382,7 @@ bool HybridKeyObjectHandle::initPqcRaw(const std::string& algorithmName, const s if (isPublic) { pkey = ncrypto::EVPKeyPointer::NewRawPublic(nid, buffer); } else { + // This path derives a key from a seed, not a supplied complete private key. pkey = ncrypto::EVPKeyPointer::NewRawSeed(nid, buffer); } @@ -1368,6 +1477,8 @@ bool HybridKeyObjectHandle::initRawPublic(const std::string& asymmetricKeyType, bool HybridKeyObjectHandle::initRawPrivate(const std::string& asymmetricKeyType, const std::shared_ptr& keyData, const std::optional& namedCurve) { + if (asymmetricKeyType.starts_with("slh-dsa-") || asymmetricKeyType.starts_with("SLH-DSA-")) + throw std::runtime_error("SLH-DSA raw private keys require createPrivateKeyAsync()"); data_ = KeyObjectData(); if (asymmetricKeyType == "ec") { diff --git a/packages/react-native-quick-crypto/cpp/keys/HybridKeyObjectHandle.hpp b/packages/react-native-quick-crypto/cpp/keys/HybridKeyObjectHandle.hpp index 47a4a02c7..d8f97e7f2 100644 --- a/packages/react-native-quick-crypto/cpp/keys/HybridKeyObjectHandle.hpp +++ b/packages/react-native-quick-crypto/cpp/keys/HybridKeyObjectHandle.hpp @@ -16,6 +16,7 @@ namespace margelo::nitro::crypto { class HybridKeyObjectHandle : public HybridKeyObjectHandleSpec { public: HybridKeyObjectHandle(); + void dispose() override; public: std::shared_ptr exportKey(std::optional format, std::optional type, @@ -69,7 +70,12 @@ class HybridKeyObjectHandle : public HybridKeyObjectHandleSpec { data_ = std::move(data); } + protected: + void loadHybridMethods() override; + private: + facebook::jsi::Value importSlhDsaRawPrivateKey(facebook::jsi::Runtime& runtime, const facebook::jsi::Value& thisArg, + const facebook::jsi::Value* args, size_t argCount); KeyObjectData data_; bool initRawKey(KeyType keyType, std::shared_ptr keyData); diff --git a/packages/react-native-quick-crypto/cpp/slhdsa/HybridSlhDsaKeyPair.cpp b/packages/react-native-quick-crypto/cpp/slhdsa/HybridSlhDsaKeyPair.cpp index ef9db32db..1298025d9 100644 --- a/packages/react-native-quick-crypto/cpp/slhdsa/HybridSlhDsaKeyPair.cpp +++ b/packages/react-native-quick-crypto/cpp/slhdsa/HybridSlhDsaKeyPair.cpp @@ -6,8 +6,10 @@ #include #include +#include #include "QuickCryptoUtils.hpp" +#include "SlhDsaRawPrivateKeyValidation.hpp" #if OPENSSL_VERSION_NUMBER >= 0x30500000L #define RNQC_HAS_SLH_DSA 1 @@ -21,18 +23,8 @@ using EVP_MD_CTX_ptr = std::unique_ptr; using EVP_PKEY_CTX_ptr = std::unique_ptr; #if RNQC_HAS_SLH_DSA -static constexpr std::array kSlhDsaVariants{ - "SLH-DSA-SHA2-128s", "SLH-DSA-SHA2-128f", "SLH-DSA-SHA2-192s", "SLH-DSA-SHA2-192f", "SLH-DSA-SHA2-256s", "SLH-DSA-SHA2-256f", - "SLH-DSA-SHAKE-128s", "SLH-DSA-SHAKE-128f", "SLH-DSA-SHAKE-192s", "SLH-DSA-SHAKE-192f", "SLH-DSA-SHAKE-256s", "SLH-DSA-SHAKE-256f", -}; - static bool isValidSlhDsaVariant(const std::string& variant) { - for (const char* v : kSlhDsaVariants) { - if (variant == v) { - return true; - } - } - return false; + return slhDsaRawPrivateKeySize(variant) != 0; } #endif diff --git a/packages/react-native-quick-crypto/cpp/slhdsa/SlhDsaRawPrivateKeyValidation.hpp b/packages/react-native-quick-crypto/cpp/slhdsa/SlhDsaRawPrivateKeyValidation.hpp new file mode 100644 index 000000000..5cbfc007f --- /dev/null +++ b/packages/react-native-quick-crypto/cpp/slhdsa/SlhDsaRawPrivateKeyValidation.hpp @@ -0,0 +1,108 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace margelo::nitro::crypto { + +inline std::size_t slhDsaRawPrivateKeySize(std::string_view variant) { + static constexpr std::array, 12> variants{{ + {"SLH-DSA-SHA2-128s", 64}, + {"SLH-DSA-SHA2-128f", 64}, + {"SLH-DSA-SHA2-192s", 96}, + {"SLH-DSA-SHA2-192f", 96}, + {"SLH-DSA-SHA2-256s", 128}, + {"SLH-DSA-SHA2-256f", 128}, + {"SLH-DSA-SHAKE-128s", 64}, + {"SLH-DSA-SHAKE-128f", 64}, + {"SLH-DSA-SHAKE-192s", 96}, + {"SLH-DSA-SHAKE-192f", 96}, + {"SLH-DSA-SHAKE-256s", 128}, + {"SLH-DSA-SHAKE-256f", 128}, + }}; + for (const auto& [name, size] : variants) { + if (variant == name) + return size; + } + return 0; +} + +class SlhDsaRawPrivateKeyBusy final : public std::runtime_error { + public: + SlhDsaRawPrivateKeyBusy() : std::runtime_error("SLH-DSA raw private key import busy") {} +}; + +// One bounded owned secret and one queued/running validation across runtimes. +class SlhDsaRawPrivateKeyValidation final { + public: + SlhDsaRawPrivateKeyValidation(std::string variant, const uint8_t* input, std::size_t size) + : variant_(std::move(variant)), size_(slhDsaRawPrivateKeySize(variant_)) { + if (input == nullptr || size_ == 0 || size != size_) + fail(); + if (inFlight_.test_and_set(std::memory_order_acquire)) + throw SlhDsaRawPrivateKeyBusy(); + std::copy_n(input, size_, secret_.begin()); + } + + ~SlhDsaRawPrivateKeyValidation() { + OPENSSL_cleanse(secret_.data(), secret_.size()); + inFlight_.clear(std::memory_order_release); + } + + SlhDsaRawPrivateKeyValidation(const SlhDsaRawPrivateKeyValidation&) = delete; + SlhDsaRawPrivateKeyValidation& operator=(const SlhDsaRawPrivateKeyValidation&) = delete; + + using Key = std::unique_ptr; + + Key validate() const { +#if OPENSSL_VERSION_NUMBER >= 0x30600000L + struct ErrorScope { + ErrorScope() { + ERR_clear_error(); + } + ~ErrorScope() { + ERR_clear_error(); + } + } errors; + using Context = std::unique_ptr; + Key key(EVP_PKEY_new_raw_private_key_ex(nullptr, variant_.c_str(), nullptr, secret_.data(), size_), EVP_PKEY_free); + if (!key || EVP_PKEY_is_a(key.get(), variant_.c_str()) != 1) + fail(); + const Context context(EVP_PKEY_CTX_new_from_pkey(nullptr, key.get(), nullptr), EVP_PKEY_CTX_free); + // Raw import accepts a supplied root. The provider must verify consistency. + if (!context || EVP_PKEY_pairwise_check(context.get()) != 1) + fail(); + std::vector publicKey(size_ / 2); + std::size_t size = publicKey.size(); + if (EVP_PKEY_get_raw_public_key(key.get(), publicKey.data(), &size) != 1 || size != publicKey.size() || + CRYPTO_memcmp(publicKey.data(), secret_.data() + size_ - publicKey.size(), publicKey.size()) != 0) + fail(); + return key; +#else + fail(); +#endif + } + + private: + [[noreturn]] static void fail() { + throw std::runtime_error("SLH-DSA raw private key validation failed"); + } + inline static std::atomic_flag inFlight_ = ATOMIC_FLAG_INIT; + std::string variant_; + std::size_t size_; + std::array secret_{}; +}; + +} // namespace margelo::nitro::crypto diff --git a/packages/react-native-quick-crypto/src/keys/index.ts b/packages/react-native-quick-crypto/src/keys/index.ts index 8baf99071..dea3b0228 100644 --- a/packages/react-native-quick-crypto/src/keys/index.ts +++ b/packages/react-native-quick-crypto/src/keys/index.ts @@ -37,6 +37,11 @@ import { KeyType, } from '../utils'; import { randomBytes } from '../random'; +import type { + SlhDsaKeyPairType, + SlhDsaPrivateKeyFactoryHandle, +} from '../utils'; +import { SLH_DSA_VARIANTS } from '../slhdsa'; interface KeyInputObject { key: BinaryLike | KeyObject | CryptoKey | JWK; @@ -78,6 +83,52 @@ function createPublicKeyFromRaw(input: KeyInputObject): PublicKeyObject { return new PublicKeyObject(handle); } +/** RNQC extension: validates and imports a complete SLH-DSA key off-thread. + * The native call snapshots the ArrayBuffer before this function returns. + */ +export async function createPrivateKeyAsync(input: { + key: ArrayBuffer; + format: 'raw-private'; + asymmetricKeyType: SlhDsaKeyPairType; +}): Promise { + const error = 'SLH-DSA raw private key validation failed'; + if ( + !input || + input.format !== 'raw-private' || + typeof input.asymmetricKeyType !== 'string' + ) { + throw new Error(error); + } + const variant = SLH_DSA_VARIANTS.find( + v => v.toLowerCase() === input.asymmetricKeyType, + ); + if (!variant) throw new Error(error); + const byteLength = Object.getOwnPropertyDescriptor( + ArrayBuffer.prototype, + 'byteLength', + )!.get!; + try { + Reflect.apply(byteLength, input.key, []); + } catch { + throw new Error(error); + } + const factory = + NitroModules.createHybridObject( + 'KeyObjectHandle', + ); + try { + const handle = await factory.importSlhDsaRawPrivateKey(variant, input.key); + try { + return new PrivateKeyObject(handle); + } catch (err) { + handle.dispose(); + throw err; + } + } finally { + factory.dispose(); + } +} + function createPrivateKeyFromRaw(input: KeyInputObject): PrivateKeyObject { if (input.format !== 'raw-private' && input.format !== 'raw-seed') { throw new Error('Invalid format for createPrivateKey raw import'); @@ -85,6 +136,12 @@ function createPrivateKeyFromRaw(input: KeyInputObject): PrivateKeyObject { if (typeof input.asymmetricKeyType !== 'string') { throw new Error('options.asymmetricKeyType is required for raw key import'); } + if ( + input.format === 'raw-private' && + input.asymmetricKeyType.toLowerCase().startsWith('slh-dsa-') + ) { + throw new Error('SLH-DSA raw private keys require createPrivateKeyAsync()'); + } if (input.asymmetricKeyType === 'ec' && !input.namedCurve) { throw new Error('options.namedCurve is required for EC raw key import'); } diff --git a/packages/react-native-quick-crypto/src/utils/types.ts b/packages/react-native-quick-crypto/src/utils/types.ts index d56b5f217..46ce07081 100644 --- a/packages/react-native-quick-crypto/src/utils/types.ts +++ b/packages/react-native-quick-crypto/src/utils/types.ts @@ -555,6 +555,14 @@ export type CipherOFBType = 'aes-128-ofb' | 'aes-192-ofb' | 'aes-256-ofb'; export type KeyObjectHandle = KeyObjectHandleType; +// Raw JSI factory method: brand checks and callback attachment precede admission. +export interface SlhDsaPrivateKeyFactoryHandle extends KeyObjectHandleType { + importSlhDsaRawPrivateKey( + variant: string, + key: ArrayBuffer, + ): Promise; +} + export type RawDiffieHellmanKeyInput = { key: ArrayBuffer | ArrayBufferView | string; format: 'raw-public' | 'raw-private' | 'raw-seed'; diff --git a/packages/react-native-quick-crypto/test/native/slhdsa_raw_private_admission.cpp b/packages/react-native-quick-crypto/test/native/slhdsa_raw_private_admission.cpp new file mode 100644 index 000000000..42f667671 --- /dev/null +++ b/packages/react-native-quick-crypto/test/native/slhdsa_raw_private_admission.cpp @@ -0,0 +1,45 @@ +// Standalone regression test. Link with OpenSSL libcrypto; no React Native or +// ncrypto dependency is needed. This tests admission, not provider validation. +// From the package directory (with libcrypto pkg-config configured): +// c++ -std=c++20 test/native/slhdsa_raw_private_admission.cpp $(pkg-config --cflags --libs libcrypto) -o /tmp/rnqc-slh-admission +#include "../../cpp/slhdsa/SlhDsaRawPrivateKeyValidation.hpp" + +#include +#include +#include + +using margelo::nitro::crypto::SlhDsaRawPrivateKeyBusy; +using margelo::nitro::crypto::SlhDsaRawPrivateKeyValidation; + +static void expectBusy(const std::array& raw) { + try { + SlhDsaRawPrivateKeyValidation second("SLH-DSA-SHAKE-128s", raw.data(), raw.size()); + } catch (const SlhDsaRawPrivateKeyBusy& error) { + if (std::string_view(error.what()) == "SLH-DSA raw private key import busy") + return; + throw; + } + throw std::runtime_error("Overlapping admission did not reject as busy"); +} + +int main() { + const std::array raw{}; + { + SlhDsaRawPrivateKeyValidation first("SLH-DSA-SHAKE-128s", raw.data(), raw.size()); + expectBusy(raw); + try { + SlhDsaRawPrivateKeyValidation invalid("unsupported", raw.data(), raw.size()); + throw std::logic_error("Invalid variant was admitted"); + } catch (const std::runtime_error& error) { + if (std::string_view(error.what()) != "SLH-DSA raw private key validation failed") + throw; + } + // A failed constructor must not clear another job's process-wide admission. + expectBusy(raw); + } + { + SlhDsaRawPrivateKeyValidation readmitted("SLH-DSA-SHAKE-128s", raw.data(), raw.size()); + expectBusy(raw); + } + SlhDsaRawPrivateKeyValidation readmittedAgain("SLH-DSA-SHAKE-128s", raw.data(), raw.size()); +}