Compile ML-KEM keys and KEM operations (#3842)

* Compile ML-KEM keys and KEM operations

* Fix ML-KEM async failures, key import and unit selection

* Read decapsulate ciphertexts through Node's argument rules

* Make raw key export robust for ML-KEM keys
This commit is contained in:
Chris Tate
2026-11-18 21:44:52 -06:00
committed by GitHub
parent aa302e24ad
commit 7af60dd09f
29 changed files with 991 additions and 28 deletions
@@ -11273,9 +11273,9 @@
"inherited": true
},
"static": {
"status": "not-implemented",
"detail": "No static compiler lowering is registered for this API yet.",
"verification": "registry-gap"
"status": "partial",
"detail": "Implemented for the call shapes accepted by the compiler lowering.",
"verification": "test-backed"
}
},
{
@@ -11319,9 +11319,9 @@
"inherited": true
},
"static": {
"status": "not-implemented",
"detail": "No static compiler lowering is registered for this API yet.",
"verification": "registry-gap"
"status": "partial",
"detail": "Implemented for the call shapes accepted by the compiler lowering.",
"verification": "test-backed"
}
},
{
@@ -20246,6 +20246,7 @@
"evidence": "derived:descendants",
"tests": [
"tests/corpus/1358-crypto-random.ts",
"tests/corpus/1534-crypto-hash-chain.ts",
"tests/corpus/1568-x509-fingerprint.ts",
"tests/corpus/1572-x509-validity-date-gettime.ts",
"tests/corpus/2556-crypto-introspection.ts",
@@ -21273,8 +21274,23 @@
"inherited": true
},
"static": {
"status": "not-implemented",
"evidence": "compiler-unmatched:crypto"
"status": "partial",
"evidence": "surface-manifest:node-builtin.crypto.decapsulate",
"tests": [
"tests/corpus/crypto-argon2.ts",
"tests/corpus/key-object-to-crypto-key.ts",
"tests/corpus/key-object-from-crypto-key.ts",
"tests/corpus/key-object-from-arguments.mjs",
"tests/corpus/1358-crypto-random.ts",
"tests/corpus/1534-crypto-hash-chain.ts",
"tests/corpus/2556-crypto-introspection.ts",
"tests/corpus/2890-crypto-static-utility.ts",
"tests/harness/npm-static.test.ts",
"tests/corpus/node24-crypto-sha2.ts",
"tests/corpus/node24-crypto-kdf.ts",
"tests/corpus/node24-crypto-kdf-errors.ts",
"tests/corpus/node24-crypto-kdf-options.ts"
]
},
"anchorSource": "exact"
},
@@ -21330,8 +21346,23 @@
"inherited": true
},
"static": {
"status": "not-implemented",
"evidence": "compiler-unmatched:crypto"
"status": "partial",
"evidence": "surface-manifest:node-builtin.crypto.encapsulate",
"tests": [
"tests/corpus/crypto-argon2.ts",
"tests/corpus/key-object-to-crypto-key.ts",
"tests/corpus/key-object-from-crypto-key.ts",
"tests/corpus/key-object-from-arguments.mjs",
"tests/corpus/1358-crypto-random.ts",
"tests/corpus/1534-crypto-hash-chain.ts",
"tests/corpus/2556-crypto-introspection.ts",
"tests/corpus/2890-crypto-static-utility.ts",
"tests/harness/npm-static.test.ts",
"tests/corpus/node24-crypto-sha2.ts",
"tests/corpus/node24-crypto-kdf.ts",
"tests/corpus/node24-crypto-kdf-errors.ts",
"tests/corpus/node24-crypto-kdf-options.ts"
]
},
"anchorSource": "exact"
},
+22
View File
@@ -251,6 +251,10 @@ declare module "crypto" {
options: X448KeyPairOptions<"der", "der">,
): KeyPairSyncResult<Buffer, Buffer>;
export function generateKeyPairSync(type: "x448", options?: {}): KeyPairKeyObjectResult;
export function generateKeyPairSync(
type: "ml-kem-512" | "ml-kem-768" | "ml-kem-1024",
options?: {},
): KeyPairKeyObjectResult;
export function generateKeyPair(
type: "x25519",
options: {} | undefined,
@@ -266,6 +270,24 @@ declare module "crypto" {
options: {} | undefined,
callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void,
): void;
export function generateKeyPair(
type: "ml-kem-512" | "ml-kem-768" | "ml-kem-1024",
options: {} | undefined,
callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void,
): void;
/* crypto.encapsulate/decapsulate: the KEM wrappers. Packet installments
* implement ML-KEM first; the other KEM-capable key types follow. */
export function encapsulate(key: KeyObject): { sharedKey: Buffer; ciphertext: Buffer };
export function encapsulate(
key: KeyObject,
callback: (error: Error | null, result: { sharedKey: Buffer; ciphertext: Buffer }) => void,
): void;
export function decapsulate(key: KeyObject, ciphertext: ArrayBuffer | ScriptcBufferView): Buffer;
export function decapsulate(
key: KeyObject,
ciphertext: ArrayBuffer | ScriptcBufferView,
callback: (error: Error | null, sharedKey: Buffer) => void,
): void;
export function generateKeyPair(
type: "rsa",
options: RSAKeyPairKeyObjectOptions,
@@ -1603,6 +1603,8 @@ export const LIB_FN_SYMS: Record<string, string> = {
"crypto.signOneshotCb": "scr_crypto_sign_oneshot_async",
"crypto.signOneshotMaybe": "scr_crypto_sign_oneshot_maybe",
"crypto.diffieHellman": "scr_crypto_diffie_hellman",
"crypto.encapsulate": "scr_crypto_encapsulate_dyn",
"crypto.decapsulate": "scr_crypto_decapsulate_dyn",
"crypto.verifyOneshot": "scr_crypto_verify_oneshot",
"crypto.verifyOneshotCb": "scr_crypto_verify_oneshot_async",
"crypto.verifyOneshotMaybe": "scr_crypto_verify_oneshot_maybe",
@@ -2382,6 +2384,8 @@ export const USES_TIMERS_LIB_FNS = new Set<IrLibFn>([
"crypto.verifyOneshotCb",
"crypto.verifyOneshotMaybe",
"crypto.diffieHellman",
"crypto.encapsulate",
"crypto.decapsulate",
"crypto.checkPrimeCb",
"crypto.generatePrimeCb",
// The checked-dynamic KDF and random entries deliver a callback from the
@@ -489,6 +489,14 @@ export const LINK_FEATURE_REQUIREMENTS: readonly LinkFeatureRequirement[] = [
// listeners), so the iterator unit brings the checked-dynamic async unit
// with it.
{ feature: "watchEvents", requires: ["watch", "dynAsync"] },
// scr_mlkem.c installs the vendored core's hook table that the pki unit
// reads for ML-KEM keys, and the table's storage lives in the pki unit:
// the two units select each other. The pki unit takes the algorithm and
// the encoded key at run time (generateKeyPairSync's type,
// createPrivateKey's DER), so a program that never spells a parameter set
// still needs the hook when it can reach one.
{ feature: "pki", requires: ["mlkem"] },
{ feature: "mlkem", requires: ["pki"] },
// scr_fs_web_stream.c reads through the FileHandle unit; the web stream
// unit comes with it through executable-features' webStreams OR.
{ feature: "fsWebStream", requires: ["fileHandle"] },
@@ -84,6 +84,7 @@ import {
currentVendorCacheBuildIdentity,
vendorBuildCacheRoot,
tlsArchivePath,
vendorMlkemDir,
mlkemArchivePath,
ensureMlkemArchive,
brotliArchivePath,
@@ -345,8 +346,6 @@ const RUNTIME_UNITS: readonly RuntimeUnit[] = [
? []
: ["-I", join(vendorZstdDir(), "lib"), u.rt(join(u.rtDir, "scr_zstd.c")), ...u.zstdObjects],
),
// ML-KEM (scr_mlkem.c): the vendored mlkem-native archive.
unitArgs((u) => (u.mlkemArchive === null ? [] : [u.mlkemArchive])),
// node:sqlite (scr_sqlite.c) over the vendored SQLite amalgamation.
unitArgs((u) =>
u.sqliteArchive === null
@@ -526,6 +525,9 @@ const RUNTIME_UNITS: readonly RuntimeUnit[] = [
unit((u) => u.opts.x509 === true, "scr_x509.c"),
// Argon2 (crypto.argon2 and crypto.argon2Sync) is self-contained.
unit((u) => u.opts.argon2 === true, "scr_argon2.c"),
// ML-KEM (node:crypto's encapsulate/decapsulate and WebCrypto): the
// wrapper unit over the vendored mlkem-native archive.
unit((u) => u.opts.mlkem === true, "scr_mlkem.c"),
// The TLS socket certificate accessors read scr_tls.c and build with scr_x509.c.
unit((u) => u.tls && u.opts.x509 === true, "scr_tls_x509.c"),
// The crypto global's object extends scr_async_dyn.c's.
@@ -1184,6 +1186,7 @@ export async function compileCInternal(
"-Wno-deprecated-declarations", // ucontext fibers (scr_async.c)
"-I",
rtDir,
...(mlkem ? ["-I", vendorMlkemDir(), "-I", join(vendorMlkemDir(), "src")] : []),
...runtimeSources.map((f) => rt(join(rtDir, f))),
...runtimeUnitArgs({
opts,
@@ -1211,6 +1214,8 @@ export async function compileCInternal(
icuArchive,
icuIncludeDirs,
}),
// The ML-KEM cores follow the wrapper that references them.
...(mlkemArchive !== null ? [mlkemArchive] : []),
// A .ll program TU (the LLVM backend) deliberately carries no target
// triple (byte-stable output; clang supplies the host/SCRIPTC_TARGET
// triple exactly as it does for .c) — silence the -Woverride-module
@@ -1258,6 +1263,7 @@ export async function compileCInternal(
...(regex ? ["-I", vendorEngineDir()] : []),
...(zlibObjects.length > 0 ? ["-I", vendorZlibDir()] : []),
...(tlsArchive !== null ? ["-I", join(vendorTlsDir(), "include")] : []),
...(mlkem ? ["-I", vendorMlkemDir(), "-I", join(vendorMlkemDir(), "src")] : []),
...(sqliteArchive !== null ? ["-I", vendorSqliteDir()] : []),
...icuIncludeDirs.flatMap((dir) => ["-I", dir]),
];
@@ -1851,6 +1851,8 @@ function lowerPkiCall(
privateEncrypt: ["crypto.privateEncrypt", 2, 2, "privateEncrypt(key, buffer)"],
publicDecrypt: ["crypto.publicDecrypt", 2, 2, "publicDecrypt(key, buffer)"],
diffieHellman: ["crypto.diffieHellman", 1, 2, "diffieHellman(options[, callback])"],
encapsulate: ["crypto.encapsulate", 0, 2, "encapsulate(key[, callback])"],
decapsulate: ["crypto.decapsulate", 0, 3, "decapsulate(key, ciphertext[, callback])"],
createSign: ["crypto.createSign", 0, 2, "createSign(algorithm[, options])"],
createVerify: ["crypto.createVerify", 0, 2, "createVerify(algorithm[, options])"],
setEngine: ["crypto.setEngine", 1, 2, "setEngine(engine[, flags])"],
@@ -1754,6 +1754,8 @@ function buildBuiltinModuleFns(): BuiltinModuleFnTable {
privateEncrypt: { fn: "crypto.privateEncrypt", params: [], result: DYN },
publicDecrypt: { fn: "crypto.publicDecrypt", params: [], result: DYN },
diffieHellman: { fn: "crypto.diffieHellman", params: [], result: DYN },
encapsulate: { fn: "crypto.encapsulate", params: [], result: DYN },
decapsulate: { fn: "crypto.decapsulate", params: [], result: DYN },
pbkdf2Sync: {
fn: "crypto.pbkdf2",
params: [BYTES_U8, BYTES_U8, F64, F64, STRING],
@@ -1762,6 +1762,8 @@ const MAY_THROW_LIB_FNS_PART_6: readonly IrLibFn[] = [
"crypto.createPublicKey",
"crypto.generateKeyPairSync",
"crypto.generateKeyPairCb",
"crypto.encapsulate",
"crypto.decapsulate",
// Argon2 reads its parameters object (whose members convert strings and
// BufferSources) and may run program code through those conversions.
"crypto.argon2Sync",
@@ -7224,6 +7224,8 @@ function buildLibFnSignatures() {
"crypto.createPrivateKey": { argTypes: [DYN], result: DYN },
"crypto.createPublicKey": { argTypes: [DYN], result: DYN },
"crypto.generateKeyPairSync": { argTypes: [DYN, DYN], result: DYN },
"crypto.encapsulate": { argTypes: [DYN, DYN], result: DYN },
"crypto.decapsulate": { argTypes: [DYN, DYN, DYN], result: DYN },
"crypto.generateKeyPairCb": { argTypes: [DYN, DYN, DYN], result: VOID },
"crypto.signOneshot": { argTypes: [DYN, DYN, DYN], result: DYN },
"crypto.signOneshotCb": { argTypes: [DYN, DYN, DYN, DYN], result: VOID },
+23 -3
View File
@@ -1119,6 +1119,8 @@ export const PKI_LIB_FNS: ReadonlySet<IrLibFn> = new Set([
"crypto.spkacChallenge",
"crypto.spkacPublicKey",
"crypto.diffieHellman",
"crypto.encapsulate",
"crypto.decapsulate",
]);
/** The WebCrypto algorithms scr_webcrypto_pki.c implements over the pki
@@ -1147,6 +1149,21 @@ function ed25519NameScan(): RuleScan {
};
}
/** Whether a string literal names an ML-KEM parameter set (the node:crypto
* key types "ml-kem-512/768/1024" and the WebCrypto/JWK algorithm names
* "ML-KEM-<n>"): the mlkem unit links then, and with it the pki unit its
* hook installs into. */
function mlkemNameScan(): RuleScan {
let named = false;
return {
expr: (node) => {
if (!named && node.kind === "strLit" && node.value.toLowerCase().startsWith("ml-kem"))
named = true;
},
result: () => named,
};
}
/** tty.WriteStream's color methods, which the process stream object has
* only in the build a program that names them selects. */
const TERMINAL_COLOR_METHODS: ReadonlySet<string> = new Set(["getColorDepth", "hasColors"]);
@@ -2143,9 +2160,12 @@ const RUNTIME_FEATURE_RULES = {
dh: rule({ fns: [...DH_LIB_FNS] }),
/** Argon2: scr_argon2.c. */
argon2: rule({ fns: ["crypto.argon2Sync", "crypto.argon2Cb"] }),
/** ML-KEM (mlkem-native): selected by the node:crypto encapsulate and
* WebCrypto ML-KEM lowerings, and links the vendored archive. */
mlkem: rule({ fns: [] }),
/** ML-KEM (mlkem-native): links the vendored archive and the scr_mlkem.c
* wrapper when a string literal names a parameter set or the program
* encapsulates/decapsulates through pki; the wrapper and the pki unit
* select each other (LINK_FEATURE_REQUIREMENTS), since pki reaches ML-KEM
* by run-time algorithm and key names. */
mlkem: rule({ fns: ["crypto.encapsulate", "crypto.decapsulate"], scan: mlkemNameScan }),
emitter: rule({
initial: (mod) =>
mod.workers === true || (mod.classes ?? []).some((c) => c.name === RUNTIME_EMITTER_CLASS),
+12
View File
@@ -611,12 +611,24 @@
"name": "crypto.createVerify",
"status": "static"
},
{
"id": "node-builtin.crypto.decapsulate",
"kind": "node-builtin",
"name": "crypto.decapsulate",
"status": "static"
},
{
"id": "node-builtin.crypto.diffieHellman",
"kind": "node-builtin",
"name": "crypto.diffieHellman",
"status": "static"
},
{
"id": "node-builtin.crypto.encapsulate",
"kind": "node-builtin",
"name": "crypto.encapsulate",
"status": "static"
},
{
"id": "node-builtin.crypto.generateKey",
"kind": "node-builtin",
@@ -0,0 +1,6 @@
{
"order": [
"<repo>/tests/corpus/crypto-ml-kem-callback-errors.ts"
],
"diags": []
}
@@ -0,0 +1,6 @@
{
"order": [
"<repo>/tests/corpus/crypto-ml-kem-callbacks.ts"
],
"diags": []
}
@@ -0,0 +1,6 @@
{
"order": [
"<repo>/tests/corpus/crypto-ml-kem-literal.ts"
],
"diags": []
}
@@ -0,0 +1,6 @@
{
"order": [
"<repo>/tests/corpus/crypto-ml-kem-runtime-input.ts"
],
"diags": []
}
@@ -0,0 +1,6 @@
{
"order": [
"<repo>/tests/corpus/crypto-ml-kem.ts"
],
"diags": []
}
@@ -99,6 +99,8 @@ export const OPTIONAL_RUNTIME_SOURCES = [
["scr_idna.c", "regex"],
// crypto.argon2 and crypto.argon2Sync.
["scr_argon2.c", "argon2"],
// ML-KEM (node:crypto encapsulate/decapsulate and WebCrypto).
["scr_mlkem.c", "mlkem"],
// The worker unit's SHARE_ENV symbol reaches the symbol unit
// (scr_worker_events.c), which assembles symbol equality messages here.
["scr_assert.c", any("assert", "regex", "symbol", "workers")],
+2
View File
@@ -340,6 +340,8 @@ ScrDyn *scr_wc_key_object_to_crypto_key(ScrDyn *args);
ScrDyn *scr_wc_key_object_from(ScrDyn *args);
/* crypto.argon2 and crypto.argon2Sync (scr_argon2.c): the argument vector. */
ScrDyn *scr_crypto_argon2_sync(ScrDyn *args);
ScrDyn *scr_crypto_encapsulate_dyn(ScrDyn *key, ScrDyn *callback);
ScrDyn *scr_crypto_decapsulate_dyn(ScrDyn *key, ScrDyn *ciphertext, ScrDyn *callback);
ScrDyn *scr_crypto_argon2_cb(ScrDyn *args);
ScrPromise *scr_webcrypto_verify(ScrDyn *args);
ScrPromise *scr_webcrypto_digest(ScrDyn *args);
+60
View File
@@ -0,0 +1,60 @@
/* ML-KEM (FIPS 203) on the vendored mlkem-native core (mlkem/), whose C
* backend the compiler builds once per parameter set in the mlkem vendor
* archive. This unit maps the runtime's level argument to those symbols,
* supplies the random-byte hook the randomized entry points reference, and
* installs the core the pki unit reaches ML-KEM keys through, so a program
* that never names an ML-KEM algorithm links neither this unit nor the
* archive. */
#include "scr_runtime.h"
#include "scr_pki.h"
/* The vendored API, namespaced per parameter set (numeric level). */
#define SCR_MLKEM_DECL(level) \
int PQCP_MLKEM_NATIVE_MLKEM##level##_keypair_derand(uint8_t *pk, uint8_t *sk, \
const uint8_t coins[64]); \
int PQCP_MLKEM_NATIVE_MLKEM##level##_enc_derand(uint8_t *ct, uint8_t *ss, const uint8_t *pk, \
const uint8_t coins[32]); \
int PQCP_MLKEM_NATIVE_MLKEM##level##_dec(uint8_t *ss, const uint8_t *ct, const uint8_t *sk)
SCR_MLKEM_DECL(512);
SCR_MLKEM_DECL(768);
SCR_MLKEM_DECL(1024);
/* mlkem_native.c's randomized entry points reference this hook; the runtime
* draws from its cryptographically secure source. */
int randombytes(uint8_t *out, size_t outlen) {
ScrBytes *bytes = scr_crypto_random_bytes((double)outlen);
if (!bytes) return -1;
if (outlen != 0) memcpy(out, bytes->data, outlen);
scr_bytes_release(bytes);
return 0;
}
static bool scr_mlkem_keypair_derand(int level, uint8_t *pk, uint8_t *sk, const uint8_t seed[64]) {
if (level == 512) return PQCP_MLKEM_NATIVE_MLKEM512_keypair_derand(pk, sk, seed) == 0;
if (level == 768) return PQCP_MLKEM_NATIVE_MLKEM768_keypair_derand(pk, sk, seed) == 0;
return PQCP_MLKEM_NATIVE_MLKEM1024_keypair_derand(pk, sk, seed) == 0;
}
static bool scr_mlkem_encapsulate(int level, uint8_t *ct, uint8_t shared[32], const uint8_t *pk,
const uint8_t seed[32]) {
if (level == 512) return PQCP_MLKEM_NATIVE_MLKEM512_enc_derand(ct, shared, pk, seed) == 0;
if (level == 768) return PQCP_MLKEM_NATIVE_MLKEM768_enc_derand(ct, shared, pk, seed) == 0;
return PQCP_MLKEM_NATIVE_MLKEM1024_enc_derand(ct, shared, pk, seed) == 0;
}
static bool scr_mlkem_decapsulate(int level, uint8_t shared[32], const uint8_t *ct,
const uint8_t *sk) {
if (level == 512) return PQCP_MLKEM_NATIVE_MLKEM512_dec(shared, ct, sk) == 0;
if (level == 768) return PQCP_MLKEM_NATIVE_MLKEM768_dec(shared, ct, sk) == 0;
return PQCP_MLKEM_NATIVE_MLKEM1024_dec(shared, ct, sk) == 0;
}
static const ScrPkiMlkemCore scr_mlkem_core = {
.keypair_derand = scr_mlkem_keypair_derand,
.encapsulate = scr_mlkem_encapsulate,
.decapsulate = scr_mlkem_decapsulate,
};
__attribute__((constructor)) static void scr_mlkem_install(void) {
scr_pki_mlkem_core = &scr_mlkem_core;
}
+522 -13
View File
@@ -227,6 +227,13 @@ typedef struct SpKey {
bool x448;
uint8_t x448_seed[56];
uint8_t x448_pub[56];
/* An ML-KEM key: the 64-byte seed Node's PKCS#8/JWK encode, and the
* expanded public and secret keys the vendored core derives from it. */
bool mlkem;
int mlkem_level;
uint8_t mlkem_seed[64];
uint8_t mlkem_pk[1568];
uint8_t mlkem_sk[3168];
/* An RSA-PSS key (id-RSASSA-PSS): signatures only, with PSS padding.
* With RSASSA-PSS-params it signs only with pss_md and MGF1 over
* pss_mgf1, and salts of at least pss_salt bytes. */
@@ -292,6 +299,7 @@ static bool sp_is_ed(const SpKey *k) { return k->ed25519; }
static bool sp_is_x(const SpKey *k) { return k->x25519; }
static bool sp_is_x448(const SpKey *k) { return k->x448; }
static bool sp_is_mlkem(const SpKey *k) { return k->mlkem; }
/* The OKP key material and its size: X25519 32 bytes, X448 56. */
static const uint8_t *sp_okp_seed(const SpKey *k) { return k->x448 ? k->x448_seed : k->ed_seed; }
static uint8_t *sp_okp_pub_mut(SpKey *k) { return k->x448 ? k->x448_pub : k->ed_pub; }
@@ -321,6 +329,24 @@ static const char *sp_pss_md_name(mbedtls_md_type_t md) {
/* An Ed25519 or X25519 key: 32-byte private and public keys, no details. */
static bool sp_is_okp(const SpKey *k) { return k->ed25519 || k->x25519 || k->x448; }
/* ML-KEM levels as Node names them. */
static const char *sp_mlkem_name(int level) {
return level == 512 ? "ml-kem-512" : level == 768 ? "ml-kem-768" : "ml-kem-1024";
}
const ScrPkiMlkemCore *scr_pki_mlkem_core = NULL;
static size_t sp_mlkem_pk_bytes(int level) {
return level == 512 ? 800 : level == 768 ? 1184 : 1568;
}
static size_t sp_mlkem_sk_bytes(int level) {
return level == 512 ? 1632 : level == 768 ? 2400 : 3168;
}
static size_t sp_mlkem_ct_bytes(int level) {
return level == 512 ? 768 : level == 768 ? 1088 : 1568;
}
static const char *sp_mlkem_alg(int level);
static SpKey *sp_mlkem_from_jwk(const ScrDyn *jwk, bool private_key);
/* X448(scalar, point) per RFC 7748 over mbedTLS's Curve448 group, or of the
* base point when point is NULL; the Montgomery ladder needs the RNG. */
@@ -412,7 +438,8 @@ static const SpCurve *sp_curve_of(const SpKey *k) {
/* A parsed key is usable when it is RSA or EC on a curve above. */
static bool sp_key_supported(const SpKey *k) {
return sp_is_okp(k) || sp_is_rsa(k) || (sp_is_ec(k) && sp_curve_of(k) != NULL);
return sp_is_okp(k) || sp_is_mlkem(k) || sp_is_rsa(k) ||
(sp_is_ec(k) && sp_curve_of(k) != NULL);
}
/* ── DER writing ──────────────────────────────────────────────────────── */
@@ -457,6 +484,69 @@ static int sp_write_ed_der(const uint8_t *prefix, size_t prefix_len, const uint8
return sp_write_okp_der(prefix, prefix_len, key, 32, buf, size);
}
/* ML-KEM's AlgorithmIdentifier OID (2.16.840.1.101.3.4.4.1/2/3). */
static void sp_mlkem_oid(int level, unsigned char oid[9]) {
static const unsigned char base[9] = {0x60, 0x86, 0x48, 0x01, 0x65,
0x03, 0x04, 0x04, 0x01};
memcpy(oid, base, sizeof base);
oid[8] = (unsigned char)(level == 512 ? 1 : level == 768 ? 2 : 3);
}
static int sp_write_mlkem_spki(SpKey *k, unsigned char *buf, size_t size) {
size_t n = sp_mlkem_pk_bytes(k->mlkem_level);
unsigned char oid[9];
sp_mlkem_oid(k->mlkem_level, oid);
unsigned char *c = buf + size;
int r, len = 0;
if ((r = mbedtls_asn1_write_bitstring(&c, buf, k->mlkem_pk, n * 8)) < 0) return r;
len += r;
int alg = 0;
if ((r = mbedtls_asn1_write_oid(&c, buf, (const char *)oid, sizeof oid)) < 0) return r;
alg += r;
if ((r = mbedtls_asn1_write_len(&c, buf, (size_t)alg)) < 0) return r;
alg += r;
if ((r = mbedtls_asn1_write_tag(&c, buf, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) < 0)
return r;
len += alg + r;
if ((r = mbedtls_asn1_write_len(&c, buf, (size_t)len)) < 0) return r;
len += r;
if ((r = mbedtls_asn1_write_tag(&c, buf, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) < 0)
return r;
return len + r;
}
static int sp_write_mlkem_pkcs8(SpKey *k, unsigned char *buf, size_t size) {
unsigned char oid[9];
sp_mlkem_oid(k->mlkem_level, oid);
unsigned char *c = buf + size;
int r, len = 0;
if ((r = mbedtls_asn1_write_raw_buffer(&c, buf, k->mlkem_seed, 64)) < 0) return r;
len += r;
if ((r = mbedtls_asn1_write_len(&c, buf, 64)) < 0) return r;
len += r;
if ((r = mbedtls_asn1_write_tag(&c, buf, MBEDTLS_ASN1_CONTEXT_SPECIFIC | 0)) < 0) return r;
len += r;
if ((r = mbedtls_asn1_write_len(&c, buf, (size_t)len)) < 0) return r;
len += r;
if ((r = mbedtls_asn1_write_tag(&c, buf, MBEDTLS_ASN1_OCTET_STRING)) < 0) return r;
len += r;
int oid_len = 0;
if ((r = mbedtls_asn1_write_oid(&c, buf, (const char *)oid, sizeof oid)) < 0) return r;
oid_len += r;
if ((r = mbedtls_asn1_write_len(&c, buf, (size_t)oid_len)) < 0) return r;
oid_len += r;
if ((r = mbedtls_asn1_write_tag(&c, buf, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) < 0)
return r;
len += oid_len + r;
if ((r = mbedtls_asn1_write_int(&c, buf, 0)) < 0) return r;
len += r;
if ((r = mbedtls_asn1_write_len(&c, buf, (size_t)len)) < 0) return r;
len += r;
if ((r = mbedtls_asn1_write_tag(&c, buf, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) < 0)
return r;
return len + r;
}
/* A digest AlgorithmIdentifier with NULL parameters, written backwards
* at *c; the written length or a negative error. */
static int sp_write_md_alg(unsigned char **c, unsigned char *start, mbedtls_md_type_t md) {
@@ -535,6 +625,7 @@ static int sp_write_pss_alg(unsigned char **c, unsigned char *start, const SpKey
static int sp_write_pkcs1_public_der(SpKey *k, unsigned char *buf, size_t size);
static int sp_write_spki_der(SpKey *k, unsigned char *buf, size_t size) {
if (sp_is_mlkem(k)) return sp_write_mlkem_spki(k, buf, size);
if (sp_is_okp(k)) {
if (k->x448) return sp_write_okp_der(sp_x448_spki_prefix, 12, k->x448_pub, 56, buf, size);
return sp_write_ed_der(sp_is_x(k) ? sp_x_spki_prefix : sp_ed_spki_prefix, 12, k->ed_pub, buf, size);
@@ -568,6 +659,7 @@ static int sp_write_pkcs1_public_der(SpKey *k, unsigned char *buf, size_t size)
* parameters, or id-ecPublicKey with the curve OID), and the inner key,
* which for EC omits the parameters field. */
static int sp_write_pkcs8_der(SpKey *k, unsigned char *buf, size_t size) {
if (sp_is_mlkem(k)) return sp_write_mlkem_pkcs8(k, buf, size);
if (sp_is_okp(k)) {
if (k->x448) return sp_write_okp_der(sp_x448_pkcs8_prefix, 16, k->x448_seed, 56, buf, size);
return sp_write_ed_der(sp_is_x(k) ? sp_x_pkcs8_prefix : sp_ed_pkcs8_prefix, 16, k->ed_seed, buf,
@@ -1379,6 +1471,15 @@ static ScrDyn *sp_b64url(const uint8_t *raw, size_t len) {
static ScrDyn *sp_export_jwk(SpKey *k) {
ScrDyn *jwk = scr_dyn_new_obj();
if (sp_is_mlkem(k)) {
sp_set(jwk, "kty", sp_dyn_str(scr_str_new("AKP", 3)));
sp_set(jwk, "alg", sp_dyn_str(scr_str_new(sp_mlkem_alg(k->mlkem_level),
strlen(sp_mlkem_alg(k->mlkem_level)))));
sp_set(jwk, "pub",
sp_b64url(k->mlkem_pk, sp_mlkem_pk_bytes(k->mlkem_level)));
if (k->private_key) sp_set(jwk, "priv", sp_b64url(k->mlkem_seed, 64));
return jwk;
}
if (sp_is_okp(k)) {
sp_set(jwk, "kty", sp_dyn_str(scr_str_new("OKP", 3)));
if (k->x448) {
@@ -1503,6 +1604,7 @@ static SpKey *sp_key_from_jwk_plain(const ScrDyn *jwk, bool want_private) {
scr_dyn_prop_type_fail("key.kty", "of type string", kty);
return NULL;
}
if (sp_is_str(kty, "AKP")) return sp_mlkem_from_jwk(jwk, want_private);
bool has_d = !sp_absent(sp_opt(jwk, "d"));
if (want_private && !has_d) {
sp_invalid_jwk();
@@ -1619,11 +1721,21 @@ static SpKey *sp_key_from_jwk_plain(const ScrDyn *jwk, bool want_private) {
/* The private key of a public SpKey derived from `k`. */
static SpKey *sp_public_of(SpKey *k) {
if (sp_is_mlkem(k)) {
SpKey *pub = sp_key_alloc(false);
pub->mlkem = true;
pub->mlkem_level = k->mlkem_level;
memcpy(pub->mlkem_pk, k->mlkem_pk, sp_mlkem_pk_bytes(k->mlkem_level));
return pub;
}
if (sp_is_okp(k)) {
SpKey *pub = sp_key_alloc(false);
pub->ed25519 = k->ed25519;
pub->x25519 = k->x25519;
pub->x448 = k->x448;
pub->mlkem = k->mlkem;
pub->mlkem_level = k->mlkem_level;
memcpy(pub->mlkem_pk, k->mlkem_pk, sizeof pub->mlkem_pk);
memcpy(pub->ed_pub, k->ed_pub, 32);
memcpy(pub->x448_pub, k->x448_pub, 56);
return pub;
@@ -1709,12 +1821,121 @@ static bool sp_cert_spki(const unsigned char *der, size_t len, const unsigned ch
return true;
}
/* ML-KEM's JWK algorithm name for a level. */
static const char *sp_mlkem_alg(int level) {
return level == 512 ? "ML-KEM-512" : level == 768 ? "ML-KEM-768" : "ML-KEM-1024";
}
/* Decodes a JWK base64url member into exactly `len` bytes. */
static bool sp_jwk_b64(const ScrDyn *jwk, const char *key, uint8_t *out, size_t len) {
const ScrDyn *v = sp_opt(jwk, key);
if (v->kind != SCR_DYN_STR) return false;
size_t encoded = (len * 4 + 2) / 3;
if (v->v.str->len != encoded) return false;
unsigned char *b64 = malloc(encoded + 4);
if (!b64) scr_trap("scriptc: out of memory\n");
for (size_t i = 0; i < encoded; i++) {
char c = v->v.str->data[i];
b64[i] = (unsigned char)(c == '-' ? '+' : c == '_' ? '/' : c);
}
size_t padded = encoded;
while (padded % 4) b64[padded++] = '=';
size_t n = 0;
bool ok = mbedtls_base64_decode(out, len, &n, b64, padded) == 0 && n == len;
mbedtls_platform_zeroize(b64, encoded + 4);
free(b64);
return ok;
}
/* An ML-KEM key from PKCS#8 or SubjectPublicKeyInfo DER. */
static SpKey *sp_mlkem_from_der(const unsigned char *der, size_t len, bool private_key) {
static const unsigned char pre_pkcs8[17] = {0x30, 0x54, 0x02, 0x01, 0x00, 0x30,
0x0b, 0x06, 0x09, 0x60, 0x86, 0x48,
0x01, 0x65, 0x03, 0x04, 0x04};
static const unsigned char pre_spki_tail[12] = {0x30, 0x0b, 0x06, 0x09, 0x60, 0x86,
0x48, 0x01, 0x65, 0x03, 0x04, 0x04};
/* A PKCS#8 private encoding answers a public key too (createPublicKey
* from a private key or its PEM/DER), through the public half derived
* from the seed. */
if (len == 86 && memcmp(der, pre_pkcs8, sizeof pre_pkcs8) == 0) {
if (der[18] != 0x04 || der[19] != 0x42 || der[20] != 0x80 || der[21] != 0x40) return NULL;
int level = der[17] == 1 ? 512 : der[17] == 2 ? 768 : der[17] == 3 ? 1024 : 0;
if (level == 0) return NULL;
SpKey *k = sp_key_alloc(private_key);
k->mlkem = true;
k->mlkem_level = level;
memcpy(k->mlkem_seed, der + 22, 64);
if (!scr_pki_mlkem_core ||
!scr_pki_mlkem_core->keypair_derand(level, k->mlkem_pk, k->mlkem_sk, k->mlkem_seed)) {
sp_key_release(k);
return NULL;
}
if (!private_key) mbedtls_platform_zeroize(k->mlkem_seed, 64);
return k;
}
if (private_key) return NULL;
if (len < 22 || der[0] != 0x30 || der[1] != 0x82 ||
memcmp(der + 4, pre_spki_tail, sizeof pre_spki_tail) != 0)
return NULL;
int level = der[16] == 1 ? 512 : der[16] == 2 ? 768 : der[16] == 3 ? 1024 : 0;
if (level == 0) return NULL;
size_t pk_len = sp_mlkem_pk_bytes(level);
if (len != pk_len + 22 || der[17] != 0x03 || der[18] != 0x82 || der[21] != 0x00) return NULL;
if ((size_t)((der[2] << 8) | der[3]) != len - 4 ||
(size_t)((der[19] << 8) | der[20]) != pk_len + 1)
return NULL;
SpKey *k = sp_key_alloc(false);
k->mlkem = true;
k->mlkem_level = level;
memcpy(k->mlkem_pk, der + 22, pk_len);
return k;
}
/* An ML-KEM key from an AKP JWK: alg names the level, pub is required and
* must match the public key derived from priv when both are present. */
static SpKey *sp_mlkem_from_jwk(const ScrDyn *jwk, bool private_key) {
const ScrDyn *alg = sp_opt(jwk, "alg");
int level = 0;
if (alg->kind == SCR_DYN_STR) {
if (sp_is_str(alg, "ML-KEM-512")) level = 512;
else if (sp_is_str(alg, "ML-KEM-768")) level = 768;
else if (sp_is_str(alg, "ML-KEM-1024")) level = 1024;
}
if (level == 0) {
scr_pki_throw_fmt(SCR_ERR_TYPE, "ERR_CRYPTO_INVALID_JWK", "Unsupported JWK AKP \"alg\"");
return NULL;
}
size_t pk_len = sp_mlkem_pk_bytes(level);
static const char invalid[] = "Invalid JWK AKP key";
SpKey *k = sp_key_alloc(private_key);
k->mlkem = true;
k->mlkem_level = level;
bool ok = sp_jwk_b64(jwk, "pub", k->mlkem_pk, pk_len);
if (ok && private_key) {
ok = sp_jwk_b64(jwk, "priv", k->mlkem_seed, 64);
if (ok) {
uint8_t derived_pk[1568];
ok = scr_pki_mlkem_core &&
scr_pki_mlkem_core->keypair_derand(level, derived_pk, k->mlkem_sk, k->mlkem_seed) &&
memcmp(derived_pk, k->mlkem_pk, pk_len) == 0;
}
}
if (!ok) {
sp_key_release(k);
sp_throw(SCR_ERR_TYPE, "ERR_CRYPTO_INVALID_JWK", invalid);
return NULL;
}
return k;
}
/* An Ed25519 key from PKCS#8 or SubjectPublicKeyInfo DER, or (for a public
* key) the key of an X.509 certificate; NULL when the DER is none of
* these, or with *failed set and an error pending. A private key wanted
* as public answers its public key. */
static SpKey *sp_ed_from_der(const unsigned char *der, size_t len, bool private_key, bool *failed) {
*failed = false;
SpKey *mlkem = sp_mlkem_from_der(der, len, private_key);
if (mlkem) return mlkem;
/* X25519 keys, which need no other unit. */
if (len == 48 && memcmp(der, sp_x_pkcs8_prefix, 16) == 0) {
SpKey *k = sp_key_alloc(private_key);
@@ -2367,10 +2588,21 @@ static void sp_incompatible_key_type(void) {
static void sp_invalid_key_data(void) { sp_throw(SCR_ERR_TYPE, "ERR_INVALID_ARG_VALUE", "Invalid key data"); }
/* A key's raw encoding: an EC public point, compressed when asked, or the
* private scalar at the curve's size, or an Ed25519 public key or seed.
* raw-seed, and every encoding of an RSA key, throw
* ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS. NULL with the error pending. */
* private scalar at the curve's size, an Ed25519 public key or seed, or an
* ML-KEM public key or 64-byte seed. raw-seed of other key types, and
* every encoding of an RSA key, throw ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS.
* NULL with the error pending. */
static ScrDyn *sp_export_raw(SpKey *k, bool private_part, bool seed, bool compressed) {
/* ML-KEM keys hold no mbedTLS key context: their raw forms are the
* encoded public key and the seed (raw-private has no encoding). */
if (sp_is_mlkem(k)) {
if (private_part && !seed) {
sp_incompatible_key_type();
return NULL;
}
if (seed) return sp_dyn_buffer(k->mlkem_seed, 64);
return sp_dyn_buffer(k->mlkem_pk, sp_mlkem_pk_bytes(k->mlkem_level));
}
if (seed || sp_is_rsa(k)) {
sp_incompatible_key_type();
return NULL;
@@ -2397,9 +2629,6 @@ static const char *const sp_other_named_types[] = {
"ml-dsa-44",
"ml-dsa-65",
"ml-dsa-87",
"ml-kem-512",
"ml-kem-768",
"ml-kem-1024",
"slh-dsa-sha2-128f",
"slh-dsa-sha2-128s",
"slh-dsa-sha2-192f",
@@ -2696,7 +2925,7 @@ static ScrDyn *sp_export_plain(SpKey *k, const ScrDyn *options) {
static ScrDyn *sp_key_details(SpKey *k) {
ScrDyn *details = scr_dyn_new_obj();
if (sp_is_okp(k)) return details;
if (sp_is_okp(k) || sp_is_mlkem(k)) return details;
if (sp_is_rsa(k)) {
mbedtls_rsa_context *rsa = mbedtls_pk_rsa(k->pk);
mbedtls_mpi e;
@@ -2728,7 +2957,8 @@ static ScrDyn *sp_key_details(SpKey *k) {
/* The DER that identifies a key for equals(): its private encoding for a
* private key, its SubjectPublicKeyInfo otherwise. */
static int sp_identity_der(SpKey *k, unsigned char *buf, size_t size) {
if (sp_is_okp(k)) return k->private_key ? sp_write_pkcs8_der(k, buf, size) : sp_write_spki_der(k, buf, size);
if (sp_is_okp(k) || sp_is_mlkem(k))
return k->private_key ? sp_write_pkcs8_der(k, buf, size) : sp_write_spki_der(k, buf, size);
return k->private_key ? sp_write_private_der(k, buf, size) : sp_write_spki_der(k, buf, size);
}
@@ -2776,7 +3006,9 @@ static ScrDyn *sp_key_get(void *h, const char *name, size_t len) {
if (len == 4 && memcmp(name, "type", 4) == 0)
return k->private_key ? sp_dyn_str(scr_str_new("private", 7)) : sp_dyn_str(scr_str_new("public", 6));
if (len == 17 && memcmp(name, "asymmetricKeyType", 17) == 0)
return sp_is_ed(k) ? sp_dyn_str(scr_str_new("ed25519", 7))
return sp_is_mlkem(k) ? sp_dyn_str(scr_str_new(sp_mlkem_name(k->mlkem_level),
strlen(sp_mlkem_name(k->mlkem_level))))
: sp_is_ed(k) ? sp_dyn_str(scr_str_new("ed25519", 7))
: sp_is_x448(k) ? sp_dyn_str(scr_str_new("x448", 4))
: sp_is_x(k) ? sp_dyn_str(scr_str_new("x25519", 6))
: k->rsa_pss ? sp_dyn_str(scr_str_new("rsa-pss", 7))
@@ -2993,7 +3225,15 @@ static bool sp_check_encoding_plain(const ScrDyn *enc, const char *name, const S
/* The key generateKeyPair makes, as sp_keygen_check reads it. */
typedef struct {
enum { SP_GEN_RSA, SP_GEN_EC, SP_GEN_ED25519, SP_GEN_X25519, SP_GEN_X448 } kind;
enum {
SP_GEN_RSA,
SP_GEN_EC,
SP_GEN_ED25519,
SP_GEN_X25519,
SP_GEN_X448,
SP_GEN_MLKEM
} kind;
int mlkem_level;
double bits, exponent; /* RSA */
bool pss; /* an RSA-PSS key, restricted when pss_params */
bool pss_params, md_set, mgf1_set, salt_set;
@@ -3171,6 +3411,11 @@ static bool sp_keygen_check(const ScrDyn *type, const ScrDyn *options, SpKeyGen
gen->kind = SP_GEN_X25519;
} else if (sp_is_str(type, "x448")) {
gen->kind = SP_GEN_X448;
} else if (sp_is_str(type, "ml-kem-512") || sp_is_str(type, "ml-kem-768") ||
sp_is_str(type, "ml-kem-1024")) {
gen->kind = SP_GEN_MLKEM;
gen->mlkem_level =
sp_is_str(type, "ml-kem-512") ? 512 : sp_is_str(type, "ml-kem-768") ? 768 : 1024;
} else {
bool named = false;
for (size_t i = 0; i < sizeof sp_other_named_types / sizeof sp_other_named_types[0]; i++)
@@ -3292,6 +3537,19 @@ static SpKey *sp_keygen_run(const SpKeyGen *gen, bool *job_error) {
}
return k;
}
if (gen->kind == SP_GEN_MLKEM) {
k->mlkem = true;
k->mlkem_level = gen->mlkem_level;
sp_random(NULL, k->mlkem_seed, 64);
if (!scr_pki_mlkem_core ||
!scr_pki_mlkem_core->keypair_derand(k->mlkem_level, k->mlkem_pk, k->mlkem_sk,
k->mlkem_seed)) {
sp_key_release(k);
sp_unsupported_input();
return NULL;
}
return k;
}
if (gen->kind == SP_GEN_X448) {
k->x448 = true;
sp_random(NULL, k->x448_seed, 56);
@@ -4119,7 +4377,7 @@ static bool sp_verify_hash(SpSigKey *key, mbedtls_md_type_t md, const unsigned c
/* X25519 keys neither sign nor verify: OpenSSL's error, after the key
* checks. Releases the key and answers true when it rejects. */
static bool sp_reject_x25519(SpSigKey *k) {
if (!sp_is_x(k->key) && !sp_is_x448(k->key)) return false;
if (!sp_is_x(k->key) && !sp_is_x448(k->key) && !sp_is_mlkem(k->key)) return false;
sp_key_release(k->key);
sp_throw_openssl("03000096", "digital envelope routines", "operation not supported for this keytype",
"ERR_OSSL_EVP_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE", true);
@@ -6061,7 +6319,8 @@ static const char sp_dh_public_types[] =
/* Node's message names: a KeyObject's asymmetricKeyType. */
static const char *sp_type_name(const SpKey *k) {
return sp_is_ed(k) ? "ed25519"
return sp_is_mlkem(k) ? sp_mlkem_name(k->mlkem_level)
: sp_is_ed(k) ? "ed25519"
: sp_is_x448(k) ? "x448"
: sp_is_x(k) ? "x25519"
: k->rsa_pss ? "rsa-pss"
@@ -6261,6 +6520,8 @@ ScrBytes *scr_pki_key_exponent(const ScrPkiKey *key) {
}
ScrPkiKey *scr_pki_key_parse_der(const uint8_t *der, size_t len, bool private_key) {
SpKey *mlkem = sp_mlkem_from_der(der, len, private_key);
if (mlkem) return mlkem;
if ((private_key && len == 48 &&
(memcmp(der, sp_ed_pkcs8_prefix, 16) == 0 || memcmp(der, sp_x_pkcs8_prefix, 16) == 0)) ||
(private_key && len == 72 && memcmp(der, sp_x448_pkcs8_prefix, 16) == 0) ||
@@ -6412,6 +6673,254 @@ ScrBytes *scr_pki_export_x448_raw(ScrPkiKey *key) {
return out;
}
/* ── crypto.encapsulate / crypto.decapsulate ──────────────────────────
* Node's KEM wrappers. Packet installments cover ML-KEM first; the other
* key types OpenSSL encapsulates (RSA, EC, X25519, X448) answer the generic
* failure until they are implemented. */
static void scr_crypto_kem_decoder_unsupported(void) {
static const char message[] = "error:1E08010C:DECODER routines::unsupported";
static const char code[] = "ERR_OSSL_UNSUPPORTED";
ScrStr *text = scr_str_new(message, sizeof message - 1);
ScrError *e = scr_error_new(SCR_ERR_ERROR, text);
scr_str_release(text);
scr_error_set_prop(e, "library", 7, sp_dyn_str(scr_str_new("DECODER routines", 16)));
scr_error_set_prop(e, "reason", 6, sp_dyn_str(scr_str_new("unsupported", 11)));
scr_error_set_code(e, code);
scr_error_set_prop(e, "code", 4, sp_dyn_str(scr_str_new(code, sizeof code - 1)));
scr_throw_obj(e, &scr_error_retain_v, &scr_error_release_v, scr_error_trace_arg());
}
/* The deferred callback's adapter: (null, value) with the value the caller's
* callback receives, released after the call. */
static void scr_crypto_kem_settle_dyn(ScrClosure *cb, ScrError *error, ScrBytes *value) {
(void)error;
ScrDyn *callback = (ScrDyn *)scr_box_get_ref(cb->caps[0]);
ScrDyn *result = (ScrDyn *)value;
ScrDyn *no_error = scr_dyn_new_null();
ScrDyn *argv[2] = {no_error, result};
ScrDyn *r = scr_dyn_call(callback, argv, result ? 2 : 1, "callback");
if (r) scr_dyn_release(r);
scr_dyn_release(no_error);
if (result) scr_dyn_release(result);
scr_dyn_release(callback);
}
static void scr_crypto_kem_settle_bytes(ScrClosure *cb, ScrError *error, ScrBytes *value) {
(void)error;
ScrDyn *callback = (ScrDyn *)scr_box_get_ref(cb->caps[0]);
ScrDyn *out = scr_dyn_new_buffer(value);
scr_bytes_release(value);
ScrDyn *no_error = scr_dyn_new_null();
ScrDyn *argv[2] = {no_error, out};
ScrDyn *r = scr_dyn_call(callback, argv, 2, "callback");
if (r) scr_dyn_release(r);
scr_dyn_release(no_error);
scr_dyn_release(out);
scr_dyn_release(callback);
}
/* The deferred queue's failure adapter: the callback receives the error
* alone, as Node's crypto job completions call it. The queue owns the error
* and releases it after this returns. */
static void scr_crypto_kem_settle_error(ScrClosure *cb, ScrError *error, ScrBytes *value) {
(void)value;
ScrDyn *callback = (ScrDyn *)scr_box_get_ref(cb->caps[0]);
ScrDyn *thrown = scr_dyn_from_error(error);
ScrDyn *argv[1] = {thrown};
ScrDyn *r = scr_dyn_call(callback, argv, 1, "callback");
if (r) scr_dyn_release(r);
scr_dyn_release(thrown);
scr_dyn_release(callback);
}
/* A KEM operation the key cannot perform, in a callback form: Node queues
* the failure and answers undefined, and the callback receives the error
* alone (synchronous calls throw instead). */
static void scr_crypto_kem_fail_async(ScrDyn *callback) {
ScrStr *message = scr_str_new("Deriving bits failed", 20);
ScrError *error = scr_error_new(SCR_ERR_ERROR, message);
scr_str_release(message);
ScrClosure *settle = scr_closure_new(scr_crypto_kem_settle_error, 1);
settle->caps[0] = scr_box_new_obj(scr_dyn_retain_v, scr_dyn_release_v, NULL);
scr_box_set_ref(settle->caps[0], scr_dyn_retain(callback));
scr_crypto_defer_bytes(NULL, error, settle, scr_crypto_kem_settle_error);
}
/* validateFunction for the optional callback: a function when present. */
static bool scr_crypto_kem_callback_ok(const ScrDyn *callback) {
if (callback->kind == SCR_DYN_UNDEF) return true;
if (scr_dyn_is_callable(callback)) return true;
scr_dyn_arg_type_fail("callback", "of type function", callback);
return false;
}
/* crypto.encapsulate(key[, callback]): { sharedKey, ciphertext }, or the
* callback in a later macrotask. */
ScrDyn *scr_crypto_encapsulate_dyn(ScrDyn *key, ScrDyn *callback) {
if (!scr_crypto_kem_callback_ok(callback)) return NULL;
bool async = callback->kind != SCR_DYN_UNDEF;
ScrPkiKey *material = scr_crypto_key_object_material(key);
if (!material) {
scr_crypto_kem_decoder_unsupported();
return NULL;
}
if (!scr_pki_key_is_mlkem(material)) {
scr_pki_key_release(material);
if (async) {
scr_crypto_kem_fail_async(callback);
return scr_dyn_undefined();
}
scr_pki_mlkem_key_unsupported();
return NULL;
}
ScrDyn *result = scr_pki_mlkem_encapsulate(material);
scr_pki_key_release(material);
if (!result) {
if (async) {
scr_crypto_kem_fail_async(callback);
return scr_dyn_undefined();
}
scr_pki_mlkem_encapsulate_failed();
return NULL;
}
if (!async) return result;
ScrClosure *settle = scr_closure_new(scr_crypto_kem_settle_dyn, 1);
settle->caps[0] = scr_box_new_obj(scr_dyn_retain_v, scr_dyn_release_v, NULL);
scr_box_set_ref(settle->caps[0], scr_dyn_retain(callback));
scr_crypto_defer_dyn(result, NULL, settle, scr_crypto_kem_settle_dyn);
/* The callback form answers undefined, so an expression that reads the
* call's result sees what Node returns. */
return scr_dyn_undefined();
}
/* crypto.decapsulate(key, ciphertext[, callback]). */
ScrDyn *scr_crypto_decapsulate_dyn(ScrDyn *key, ScrDyn *ciphertext, ScrDyn *callback) {
if (!scr_crypto_kem_callback_ok(callback)) return NULL;
bool async = callback->kind != SCR_DYN_UNDEF;
ScrPkiKey *material = scr_crypto_key_object_material(key);
if (!material) {
scr_crypto_kem_decoder_unsupported();
return NULL;
}
/* The key-shape checks answer synchronously even in a callback form;
* a ciphertext (or key type) the operation cannot use is queued. */
if (!scr_pki_key_is_private(material)) {
scr_pki_mlkem_expected_private();
scr_pki_key_release(material);
return NULL;
}
/* Node's getArrayBufferOrView: a string is its UTF-8 bytes, a
* BufferSource its bytes, and anything else an argument error (before
* the operation runs, callback form included). */
ScrBytes *bytes = sp_source_bytes(ciphertext, NULL);
if (!bytes) {
scr_pki_key_release(material);
scr_dyn_arg_type_fail(
"ciphertext",
"of type string or an instance of ArrayBuffer, Buffer, TypedArray, or DataView", ciphertext);
return NULL;
}
if (!scr_pki_key_is_mlkem(material)) {
scr_pki_key_release(material);
scr_bytes_release(bytes);
if (async) {
scr_crypto_kem_fail_async(callback);
return scr_dyn_undefined();
}
scr_pki_mlkem_decapsulate_failed();
return NULL;
}
ScrBytes *shared = scr_pki_mlkem_decapsulate(material, bytes->data,
(size_t)scr_bytes_byte_len(bytes));
scr_pki_key_release(material);
scr_bytes_release(bytes);
if (!shared) {
if (async) {
scr_crypto_kem_fail_async(callback);
return scr_dyn_undefined();
}
scr_pki_mlkem_decapsulate_failed();
return NULL;
}
if (!async) {
ScrDyn *out = scr_dyn_new_buffer(shared);
scr_bytes_release(shared);
return out;
}
ScrClosure *settle = scr_closure_new(scr_crypto_kem_settle_bytes, 1);
settle->caps[0] = scr_box_new_obj(scr_dyn_retain_v, scr_dyn_release_v, NULL);
scr_box_set_ref(settle->caps[0], scr_dyn_retain(callback));
scr_crypto_defer_bytes(shared, NULL, settle, scr_crypto_kem_settle_bytes);
return scr_dyn_undefined();
}
bool scr_pki_key_is_mlkem(const ScrPkiKey *key) { return sp_is_mlkem(key); }
/* Node's errors for crypto.encapsulate/decapsulate. */
void scr_pki_mlkem_encapsulate_failed(void) {
scr_pki_throw_fmt(SCR_ERR_ERROR, "ERR_CRYPTO_OPERATION_FAILED", "Failed to perform encapsulation");
}
void scr_pki_mlkem_decapsulate_failed(void) {
scr_pki_throw_fmt(SCR_ERR_ERROR, "ERR_CRYPTO_OPERATION_FAILED", "Failed to perform decapsulation");
}
void scr_pki_mlkem_expected_private(void) {
scr_pki_throw_fmt(SCR_ERR_TYPE, "ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE",
"Invalid key object type public, expected private.");
}
/* A key type the KEM API refuses entirely (Ed25519, RSA-PSS, DSA, DH):
* OpenSSL answers the generic encapsulation/decapsulation failure. */
void scr_pki_mlkem_key_unsupported(void) {
scr_pki_throw_fmt(SCR_ERR_ERROR, "ERR_CRYPTO_OPERATION_FAILED", "Failed to perform encapsulation");
}
ScrDyn *scr_pki_mlkem_encapsulate(const ScrPkiKey *key) {
size_t ct_len = sp_mlkem_ct_bytes(key->mlkem_level);
unsigned char seed[32], shared[32];
sp_random(NULL, seed, sizeof seed);
uint8_t *ct = malloc(ct_len);
if (!ct) scr_trap("scriptc: out of memory\n");
bool ok = scr_pki_mlkem_core &&
scr_pki_mlkem_core->encapsulate(key->mlkem_level, ct, shared, key->mlkem_pk, seed);
mbedtls_platform_zeroize(seed, sizeof seed);
if (!ok) {
free(ct);
return NULL;
}
ScrDyn *result = scr_dyn_new_obj();
ScrBytes *shared_bytes = scr_bytes_new(SCR_BYTES_U8, 32);
memcpy(shared_bytes->data, shared, 32);
shared_bytes->is_buffer = true;
ScrDyn *shared_dyn = scr_dyn_new_buffer(shared_bytes);
scr_bytes_release(shared_bytes);
ScrBytes *ct_bytes = scr_bytes_new(SCR_BYTES_U8, (double)ct_len);
memcpy(ct_bytes->data, ct, ct_len);
ct_bytes->is_buffer = true;
free(ct);
ScrDyn *ct_dyn = scr_dyn_new_buffer(ct_bytes);
scr_bytes_release(ct_bytes);
scr_dyn_obj_set(result, "sharedKey", 9, shared_dyn);
scr_dyn_obj_set(result, "ciphertext", 10, ct_dyn);
mbedtls_platform_zeroize(shared, sizeof shared);
return result;
}
ScrBytes *scr_pki_mlkem_decapsulate(const ScrPkiKey *key, const unsigned char *ciphertext,
size_t len) {
if (len != sp_mlkem_ct_bytes(key->mlkem_level)) return NULL;
unsigned char shared[32];
if (!scr_pki_mlkem_core ||
!scr_pki_mlkem_core->decapsulate(key->mlkem_level, shared, ciphertext, key->mlkem_sk))
return NULL;
ScrBytes *out = scr_bytes_new(SCR_BYTES_U8, 32);
memcpy(out->data, shared, 32);
mbedtls_platform_zeroize(shared, sizeof shared);
return out;
}
ScrBytes *scr_pki_shared_secret(ScrPkiKey *private_key, ScrPkiKey *public_key) {
ScrDyn *dyn = sp_dh_compute(private_key, public_key, false);
if (!dyn) {
+25
View File
@@ -77,6 +77,31 @@ ScrPkiKey *scr_pki_generate_x448(void);
bool scr_pki_key_is_x448(const ScrPkiKey *key);
ScrPkiKey *scr_pki_key_from_x448_raw(const uint8_t *raw, size_t len);
ScrBytes *scr_pki_export_x448_raw(ScrPkiKey *key);
/* The per-level ML-KEM core, installed by the optional scr_mlkem unit (the
* vendored mlkem-native archive). pki holds ML-KEM key material and DER/JWK
* forms without referencing that unit, so a program that never names an
* ML-KEM algorithm does not link it. */
typedef struct ScrPkiMlkemCore {
bool (*keypair_derand)(int level, uint8_t *pk, uint8_t *sk, const uint8_t seed[64]);
bool (*encapsulate)(int level, uint8_t *ct, uint8_t shared[32], const uint8_t *pk,
const uint8_t seed[32]);
bool (*decapsulate)(int level, uint8_t *shared, const uint8_t *ct, const uint8_t *sk);
} ScrPkiMlkemCore;
extern const ScrPkiMlkemCore *scr_pki_mlkem_core;
/* ML-KEM (FIPS 203): node:crypto's crypto.encapsulate/decapsulate over the
* vendored core. The encapsulation answers a fresh object
* { sharedKey, ciphertext } (both Buffers) or NULL with the error pending;
* the decapsulation answers the 32-byte shared key, or NULL. */
bool scr_pki_key_is_mlkem(const ScrPkiKey *key);
ScrDyn *scr_pki_mlkem_encapsulate(const ScrPkiKey *key);
ScrBytes *scr_pki_mlkem_decapsulate(const ScrPkiKey *key, const unsigned char *ciphertext,
size_t len);
/* Node's key-shape errors for the KEM entry points. */
void scr_pki_mlkem_encapsulate_failed(void);
void scr_pki_mlkem_decapsulate_failed(void);
void scr_pki_mlkem_expected_private(void);
void scr_pki_mlkem_key_unsupported(void);
/* The shared secret of an ECDH or X25519 key pair: X25519's 32 bytes or
* ECDH's x coordinate at the field's width. NULL on failure (a public key
* of another curve or type), with no error pending. */
@@ -0,0 +1,52 @@
// crypto.encapsulate/decapsulate failures in their callback forms: the call
// answers undefined and the callback receives the operation error alone in a
// later macrotask, while the key-shape checks still throw synchronously.
// @normalize-pid
import { decapsulate, encapsulate, generateKeyPairSync } from "node:crypto";
const kp = generateKeyPairSync("ml-kem-768");
const ed = generateKeyPairSync("ed25519");
const initial = encapsulate(kp.publicKey);
const ct = initial.ciphertext;
// The result parameter is read as a value of any type: the failure call
// passes the error alone, so it is undefined there (Node's own omission).
type Failure = Error & { code?: string };
const report = (label: string, error: Error | null, value: unknown): void => {
const typed = error as Failure | null;
console.log(label, typed === null ? "null" : `${typed.name} ${typed.code ?? "no-code"} | ${typed.message}`,
value === undefined ? "no value" : typeof value);
};
const refused = encapsulate(ed.publicKey, (error: Error | null, value?: unknown) => {
report("refused key", error, value);
const short = decapsulate(kp.privateKey, Buffer.alloc(4), (nextError: Error | null, next?: unknown) => {
report("short ciphertext", nextError, next);
const text = decapsulate(kp.privateKey, "abc" as never, (textError: Error | null, textValue?: unknown) => {
report("string ciphertext", textError, textValue);
decapsulate(kp.privateKey, ct, (lastError: Error | null, lastValue?: unknown) => {
report("valid ciphertext", lastError, lastValue);
// A string ciphertext is its UTF-8 bytes: 1088 ASCII characters are
// a well-formed ML-KEM-768 ciphertext, so the callback gets a key.
decapsulate(kp.privateKey, "x".repeat(1088) as never, (stringError: Error | null, stringValue?: unknown) => {
report("string valid ciphertext", stringError, stringValue);
});
});
});
console.log("string call returned", text === undefined);
});
console.log("short call returned", short === undefined);
});
console.log("refused call returned", refused === undefined);
// An unusable ciphertext type is an argument error before the operation
// runs, callback form included.
try {
decapsulate(kp.privateKey, 5 as never);
} catch (error) {
const typed = error as Failure;
console.log("number ciphertext threw", typed.name, typed.code);
}
setTimeout(() => console.log("end"), 50);
+39
View File
@@ -0,0 +1,39 @@
// crypto.encapsulate/decapsulate callback forms: validation happens up front,
// the callback runs from the deferred crypto queue with (null, result), and
// both the sync result and the refused key types answer Node's errors.
import { decapsulate, encapsulate, generateKeyPairSync } from "node:crypto";
const kp = generateKeyPairSync("ml-kem-768");
const sync = encapsulate(kp.publicKey);
const attempt = (label: string, run: () => unknown): void => {
try {
run();
console.log(label, "ok");
} catch (error) {
const typed = error as Error & { code?: string };
console.log(label, typed.name, typed.code, "|", typed.message);
}
};
attempt("bad callback", () => encapsulate(kp.publicKey, 5 as never));
attempt("bad callback first", () => encapsulate("x" as never, 5 as never));
attempt("bad decapsulate callback", () => decapsulate(kp.privateKey, sync.ciphertext, 5 as never));
attempt("public decapsulate", () => decapsulate(kp.publicKey, sync.ciphertext));
attempt("short ciphertext", () => decapsulate(kp.privateKey, Buffer.alloc(4)));
const ed = generateKeyPairSync("ed25519");
attempt("ed25519 encapsulate", () => encapsulate(ed.publicKey));
let returned = false;
let shared = false;
encapsulate(kp.publicKey, (error, result) => {
console.log("encapsulate callback", returned, error, result?.ciphertext.length);
shared = decapsulate(kp.privateKey, result!.ciphertext).equals(result!.sharedKey);
});
returned = true;
let decapsulated = false;
decapsulate(kp.privateKey, sync.ciphertext, (error, value) => {
console.log("decapsulate callback", error, value?.length, value?.equals(sync.sharedKey));
decapsulated = true;
});
process.nextTick(() => console.log("tick"));
setTimeout(() => console.log("end", shared, decapsulated), 20);
console.log("returned");
+5
View File
@@ -0,0 +1,5 @@
// A module that only names an ML-KEM parameter set, with no asymmetric
// crypto call: the string literal selects the mlkem unit, which links the
// pki unit it installs its hook into.
const name = "ml-kem-768";
console.log(name.length, name.toUpperCase(), name.startsWith("ml-"));
@@ -0,0 +1,26 @@
// node:crypto ML-KEM reached only through run-time inputs: the algorithm is
// computed and the PKCS#8 encoding read at run time, so no parameter-set
// literal and no encapsulate/decapsulate call selects the units; the pki
// unit carries the ML-KEM hook with it.
import { createPrivateKey, createPublicKey, generateKeyPairSync } from "node:crypto";
const log = (...a: unknown[]) => console.log(a.map(String).join(" | "));
const algorithm = ["ml", "kem", "768"].join("-") as "ml-kem-768";
const kp = generateKeyPairSync(algorithm);
log("gen", kp.privateKey.asymmetricKeyType, kp.publicKey.asymmetricKeyType,
kp.privateKey.export({ type: "pkcs8", format: "der" }).length,
kp.publicKey.export({ type: "spki", format: "der" }).length);
const seed = Buffer.from("386e9c7d79136fd98439aa796bf3c36e9082416ba3363b6299ef40c5ae7c9415ad79ac7b1cacb8dcf63976aaf2a2b0e738b59afa8a29f8ca600f294e991d9d45", "hex");
const pkcs8 = Buffer.concat([Buffer.from("3054020100300b060960864801650304040204428040", "hex"), seed]);
const priv = createPrivateKey({ key: pkcs8, format: "der", type: "pkcs8" });
const pub = createPublicKey(priv);
log("import", priv.asymmetricKeyType, pub.asymmetricKeyType,
priv.export({ type: "pkcs8", format: "der" }).equals(pkcs8),
Buffer.from(pub.export({ type: "spki", format: "der" })).length);
const pubDer = pub.export({ type: "spki", format: "der" });
const again = createPublicKey({ key: pubDer, format: "der", type: "spki" });
log("public", again.asymmetricKeyType,
Buffer.from(again.export({ type: "spki", format: "der" })).equals(pubDer));
+100
View File
@@ -0,0 +1,100 @@
// node:crypto ML-KEM (FIPS 203): fixed Node-generated seeds and ciphertexts through
// @normalize-pid
// createPrivateKey/createPublicKey, DER and JWK round trips, crypto.encapsulate/
// decapsulate (sync and refusal cases), and generateKeyPairSync shapes per level.
import { createPrivateKey, createPublicKey, decapsulate, encapsulate, generateKeyPairSync } from "node:crypto";
const log = (...a: unknown[]) => console.log(a.map(String).join(" | "));
const seed512 = Buffer.from("e954ad9adfcfd48b9b1d3f854195ba7ba8cb81f3ed79d23a1c512d2164f08d4681620eef9268e7525b2ff97fde197bda8158955b1059d9a9a3ba8890b2e42a50", "hex");
const pub512 = Buffer.from("92c3cb1783a32a116ec69465ba397d2c8390898c6ea3f74ca991272977465cb84c2e431f4a92555883a31893277b228f080094536203fc8b9ae80049b9c6b3887a4c155b9847eb069af173ad923b314c144e13b06d000f87bc8c786a0d0cb954ee786e7ef0a6ce06a7f7594222e66950485cbab889fb0c17b3acc980954e430021769a44eb884b2515b66ca32f093120b1baa89aab3984202b07203654dcb2e688575efb2c785304dd98821859808d5c4216aa7d55bcc481fa282153a5aa10889430865dc598c520c05d953e207375d7f123b5c2a054b352d69165466b5360899a9eb7adace17d535745df239e352075fa776e5ca342cd96a8aa9b688a58bce9118ef13aa876461a1666408bc5203ee43e3a53c5ced60da13c917ab379d1d4bdbc959311f7c5d7d4ae51849c060200c0c4a82024b92822a37cdba6c34690e4c57446a21ddd543841a7bd46881aa0954012156b3675a3dd8355dc10ccb27b72923011439cc8b5f8c27178bfc7f59e99d85649ccbc5f71aa7f9477689a81ec6c16ea8cb1c9e717c01420595292155c7679430b5bc8c5b63c7dfd514260a189dc24a1d90694a3a93844675fd25cb121ea39b9bc124038655242accc28903cd9362caca3408c6d789bae12ba849a2a8829e195de9722ce86a0162c2762e469705757c8b66f3cecc3233c266c42655454586a3543d822a1f4205d1ed40d1c995f5ae6ba74e21e55192745aa149d4a990932baa28a05bac1c5322636ac8810eed3856a60a953f33d3fa430c100c7ace966ac5b77ac310a05d9298c7a7a425544d8b869d6283e4d4bb23a867863b52c0382b0e6c31f9e8518f678adfc76c301c369b6976c2915bab4c49808ab0cddb49124f23df8119fbc572f97ab02cc23ba1f102b5a65a310249fbc39b709350eaed31426321d577193d5f07a0e17a95992caa0a90c41e7b4c203bededb0217428620a48b0824180428c1e81960e1f984a375065224666c94589bc7b36082443caca8d586a32bb60041ec5b2e86b8298277132936ccb62c6a0c13aeca82aa6c5bfbb4b7f57545893565074c27e28c8711c69e3318a075702ba44c1c9ed5fa1bbefa8d72d1bdffadacd7562d29523a017010be6b5c64", "hex");
const ct512 = Buffer.from("2270084b36f7ea4dfba4d30a4d6772e86db863050fefcefc514da5c39b708693c8a26dc3014db061ee375e9ff05bed0c5e0feb12e3560fce71127701d43ec66fd4ecd0f89738bc8bb2724df0ed5ac5ef6d8e7d705cbc0179a160e39e178a195fe8f05a3aeeff541b10bb79c25cc2ebb711bdb03bca81288a42abbbeba2a7fb2b4093ba8b64bbae4e98357518b3cfe422352b95d7f21678a111c5aefac3c2531e00b7077fc31465bdde692e8dc4186c75f50f6273a83ca26b373f080fb0f9acb9a035dd1d4395e6c1b1fe1e5306ae3438a037e5b3735e4f7d07a46db522b98265a5dd7883da8105347a26f06a293c941e053af0cd1fa851e7a9d7144bf95ff9b8f4e1602a6dbd193dd54a15367dedcd5501dfe0293a805bb50080ac44c3e3cf3a5e2012fe528993f6140c9218f663ab5677148ec43931d5f59a8361111e01e3f7ccd544bbfcfab3ccb25c6c0f3b421b0f4bf27913ee8e319df088d82adde7a65b6b423431934eb50ef2552485088735c998bd5d6617d5df5f5a1e7d27f5148d1783d58c916d43b8a4b50702ae19ba5d6de341346eb75e9eaafc86640e272f2c97447d511f2d93f33955505160d9f2269dc1bfbd8801669a8612cf084922cfd404bd194b7934e2036834a45182b960081fb09ef9ab97285a45f7f3dcbbffa40379fab6bc498c3ced80cd5af134d3cb7cd3d094fb884ae8ae404c361604422a360f3111777cc29a6b7cb034867c02991d63633228ff86e35fe6f7df61b204c18774df01d80e69c5cc8f824151ec1c49795b7516d28c53c5d508628c42b08ce6f5b41aa73dda2536d4a76e666c32e10e49816dbe75372ad02fd36bc5affca9ae3b06279abd94b3b514444945c1afc015f63908e35f422fe57b48951946eb5a67c96d1c288293053c1ca2f5bf31b3866beff6beee2d0fc076dbbc9885061ef161c25dcb9e05cbe4c673ed3fdffd8f243fc5f67d84d671f58bf3e10552642e157f3a375772e857f661151e9cc7584e007efea1b43523f739a50822c7440161b51b4f7c38381b5bf10c0b2b7ce5da37ac212eb3125e3954c2ddb4cd5ba0a02286da4f0d", "hex");
const ss512 = Buffer.from("9d50bd605d0fa1089ff74424cbe7fbc2181d5d13256f211e7029e98b59ea1e19", "hex");
const pkcs8_512 = Buffer.concat([Buffer.from("3054020100300b060960864801650304040104428040", "hex"), seed512]);
const spki_512 = Buffer.concat([Buffer.from("30820332300b06096086480165030404010382032100", "hex"), pub512]);
const priv512 = createPrivateKey({ key: pkcs8_512, format: "der", type: "pkcs8" });
const pubk512 = createPublicKey({ key: spki_512, format: "der", type: "spki" });
log("level", 512, priv512.asymmetricKeyType, pubk512.asymmetricKeyType, JSON.stringify(priv512.asymmetricKeyDetails));
log("der", priv512.export({ type: "pkcs8", format: "der" }).equals(pkcs8_512), pubk512.export({ type: "spki", format: "der" }).equals(spki_512));
const jwk512 = priv512.export({ format: "jwk" }) as { kty?: string; alg?: string; pub?: string; priv?: string };
log("jwk", jwk512.kty, jwk512.alg, jwk512.pub!.length, jwk512.priv!.length);
log("jwk rt", createPrivateKey({ key: jwk512, format: "jwk" }).export({ type: "pkcs8", format: "der" }).equals(pkcs8_512));
log("decaps", 512, decapsulate(priv512, ct512).equals(ss512));
const enc512 = encapsulate(pubk512);
log("roundtrip", 512, enc512.sharedKey.length, enc512.ciphertext.length, decapsulate(priv512, enc512.ciphertext).equals(enc512.sharedKey));
const seed768 = Buffer.from("386e9c7d79136fd98439aa796bf3c36e9082416ba3363b6299ef40c5ae7c9415ad79ac7b1cacb8dcf63976aaf2a2b0e738b59afa8a29f8ca600f294e991d9d45", "hex");
const pub768 = Buffer.from("b37a8383bb07b0aa145ebb375cc0258472c5823a90d9998dd5e35d32741a37717e5568c69cec753a6545c82b64d3d63dace09884da2a13e25f5d1646edb68e276a74cab30cd7213a0d451f3094813b029f7f08a2fa41ae967883d6a28477367857a4343dd25e37e4b5ea767fdad1034220725ccc2b1cf76151922b55a801798cb2fdb14731c68a5e1aaa9bc81fa8626e0f0ac4ca0bbe57836610a37aaf7ab1c189176f590e28d63aa06c793e4c5f59880b5a41acbe84a6cd50287cd175740c34e076c6ea648eebe2645ac37e4248b882c9958cfacce904499135cd506b9d9ab4399a002bf3db085d7352392170db3290076a1c7e621fffb1873f7723f9212b4bc6981cb31a20491316198279334f1b2c66e14768ea1633c1e986dcebb706778bbb39188014418932845298493efb487342743ee12c62218c4e98ca3fa2c60e0449c58a2a5f3bccc01a000b35ce3ac5afd2f8a96f84337a2297a31166e6239c89c214df997b18c8074fa6a2e073b7ad23691d97b80dd07a3d4caacc254915c383a73c996df0cb6550619645bb9aa9aac5d97b83442d35113519d21eee304f31096bae813ff70610d4f86d42ca2c9cd7919bba48071b097dbc63d808016ab00242ab93507046d1a222dc2c2c1f7b8ebba14f865a2672d39048f757bc7013cc6b6be9dc31b23c03ea4356771996a9807b7e8aa6d3b8aa9af9340a3b25bc858fb2b4a0cad462e8561615722acab1ad9a74521cdb3373b96d860ac811c4bbb937c7db33605784a14b5b4bb8d021b7f49d1fd6ab6de655fc999e8cf07a73516f30e572bd5c83a8984eaf4487e2668766538590148b7a078722b2226afc5d8533947a776f2f649192c77e7ab5c86f9a025e1c35c3173d91b81dd60b01f5b80e93391739d9267dd138abe460e60958eba6840e625ed10a540c6c2a2d667ea609413392cc1d2b59b63c7b42d3551db4c838e01fb583137438a845f9aea9471d6459480e0285d4ac016bb38717301e8b2aae98f24e655c31bf71b231c63e4db125867a235ad6607b69a294f5651c82cfd8ab0609cc0ad3a15436e94ced848077f1afa9d01e4e0392c5d92f3c9205ed8020a024bf8bec6a9b0966acd4b95a5c7f0ce2242961385a32cafa002593e10fd24a073abbcc92d5950c56096fa3c1e247955c97c4559acb86e4976221628f627dbf274ea4507b664b5431a17fbb3b1a18096026b703fc47c5663a31f5dc3fe62107acf43af950590a9a5c8cf704edbb9cde2a394ff37d6364498e30ac1b6c13b275531f34a0ecf17dbc565067f9a99221a51589aac221c6cc4865f6438bf313779fb2564a688e035c1f37d110015987c9880b1d0a4eb3fa20a0826a2d0a0f9a28280e728e8c964a247b3c074018171774da5c448de2a5eceb95adfb56ac741437ecacefc8acc9280e97265ccaa12cdeb32a1e2c5c08e14614893968cc36a2c45eb4286b8be035ecf56ab4738ebca9118b518ed756c841863e3fb97a4de5c8dfc986bdb9a4f900008cb45bf527b8a62695e4fba5444c0e34b0822753659dd6b690190ee58ac26e2180666b70bc350502a22100796aafd2002e27a9e97a5f17788c5d8679aa48a382acc68a871eb74b097d8765f27426913e0e3b3a39d2f70c049c1787a33dffbe0b074a53d80aaf5c47685b1423c478", "hex");
const ct768 = Buffer.from("29e6be0f78b7efd8710d436f8a776f319856c9506f3a3c6d2af84f95d9d15480aeae536ec0cf3a26c30b9f4149945aef64afbbc0f85473810d6b5a3f58cdcd9bf260a8732aaf132ac0a632cb2d1d59f45191165b11891bc397f20237ad43f2e9d190df9db68a71307be219404b42b7d75c0b3b545cee91c31bd248eb1cc47328c609b5ce955878d6666e8336aa1435fed6ba8653230ecb447fab59f3379364816fcdee79816e50348de6f7ae18405d5b2b024fa6b058bbba697c3c33a758de1f2bf6ace8b3b6604e4ceee3c5b30d758f81f69210390c0142fc27507b203ade0d91bbd46cdc62d0302860376b6abc60c9b6235da08d3cfb27edae000e6dbe0cbd54760a9bab3abac9d53650255897ca211ad258fc9560f2b20a5d897c5120d52ad21d2969cf1a0c9529b70f84df74e58923bd85a350e9f5ba5c5b35095f55f4b9480076c3427acbf5d25d0e18bb288ec14fe7c4b739f5d6f288ba7289572040271634b48aeaba5bc2e85937bafc1c1ad50e2f8073b35c59befedb9b64ec788283adccf6c02848b364d2ac0258ad1b64de95ead3f71e759ab49f2570fd6ccdb705e9da52cdad502a743725737a66e6531a97e676064c45e95726b9e10062b049071bce2ae7268242c93767cb498e87201b664821b4e693c09b029ec9ebb186ca03e2da8fd3af0461d99b08bd8a0bc7bff36d7dc8cf473bf792cb298f84e596f9faed68e6e5a0161ca3f025f5c31a624bac0015b19a45257d16ed7d0d4efc742b15d9c3baf16aa821beadc4d56aa4233ed6c3bdcba9feff730d6ba40ce1830bbe453a90fc84a9c335d29c171aa58f5f5a24737dc30988f472247c41bdef69bb014adc030e39f56a0f04b330f5dfbe03198e4f3474c8c37b9f1de5ae4b6fea85c3f70a984d18708d6a8aca17a9a7479a56698aa1066fec07701cbd14f487b2b3c930a516ebc059d79f7cdc48d0aebd22d0651c6f846bb78926b542f7fe25573e0e7b8eede9fa412a5dafae84bdcfcf7b4a5bbf78bc680abd5034db666bbf195fa3bf6a50acc80f9926106852c8d31a2968dab5a97d5d4f8833147bf300253d39f1abd2e7aad529eef7820fb473d69403ad8d05866e4a1370bb3197047ed37a22996fbf72d153b09b8e558b8089d0dda8362a9d85f2b9c32a024df649b3a9b1cacc88f22a70a80a80dca44fe7a7ba4f4b30f488591df80e3e2ed48d05ea45a77918d3d9292b6e1e2a1daac6aca193352407009d9839049e3b7d9ed09fd23238c38db66572d51aca03650f1195ccb3301ba60aa676047a4b84bfacff6a886e312657ea024db271df02aad2633f015b7fad05515976ddef7a08162c7d779cc12f96d71fa16904356711fd56c0d0fa266c4567d12b28f17d7fd60244104a8c46a5eae8707fa421635993e4bcc8c9a18a409fe94d639219e8cc6916d9da88d523635b7efee5942b64fc6dbc5db1c93dd53f910233b0c5a4201772747fe4235ca3afaa56cb494d45550416792af25a1546469f012f69fcb2e04bc1a7e7c6264b49b8a7d96a", "hex");
const ss768 = Buffer.from("8eec11b80ad94e99623b6a5f8735acc8d1c82e306b38f65c0eca1b9ca57f4d7c", "hex");
const pkcs8_768 = Buffer.concat([Buffer.from("3054020100300b060960864801650304040204428040", "hex"), seed768]);
const spki_768 = Buffer.concat([Buffer.from("308204b2300b0609608648016503040402038204a100", "hex"), pub768]);
const priv768 = createPrivateKey({ key: pkcs8_768, format: "der", type: "pkcs8" });
const pubk768 = createPublicKey({ key: spki_768, format: "der", type: "spki" });
log("level", 768, priv768.asymmetricKeyType, pubk768.asymmetricKeyType, JSON.stringify(priv768.asymmetricKeyDetails));
log("der", priv768.export({ type: "pkcs8", format: "der" }).equals(pkcs8_768), pubk768.export({ type: "spki", format: "der" }).equals(spki_768));
const jwk768 = priv768.export({ format: "jwk" }) as { kty?: string; alg?: string; pub?: string; priv?: string };
log("jwk", jwk768.kty, jwk768.alg, jwk768.pub!.length, jwk768.priv!.length);
log("jwk rt", createPrivateKey({ key: jwk768, format: "jwk" }).export({ type: "pkcs8", format: "der" }).equals(pkcs8_768));
log("decaps", 768, decapsulate(priv768, ct768).equals(ss768));
const enc768 = encapsulate(pubk768);
log("roundtrip", 768, enc768.sharedKey.length, enc768.ciphertext.length, decapsulate(priv768, enc768.ciphertext).equals(enc768.sharedKey));
const pubFromPem768 = createPublicKey(priv768.export({ type: "pkcs8", format: "pem" }));
// Node's createPublicKey also reads a private key's PKCS#8 DER (the types
// list only the public encodings).
const pubFromDer768 = createPublicKey({
key: pkcs8_768,
format: "der",
type: "pkcs8",
} as unknown as { key: Buffer; format: "der"; type: "spki" });
log("public from private", pubFromPem768.asymmetricKeyType, pubFromDer768.asymmetricKeyType,
Buffer.from(pubFromPem768.export({ type: "spki", format: "der" })).equals(spki_768),
Buffer.from(pubFromDer768.export({ type: "spki", format: "der" })).equals(spki_768));
// The raw encodings: the public key's 1184 bytes (the SPKI's payload) and
// the private key's 64-byte seed. ML-KEM keys carry no EC context.
const rawPublic768 = pubk768.export({ format: "raw-public" } as never) as Buffer;
const rawSeed768 = priv768.export({ format: "raw-seed" } as never) as Buffer;
log("raw", Buffer.from(rawPublic768).length, Buffer.from(rawPublic768).equals(pub768),
Buffer.from(rawSeed768).length, Buffer.from(rawSeed768).equals(seed768));
const seed1024 = Buffer.from("489456f6d3014b4e44344a4aa5c60e9b4c2d0ff6a1e3c9239c5882f333a2e86799d3a8fe7ad06da6aa19832494796619073d9fae152c530b6d245a648dbff2d2", "hex");
const pub1024 = Buffer.from("811769bdd10a7ffc5e8b74b35b845878129658a813f0579e292b1ca24b24ba10cef9a388d39424f3512dd6d7691e570c0c539b8ce9ade47c803fd6ac79c89567eb1727e28b3cc561f643a51b457789195a4af620a6753dbb802dbaf6ae46b89f839c7fd330b04cdccace3bb540f24520d77a6005a393e1c37bbaca6bd24bc641444d4c32ae3cbabc7a834f20572ea149e6a3a0fc320dbb362674f023c02cc80007a7d961cdf9674065c5ca063b951cc899b2d65ac7155d54c31addb2566f06031e69a1bcc74a33271e5731baf35c01d10ba0347cc7d03a301da64b38b16a54166f2d23b9dc7b7d8ee66f03d6c252f931d3ba226c9b17b380a08bb6574570317353c0c1c3336b58b9225627aa2998c8068bd5b803da2404133327f1d05453c37938436ad6960bf004199335cf140b4ab2c469c89959ea88924d38b03b1466cf78498b095fb71135bc341a6eb4b6e4731c61f205be54ba9c98a4cef075b25998f7a02194b5840bf5bb2e9028af44424e346dc87a8f7ec420ff3cc5e6e4bf56f8a882386dae647cbca164f432c7c5934d88256ca0d57ba1e88a0b119a5cc86f262b6206171de83a4e4f17005694a99a01af11859d19300c385024ddd51481a0888271343f46964e1729f57cb8d3e58863aa8a57e53ea294b78414132a615239451118071084e919c52964835a64e4017134e73e5adb369dc7515f80c281d252ee10b3c839654cd633f857b5a47821b6993617c7ba5a4c8e945bab9e3024ed7b3c00ab2633e066fbe0a015781f19f64782009697db8a3409b5da368861e24a16e5b5748a2853fc7ef58519aa1bb18ec6b36fc7271ec27bdfa01bb230545a6ca0197c9cc0d96cb4e2af1b6c250b08454890315b1b8e12780e1b24a9f3b90de0171ffa3989df39bcfed47dde643898d003ef3a281764a677a6b045001a487845d270a02c3170ef4064d442acda65880f5ac38be523db71a85f9131a8ab6c6f652b616b038a1c760bc8350989bc433b6764935d486845d3326b867c3471f1c1a00330b235ba753860188c1e3cc996ea3599e97338cf355f69d3bbe8dc6b1296434159b89b11be8236748c208548560d5da69b717602f8b18113d03d7fc84d46b99ab9c66aa55b8bbf77a26bc87af154ab1552317e19862e357407c1a25f75a01310c73b14948b754d62c89da9b4142f399a06ba756e920de83664cf90142230b90aab87c3e517cb497206882a8db361fe8b2ced1071da306e6687975597996cc0739ec46d3b512c348a37bb2c4efbd981fbe4bdbe758244c6baeab5292f34471090a70c0229ebf5ad38c716dd33ac3425ca45aa28566857386450ce72c89b6830d985381ec02eeb0a714ad908812b0313f24e83c656f44910b66c7b054c62feb217764671b224a9d89881afc658bc90383ce189739755cf5433ad419204697f50316909d38ebce5390ac5b9d4ab119c607aa14129436b6e13d36c5c00020aca01eb4802c235373a092266b3cd9d55ad7ba088bdc92430608ff930b62bf2aefa472d261445168c02eeeb0608b84df47b1a5814b682d90e7f894d9b5111a176a980b5202cc24c304821c1576a83f314d9a9cf9f36631c5371b340883f7549ca944a5998553eba202193173e54276b04adf4382d42d2c7d60b816ff9357ae8c765b3c65d81087dfa08223c625e6821c994986a055c0461621a63a90dd805ff162ec5a28d1c94bc465c016d9bb8f5c14b82fb5280c2a01037a147e21d960b4301ec365f4c622bfa1ac4c71d2feaaf9be2bc66b48e42ca07fbf9aa1cf4801fb4717143c6f67029daca695f786204f6caafb47ea3032a3630201a5a81f1780c4bf60659e9a096b30dbea229c8163ad264ae7c841c7ec6b3947b838bc859bd3b9b5a4c0e662c8cdcfc7f18b39ed8da248b5c964c43b4cb596f0e583d8fa1581531cbd4d3180838bbd2e74a078788e9bb3fe741cdd4e17f6da862a3d291672a78e65272de802aee4524e392ad1a48280129a6f2090d4810ac93c0723a92aab31906bb1c35e6546266e8a37b4c10027a6268796a0b5643044c438ed460c1d35955533a4242630f4170d329a6ef42aaeeb329b7517918759f2507b6b1462dd2812ce421627a96b172ac6804570c038506ba999d1f64ce5a99007a5068624959ca06b16b2980fa05ba68dcc2b0e500db28e700d9471a962c44f79bd6cc1d0a3f23045c567d9c19c830", "hex");
const ct1024 = Buffer.from("bed603a0af9fcabbc5c30a707abe71d06840675ec302d5c3191a7f255de8ac7f5a84520f749cda339f2ef185ab8622a13ba406fd3fb6d89426794c7a798f7401187bbb3d971ce39e4fe81047fda06c4e06a063640d5a33f92f9067c9de53b8fd85cf95fd421631824c330008e1b1c9b59b9c0489bd2803c678a91724e3204020b5c8f1ef9bf415806606f292681f7d3f0acab163fc815a218ed4f23890ddf57db0cb8cdb3c6d72702a3500d06e79ed77764ec22de47df8d0de80a266273c56e459306f3473140368d7b6068b29571eab7d2fe13d20a4f8779e389a54af5122ba40a704fc106b9c366823e90381be9088c8e171894050108af6df731f8bebe7b37ebee6e201a3c7e124e67d26fa1104860df0130f504b80274d162f3c99389de960d4e1e93f1d90fb4161d9d1e034e09adf50583c19def330670c8498e82a285d9c8a46ef019d3e1485434e9ab770463c0f060bef26f2b7c282133cac9c5ec1bf2d72fe189e2fdf4d570ea58eb61ab50580aadb529ccf0933037e1b84489601571fbe9f880b0ba13bb744967dcc0c69cb36a5996ce669b91ee9bd1376818ff97d046912ef585bed0a535a08ebb7727b882d67a60a2c909641494b366e1308ab431f64cf89f82ba72f30d57056bc63402a1aa0dd9fe8971ba8d0a0ab116b1404a0311670a645d69d4016bee0bb8450bde3568ce87c98e6b129c6d4dff514eb4785eda0e061aac12e62745dbe4b53ee35a100ed8ca0817c92aee664da41983719a71674a16521b981d42d876840c0e31223b1a3d01e3085fb86f53e2dc725fed4b1908e59ee0924f4c5b9939e361df1ccff06125ee40a5974c820e7438c10eeaf25b2184d6f613996cfb87f80d44b0b1d7dd498a953ffb77c07972dd71ee6df8db56f6edba23ea6827084fe3d342a99ab7ae8fe0ef48e8e43b4eb29554cd8f2e285a298b30bd3d10864cb36e4d74ced5a02e5d1cdb66d8630fcc13aa3acc9550e7e30e5bb63bbc20dd850d305d1eee460a38910e31b49dfb87e6009e00cd0bea1aa134f6e66dbeb6adefe05e8f8706e476cc36cc78d8117c3446d3c87356003b186792bf6d787854149764e4f157c4a36eb9ccd783c3cbb60dbbe46e808fee5ede5656961710ef6ab25df5e720b86373d4cfeee346538e77fc1c3e53d9455631b5ab24a0d32b764d429ce2e298a3755b3b3b418bb12f90080ea11d762954ee244c6e39b03fa4f7f4df6bf4207c36f1f4bffa189889468b94c3ba83e11f87ad8e756c7a0e2d216e8494051df22df8a72683e1fd5d4944844b6ad5cd6cbdf84086e6cd75c49dd4c42248e180fdc6fe7d05313ea7f7e24389f4ce7faf72cd949e3aa66f81dabad88c9d9d429ec1c23b80923e45cddf3891f5483ceb9cc1b0aeab90c5f68c5fad4c323ad17542a8dc53840831ed084f745e8814048733d1d43c237f798026093c2b56735cf31c037e033000874007e10b9af0f8c48251e826f75781466520b7cf3a93cc393308cf041990840fb7251e6f4f0df99141194c3e67319cbf797a0505851ee12f59437ba7c73d32be3b8289ab0739de9999b50226a26bee310a58b71cef093fecd8677bf0fb756f00e24cb7baf6c9c2c06f64c67268d50d30887ccb5675814bd44c739fb0f0f0ed6c5af572f6914553702e61064c7bd2a96edaf9d63809393d3dd68520adaee50cf368d31ae5c0f2494ea4ea31f323427d91dad8ddf66b95e4a4cf14ded957a74eee90278b616803c385d99da88be08475de9e466cdb70e53ab43c87a9ed1f7d66008bb7f4e6e4cec7a674bdac049714ff14bb0f08d55bb8ea0e7523791d12f94a4c8180908f38d8fd0f4fba672d30656d73fe0b192debc34bd45f611a13c15315fdf81c91905b567076a9a16222e5b01a0d129d4e93252ec02f30f2203573283a6be0f73e1c99388aa0535df3680e9ae5352c4d559ea490addf283f419fcf729998dcf06fc6b5fb9fde933bf731ef8443800519918bec78da6533ab6502045bd69bd609f74b204466d223f98046da46f116565d1d4d081e9d173a469fb9f929d25ecf0b86ac419809ee0db9b5a84d71bf1b2aff8714a1ca877eca00c7f98e12e31c929fce45777c53a20e3f1cf337251cde0e8da9b1aaa42621374c2e2f5f33d9c278b3af01262f2c065f93edfc50b529f7189611026ebc2f7d646d23b706cd62a69936b0cec26722a41adb0e289e032e316", "hex");
const ss1024 = Buffer.from("91b5ee20dccab22a67005c6eb682081fe3a92410d849f5d85fbe89f4cbc17846", "hex");
const pkcs8_1024 = Buffer.concat([Buffer.from("3054020100300b060960864801650304040304428040", "hex"), seed1024]);
const spki_1024 = Buffer.concat([Buffer.from("30820632300b06096086480165030404030382062100", "hex"), pub1024]);
const priv1024 = createPrivateKey({ key: pkcs8_1024, format: "der", type: "pkcs8" });
const pubk1024 = createPublicKey({ key: spki_1024, format: "der", type: "spki" });
log("level", 1024, priv1024.asymmetricKeyType, pubk1024.asymmetricKeyType, JSON.stringify(priv1024.asymmetricKeyDetails));
log("der", priv1024.export({ type: "pkcs8", format: "der" }).equals(pkcs8_1024), pubk1024.export({ type: "spki", format: "der" }).equals(spki_1024));
const jwk1024 = priv1024.export({ format: "jwk" }) as { kty?: string; alg?: string; pub?: string; priv?: string };
log("jwk", jwk1024.kty, jwk1024.alg, jwk1024.pub!.length, jwk1024.priv!.length);
log("jwk rt", createPrivateKey({ key: jwk1024, format: "jwk" }).export({ type: "pkcs8", format: "der" }).equals(pkcs8_1024));
log("decaps", 1024, decapsulate(priv1024, ct1024).equals(ss1024));
const enc1024 = encapsulate(pubk1024);
log("roundtrip", 1024, enc1024.sharedKey.length, enc1024.ciphertext.length, decapsulate(priv1024, enc1024.ciphertext).equals(enc1024.sharedKey));
const typed = (label: string, run: () => unknown) => {
try { run(); log(label, "ok"); } catch (error) { const x = error as Error & { code?: string }; log(label, x.name, x.code, x.message); }
};
typed("decapsulate public", () => decapsulate(pubk768, ct768));
typed("bad ciphertext", () => decapsulate(priv768, Buffer.alloc(10)));
typed("string key", () => encapsulate("x" as unknown as typeof pubk768));
const ed = generateKeyPairSync("ed25519");
typed("ed25519 key", () => encapsulate(ed.publicKey));
typed("wrong level ciphertext", () => decapsulate(priv768, ct512));
typed("raw-private", () => priv768.export({ format: "raw-private" } as never));
typed("private raw-public", () => priv768.export({ format: "raw-public" } as never));
typed("public raw-seed", () => pubk768.export({ format: "raw-seed" } as never));
typed("number ciphertext", () => decapsulate(priv768, 5 as never));
typed("object ciphertext", () => decapsulate(priv768, {} as never));
log("string ciphertext", decapsulate(priv768, "x".repeat(1088) as never).length,
decapsulate(priv768, "α".repeat(544) as never).length);
typed("string wrong length", () => decapsulate(priv768, "x".repeat(1087) as never));
for (const level of [512, 768, 1024] as const) {
const kp = generateKeyPairSync(level === 512 ? "ml-kem-512" : level === 768 ? "ml-kem-768" : "ml-kem-1024");
log("gen", level, kp.privateKey.asymmetricKeyType, kp.publicKey.export({ type: "spki", format: "der" }).length, kp.privateKey.export({ type: "pkcs8", format: "der" }).length);
log("gen roundtrip", level, Buffer.from(createPublicKey(kp.privateKey).export({ type: "spki", format: "der" })).equals(Buffer.from(kp.publicKey.export({ type: "spki", format: "der" }))));
const e = encapsulate(kp.publicKey);
log("gen kem", level, decapsulate(kp.privateKey, e.ciphertext).equals(e.sharedKey));
}
@@ -0,0 +1 @@
{ "plain": 2600, "san": 3800 }
@@ -0,0 +1 @@
{ "plain": 3600, "san": 5200 }