Skip to content

Lightpanda: the headless browser designed for AI and automation

webapi: RSA-OAEP export (spki, pkcs8, jwk) and jwk import

orezraeyac68ae3ce15a
diff --git a/src/browser/tests/crypto.html b/src/browser/tests/crypto.html
index ae1903466..6670873fe 100644
--- a/src/browser/tests/crypto.html
+++ b/src/browser/tests/crypto.html
@@ -234,6 +234,176 @@
});
</script>
+<script id=rsa-oaep-export type=module>
+ const state = await testing.async();
+ const algo = { name: "RSA-OAEP", hash: "SHA-256" };
+ const { privateKey, publicKey } = await crypto.subtle.generateKey(
+ { ...algo, modulusLength: 1024, publicExponent: new Uint8Array([1, 0, 1]) },
+ true,
+ ["encrypt", "decrypt"],
+ );
+ const hex = (buf) => Array.from(new Uint8Array(buf), (b) => b.toString(16).padStart(2, "0")).join("");
+ const msg = new TextEncoder().encode("exported key path");
+ const roundTrip = async (pub, priv) =>
+ new TextDecoder().decode(await crypto.subtle.decrypt(algo, priv, await crypto.subtle.encrypt(algo, pub, msg)));
+
+ // DER: spki and pkcs8 survive an import/export round trip byte for byte.
+ const spki = await crypto.subtle.exportKey("spki", publicKey);
+ const pkcs8 = await crypto.subtle.exportKey("pkcs8", privateKey);
+ const spkiKey = await crypto.subtle.importKey("spki", spki, algo, true, ["encrypt"]);
+ const pkcs8Key = await crypto.subtle.importKey("pkcs8", pkcs8, algo, true, ["decrypt"]);
+ const spkiAgain = await crypto.subtle.exportKey("spki", spkiKey);
+ const pkcs8Again = await crypto.subtle.exportKey("pkcs8", pkcs8Key);
+
+ // JWK: the public members on both halves, the private ones on the private key.
+ const publicJwk = await crypto.subtle.exportKey("jwk", publicKey);
+ const privateJwk = await crypto.subtle.exportKey("jwk", privateKey);
+ const jwkPublicKey = await crypto.subtle.importKey("jwk", publicJwk, algo, true, ["encrypt"]);
+ const jwkPrivateKey = await crypto.subtle.importKey("jwk", privateJwk, algo, true, ["decrypt"]);
+ const privateJwkAgain = await crypto.subtle.exportKey("jwk", jwkPrivateKey);
+
+ // A JWK without `alg`, `ext` or `key_ops` imports too; SHA-1 is plain "RSA-OAEP".
+ const bare = await crypto.subtle.importKey("jwk", { kty: "RSA", n: publicJwk.n, e: publicJwk.e }, { name: "RSA-OAEP", hash: "SHA-1" }, true, ["encrypt"]);
+ const bareJwk = await crypto.subtle.exportKey("jwk", bare);
+ // Each hash has its own `alg`, which a JWK import accepts back.
+ const algs = [];
+ for (const hash of ["SHA-1", "SHA-256", "SHA-384", "SHA-512"]) {
+ const key = await crypto.subtle.importKey("jwk", { kty: "RSA", n: publicJwk.n, e: publicJwk.e }, { name: "RSA-OAEP", hash }, true, ["encrypt"]);
+ const { alg } = await crypto.subtle.exportKey("jwk", key);
+ await crypto.subtle.importKey("jwk", { kty: "RSA", n: publicJwk.n, e: publicJwk.e, alg }, { name: "RSA-OAEP", hash }, true, ["encrypt"]);
+ algs.push(alg);
+ }
+
+ const results = {
+ viaSpki: await roundTrip(spkiKey, privateKey),
+ viaPkcs8: await roundTrip(publicKey, pkcs8Key),
+ viaJwk: await roundTrip(jwkPublicKey, jwkPrivateKey),
+ };
+
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual(hex(spki), hex(spkiAgain));
+ testing.expectEqual(hex(pkcs8), hex(pkcs8Again));
+ testing.expectEqual("public", spkiKey.type);
+ testing.expectEqual("private", pkcs8Key.type);
+ testing.expectEqual("RSA,RSA-OAEP-256,AQAB,true", [publicJwk.kty, publicJwk.alg, publicJwk.e, publicJwk.ext].join(","));
+ testing.expectEqual("encrypt", publicJwk.key_ops.join(","));
+ testing.expectEqual(false, "d" in publicJwk);
+ testing.expectEqual("decrypt", privateJwk.key_ops.join(","));
+ testing.expectEqual(publicJwk.n, privateJwk.n);
+ testing.expectEqual(6, ["d", "dp", "dq", "p", "q", "qi"].filter((m) => typeof privateJwk[m] === "string" && privateJwk[m].length > 0).length);
+ testing.expectEqual(JSON.stringify(privateJwk), JSON.stringify(privateJwkAgain));
+ testing.expectEqual("private", jwkPrivateKey.type);
+ testing.expectEqual(1024, jwkPrivateKey.algorithm.modulusLength);
+ testing.expectEqual("1,0,1", jwkPrivateKey.algorithm.publicExponent.join(","));
+ testing.expectEqual("exported key path", results.viaSpki);
+ testing.expectEqual("exported key path", results.viaPkcs8);
+ testing.expectEqual("exported key path", results.viaJwk);
+ testing.expectEqual("RSA-OAEP", bareJwk.alg);
+ testing.expectEqual("SHA-1", bare.algorithm.hash.name);
+ testing.expectEqual("RSA-OAEP,RSA-OAEP-256,RSA-OAEP-384,RSA-OAEP-512", algs.join(","));
+ });
+</script>
+
+<script id=rsa-oaep-jwk-errors type=module>
+ const state = await testing.async();
+ const errorName = async (fn) => {
+ try {
+ await fn();
+ return null;
+ } catch (err) {
+ return err.name;
+ }
+ };
+ const algo = { name: "RSA-OAEP", hash: "SHA-256" };
+ const gen = (extractable) => crypto.subtle.generateKey(
+ { ...algo, modulusLength: 1024, publicExponent: new Uint8Array([1, 0, 1]) },
+ extractable,
+ ["encrypt", "decrypt"],
+ );
+ const { privateKey, publicKey } = await gen(true);
+ const locked = await gen(false);
+ const pub = await crypto.subtle.exportKey("jwk", publicKey);
+ const priv = await crypto.subtle.exportKey("jwk", privateKey);
+ const importPublic = (jwk, extractable = true, usages = ["encrypt"]) =>
+ errorName(() => crypto.subtle.importKey("jwk", jwk, algo, extractable, usages));
+ const importPrivate = (jwk, usages = ["decrypt"]) =>
+ errorName(() => crypto.subtle.importKey("jwk", jwk, algo, true, usages));
+ // base64url of the member's bytes with a 0x00 octet in front.
+ const zeroPrefixed = (b64url) => {
+ const raw = atob(b64url.replace(/-/g, "+").replace(/_/g, "/"));
+ return btoa("\0" + raw).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
+ };
+ const { qi, ...withoutQi } = priv;
+ const { kty, ...withoutKty } = pub;
+ // Without key_ops, so the usage check (SyntaxError) is the one that fails.
+ const { key_ops: _publicOps, ...pubNoOps } = pub;
+ const { key_ops: _privateOps, ...privNoOps } = priv;
+
+ const results = {
+ // exportKey: each DER format belongs to one half; a non-extractable key exports nothing.
+ spkiOfPrivate: await errorName(() => crypto.subtle.exportKey("spki", privateKey)),
+ pkcs8OfPublic: await errorName(() => crypto.subtle.exportKey("pkcs8", publicKey)),
+ notExtractable: await errorName(() => crypto.subtle.exportKey("jwk", locked.privateKey)),
+ // importKey: the format and the key data must agree.
+ jwkFromBytes: await errorName(() => crypto.subtle.importKey("jwk", new Uint8Array(8), algo, true, ["encrypt"])),
+ spkiFromJwk: await errorName(() => crypto.subtle.importKey("spki", pub, algo, true, ["encrypt"])),
+ // The usages must fit the half the JWK describes (`d` makes it private).
+ privateForEncrypt: await importPrivate(privNoOps, ["encrypt"]),
+ publicForDecrypt: await importPublic(pubNoOps, true, ["decrypt"]),
+ // kty, use and alg are matched case-sensitively; alg must name the requested hash.
+ ktyMissing: await importPublic(withoutKty),
+ ktyEc: await importPublic({ ...pub, kty: "EC" }),
+ ktyLower: await importPublic({ ...pub, kty: "rsa" }),
+ useSig: await importPublic({ ...pub, use: "sig" }),
+ algOtherHash: await importPublic({ ...pub, alg: "RSA-OAEP" }),
+ algLower: await importPublic({ ...pub, alg: "rsa-oaep-256" }),
+ algUnknown: await importPublic({ ...pub, alg: "RS256" }),
+ // ext and key_ops can only narrow what is asked for.
+ extFalse: await importPublic({ ...pub, ext: false }),
+ extFalseLocked: await importPublic({ ...pub, ext: false }, false),
+ keyOpsMissing: await importPublic({ ...pub, key_ops: ["wrapKey"] }),
+ keyOpsDuplicate: await importPublic({ ...pub, key_ops: ["encrypt", "encrypt"] }),
+ keyOpsWider: await importPublic({ ...pub, key_ops: ["encrypt", "wrapKey"] }),
+ // The members must be present, minimal, well-formed, and make a valid key.
+ missingN: await importPublic({ kty: "RSA", e: pub.e }),
+ emptyE: await importPublic({ ...pub, e: "" }),
+ leadingZero: await importPublic({ ...pub, n: zeroPrefixed(pub.n) }),
+ notBase64: await importPublic({ ...pub, n: "!!!" }),
+ missingQi: await importPrivate(withoutQi),
+ wrongD: await importPrivate({ ...priv, d: priv.dp }),
+ };
+
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual("InvalidAccessError", results.spkiOfPrivate);
+ testing.expectEqual("InvalidAccessError", results.pkcs8OfPublic);
+ testing.expectEqual("InvalidAccessError", results.notExtractable);
+ testing.expectEqual("TypeError", results.jwkFromBytes);
+ testing.expectEqual("TypeError", results.spkiFromJwk);
+ testing.expectEqual("SyntaxError", results.privateForEncrypt);
+ testing.expectEqual("SyntaxError", results.publicForDecrypt);
+ testing.expectEqual("DataError", results.ktyMissing);
+ testing.expectEqual("DataError", results.ktyEc);
+ testing.expectEqual("DataError", results.ktyLower);
+ testing.expectEqual("DataError", results.useSig);
+ testing.expectEqual("DataError", results.algOtherHash);
+ testing.expectEqual("DataError", results.algLower);
+ testing.expectEqual("DataError", results.algUnknown);
+ testing.expectEqual("DataError", results.extFalse);
+ testing.expectEqual(null, results.extFalseLocked);
+ testing.expectEqual("DataError", results.keyOpsMissing);
+ testing.expectEqual("DataError", results.keyOpsDuplicate);
+ testing.expectEqual(null, results.keyOpsWider);
+ testing.expectEqual("DataError", results.missingN);
+ testing.expectEqual("DataError", results.emptyE);
+ testing.expectEqual("DataError", results.leadingZero);
+ testing.expectEqual("DataError", results.notBase64);
+ testing.expectEqual("DataError", results.missingQi);
+ testing.expectEqual("DataError", results.wrongD);
+ });
+</script>
+
<script id=aes-ctr-counter-wrap type=module>
const state = await testing.async();
// AES-CTR must increment only the rightmost `length` bits of the counter
diff --git a/src/browser/webapi/SubtleCrypto.zig b/src/browser/webapi/SubtleCrypto.zig
index 8bfda0830..8713f8cfd 100644
--- a/src/browser/webapi/SubtleCrypto.zig
+++ b/src/browser/webapi/SubtleCrypto.zig
@@ -141,10 +141,6 @@ pub fn importKey(
return EC.import(name, algo.namedCurve(), format, der, is_private, extractable, mask, exec);
}
if (RSA.canonicalName(name) != null) {
- const der = switch (key_data) {
- .bytes => |b| b.values,
- .jwk => return error.NotSupported,
- };
// RSA-OAEP import params {name, hash} match the `.hmac` variant of the
// Import union (same shape: a name plus a hash), so the hash is read there.
const hash_name = switch (algo) {
@@ -154,7 +150,17 @@ pub fn importKey(
},
else => return local.typeError("RSA-OAEP import requires a hash"),
};
- return RSA.import(format, der, hash_name, is_private, extractable, mask, exec);
+ const is_jwk = std.mem.eql(u8, format, "jwk");
+ switch (key_data) {
+ .bytes => |b| {
+ if (is_jwk) return local.typeError("jwk format expects an object");
+ return RSA.import(format, b.values, hash_name, is_private, extractable, mask, exec);
+ },
+ .jwk => |jwk| {
+ if (!is_jwk) return local.typeError("this format expects a BufferSource");
+ return RSA.importJwk(jwk, hash_name, extractable, mask, exec);
+ },
+ }
}
log.debug(.not_implemented, "SubtleCrypto.importKey", .{ .name = name });
return error.NotSupported;
@@ -175,7 +181,7 @@ pub fn importKey(
.jwk => |j| j,
.bytes => return local.typeError("jwk format expects an object"),
};
- if (!std.mem.eql(u8, jwk.kty, "oct")) {
+ if (!std.mem.eql(u8, jwk.kty orelse "", "oct")) {
return error.DataError;
}
const k = jwk.k orelse return error.DataError;
@@ -281,8 +287,11 @@ pub fn exportKey(
return exportJwk(key, exec);
}
- const is_unsupported = std.mem.eql(u8, format, "pkcs8") or std.mem.eql(u8, format, "spki");
- if (is_unsupported) {
+ const is_der = std.mem.eql(u8, format, "pkcs8") or std.mem.eql(u8, format, "spki");
+ if (is_der) {
+ if (key._type == .rsa) {
+ return RSA.exportDer(format, key, exec);
+ }
log.debug(.not_implemented, "SubtleCrypto.exportKey", .{ .format = format });
return error.NotSupported;
}
@@ -312,6 +321,7 @@ fn exportJwk(key: *CryptoKey, exec: *const Execution) !js.Promise {
const hash: []const u8 = key._algorithm.hash orelse "SHA-";
break :blk try exec.local_arena.print("HS{s}", .{hash[4..]}); // strip "SHA-"
},
+ .rsa => return RSA.exportJwk(key, exec),
else => {
log.debug(.not_implemented, "SubtleCrypto.exportKey", .{ .format = "jwk", .type = key._type });
return error.NotSupported;
diff --git a/src/browser/webapi/crypto/RSA.zig b/src/browser/webapi/crypto/RSA.zig
index 0a40fea52..69b87be40 100644
--- a/src/browser/webapi/crypto/RSA.zig
+++ b/src/browser/webapi/crypto/RSA.zig
@@ -16,9 +16,10 @@
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
-//! RSA-OAEP: key generation, import (spki/pkcs8 via DER), and the
-//! encrypt/decrypt operations. The key material lives as a libcrypto EVP_PKEY
-//! in `CryptoKey._vary.pkey`. See EC.zig for the asymmetric-key rationale.
+//! RSA-OAEP: key generation, import and export (spki/pkcs8 DER and JWK), and
+//! the encrypt/decrypt operations. The key material lives as a libcrypto
+//! EVP_PKEY in `CryptoKey._vary.pkey`. See EC.zig for the asymmetric-key
+//! rationale.
const std = @import("std");
@@ -99,6 +100,30 @@ pub fn canonicalHash(name: []const u8) ?[]const u8 {
return null;
}
+/// The JWK `alg` of each OAEP hash (JWA, section 4.3).
+const jwk_algs = [_]struct { hash: []const u8, alg: []const u8 }{
+ .{ .hash = "SHA-1", .alg = "RSA-OAEP" },
+ .{ .hash = "SHA-256", .alg = "RSA-OAEP-256" },
+ .{ .hash = "SHA-384", .alg = "RSA-OAEP-384" },
+ .{ .hash = "SHA-512", .alg = "RSA-OAEP-512" },
+};
+
+/// The JWK `alg` for a canonical hash name.
+fn jwkAlgOfHash(hash: []const u8) ?[]const u8 {
+ for (jwk_algs) |entry| {
+ if (std.mem.eql(u8, entry.hash, hash)) return entry.alg;
+ }
+ return null;
+}
+
+/// The canonical hash for a JWK `alg`. The spec matches `alg` case-sensitively.
+fn hashOfJwkAlg(alg: []const u8) ?[]const u8 {
+ for (jwk_algs) |entry| {
+ if (std.mem.eql(u8, entry.alg, alg)) return entry.hash;
+ }
+ return null;
+}
+
const max_modulus_length = 4096;
const private_usages: []const []const u8 = &.{ "decrypt", "unwrapKey" };
@@ -188,8 +213,8 @@ pub fn generate(
}
/// Imports an RSA-OAEP key from DER: `spki` (public) or `pkcs8` (private).
-/// jwk/raw aren't handled yet. libcrypto parses the DER, so a malformed
-/// structure is DataError. `hash_name` is the OAEP digest, kept for encrypt.
+/// libcrypto parses the DER, so a malformed structure is DataError. `hash_name`
+/// is the OAEP digest, kept for encrypt. JWK goes through `importJwk`.
pub fn import(
format: []const u8,
der: []const u8,
@@ -213,14 +238,108 @@ pub fn import(
if (std.mem.eql(u8, format, "pkcs8")) {
break :blk crypto.d2i_AutoPrivateKey(null, &ptr, @intCast(der.len)) orelse return error.DataError;
}
- // jwk / raw not implemented yet.
+ // "raw" isn't a format RSA keys have.
return error.NotSupported;
};
errdefer crypto.EVP_PKEY_free(pkey);
if (crypto.EVP_PKEY_id(pkey) != crypto.EVP_PKEY_RSA) return error.DataError;
- const crypto_key = try CryptoKey.init(exec, .{
+ return local.resolvePromise(try newKey(pkey, hash, is_private, extractable, usages_mask, exec));
+}
+
+/// Imports an RSA-OAEP key from a JSON Web Key: `n` and `e` for a public key,
+/// plus `d`, `p`, `q`, `dp`, `dq` and `qi` for a private one (the presence of
+/// `d` decides, as in SubtleCrypto.importKind, which already validated the
+/// usages against it). Follows the "import key" steps of RSA-OAEP: a JWK that
+/// doesn't fit the requested key, or describes an invalid one, is DataError.
+pub fn importJwk(
+ jwk: algorithm.KeyData.Jwk,
+ hash_name: []const u8,
+ extractable: bool,
+ usages_mask: u8,
+ exec: *const Execution,
+) !js.Promise {
+ const local = exec.js.local.?;
+ const hash = canonicalHash(hash_name) orelse return error.NotSupported;
+
+ if (!std.mem.eql(u8, jwk.kty orelse "", "RSA")) return error.DataError;
+ if (jwk.use) |use| {
+ if (usages_mask != 0 and !std.mem.eql(u8, use, "enc")) return error.DataError;
+ }
+ if (jwk.key_ops) |key_ops| try checkKeyOps(key_ops, usages_mask);
+ if (jwk.ext) |ext| {
+ if (!ext and extractable) return error.DataError;
+ }
+ // `alg` is optional; when present, it must name the requested hash.
+ if (jwk.alg) |alg| {
+ const alg_hash = hashOfJwkAlg(alg) orelse return error.DataError;
+ if (!std.mem.eql(u8, alg_hash, hash)) return error.DataError;
+ }
+
+ const rsa = try rsaFromJwk(jwk, exec);
+ defer crypto.RSA_free(rsa);
+ const pkey = crypto.EVP_PKEY_new() orelse return error.OutOfMemory;
+ errdefer crypto.EVP_PKEY_free(pkey);
+ if (crypto.EVP_PKEY_set1_RSA(pkey, rsa) != 1) return error.OutOfMemory;
+
+ return local.resolvePromise(try newKey(pkey, hash, jwk.d != null, extractable, usages_mask, exec));
+}
+
+/// A JWK `key_ops` must hold every requested usage, and no value twice
+/// (RFC 7517, section 4.3). Values that aren't usages are allowed.
+fn checkKeyOps(key_ops: []const []const u8, usages_mask: u8) !void {
+ var listed: u8 = 0;
+ for (key_ops, 0..) |op, i| {
+ for (key_ops[0..i]) |earlier| {
+ if (std.mem.eql(u8, earlier, op)) return error.DataError;
+ }
+ if (common.usageBit(op)) |bit| listed |= bit;
+ }
+ if (usages_mask & ~listed != 0) return error.DataError;
+}
+
+/// The RSA key described by a JWK (JWA, section 6.3). A private key needs all
+/// of the CRT members; libcrypto rejects members that don't make a valid key,
+/// such as the extra primes of `oth`, which this two-prime import ignores.
+fn rsaFromJwk(jwk: algorithm.KeyData.Jwk, exec: *const Execution) !*crypto.RSA {
+ const members = [_]?[]const u8{ jwk.n, jwk.e, jwk.d, jwk.p, jwk.q, jwk.dp, jwk.dq, jwk.qi };
+ const needed: usize = if (jwk.d == null) 2 else members.len;
+
+ var nums: [members.len]*crypto.BIGNUM = undefined;
+ var count: usize = 0;
+ defer for (nums[0..count]) |num| crypto.BN_free(num);
+ for (members[0..needed]) |member| {
+ nums[count] = try jwkBigNum(member, exec);
+ count += 1;
+ }
+
+ if (jwk.d == null) {
+ return crypto.RSA_new_public_key(nums[0], nums[1]) orelse error.DataError;
+ }
+ return crypto.RSA_new_private_key(nums[0], nums[1], nums[2], nums[3], nums[4], nums[5], nums[6], nums[7]) orelse error.DataError;
+}
+
+/// A JWK Base64urlUInt member as a BIGNUM. A missing or empty member, or one
+/// with a leading zero octet (JWA, section 2: it must use the minimum number of
+/// octets), is DataError.
+fn jwkBigNum(member: ?[]const u8, exec: *const Execution) !*crypto.BIGNUM {
+ const bytes = try common.base64Decode(exec.local_arena, member orelse return error.DataError);
+ if (bytes.len == 0 or (bytes.len > 1 and bytes[0] == 0)) return error.DataError;
+ return crypto.BN_bin2bn(bytes.ptr, bytes.len, null) orelse error.OutOfMemory;
+}
+
+/// Wraps an RSA `pkey` in a CryptoKey. The key takes ownership of `pkey` only on
+/// success.
+fn newKey(
+ pkey: *crypto.EVP_PKEY,
+ hash: []const u8,
+ is_private: bool,
+ extractable: bool,
+ usages_mask: u8,
+ exec: *const Execution,
+) !*CryptoKey {
+ return CryptoKey.init(exec, .{
._type = .rsa,
._kind = if (is_private) .private else .public,
._extractable = extractable,
@@ -234,15 +353,102 @@ pub fn import(
},
._vary = .{ .pkey = pkey },
});
- return local.resolvePromise(crypto_key);
+}
+
+/// Exports an RSA key as DER: `spki` for a public key, `pkcs8` for a private
+/// one. Asking for the other half's format is InvalidAccessError.
+pub fn exportDer(format: []const u8, key: *const CryptoKey, exec: *const Execution) !js.Promise {
+ const local = exec.js.local.?;
+ const pkey = key.getKeyObject();
+
+ var out: [*c]u8 = null;
+ const len = blk: {
+ if (std.mem.eql(u8, format, "spki")) {
+ if (key._kind != .public) return error.InvalidAccessError;
+ break :blk crypto.i2d_PUBKEY(pkey, &out);
+ }
+ if (key._kind != .private) return error.InvalidAccessError;
+ const info = crypto.EVP_PKEY2PKCS8(pkey) orelse return error.OperationError;
+ defer crypto.PKCS8_PRIV_KEY_INFO_free(info);
+ break :blk crypto.i2d_PKCS8_PRIV_KEY_INFO(info, &out);
+ };
+ defer crypto.OPENSSL_free(out);
+ if (len <= 0) return error.OperationError;
+
+ const der = try exec.local_arena.dupe(u8, out[0..@intCast(len)]);
+ return local.resolvePromise(js.ArrayBuffer{ .values = der });
+}
+
+/// The JWK of an RSA-OAEP key (JWA, section 6.3). Members are listed in
+/// lexicographic order, the order browsers return a JsonWebKey in.
+const JwkPublic = struct {
+ alg: []const u8,
+ e: []const u8,
+ ext: bool,
+ key_ops: []const []const u8,
+ kty: []const u8 = "RSA",
+ n: []const u8,
+};
+
+const JwkPrivate = struct {
+ alg: []const u8,
+ d: []const u8,
+ dp: []const u8,
+ dq: []const u8,
+ e: []const u8,
+ ext: bool,
+ key_ops: []const []const u8,
+ kty: []const u8 = "RSA",
+ n: []const u8,
+ p: []const u8,
+ q: []const u8,
+ qi: []const u8,
+};
+
+/// Exports an RSA-OAEP key as a JWK: the public members for either half, plus
+/// the private members (with the CRT parameters) for the private key.
+pub fn exportJwk(key: *const CryptoKey, exec: *const Execution) !js.Promise {
+ const local = exec.js.local.?;
+ const rsa = crypto.EVP_PKEY_get0_RSA(key.getKeyObject()) orelse return error.OperationError;
+ const alg = jwkAlgOfHash(key._algorithm.hash orelse "") orelse return error.OperationError;
+ const n = try jwkMember(crypto.RSA_get0_n(rsa), exec);
+ const e = try jwkMember(crypto.RSA_get0_e(rsa), exec);
+ const key_ops = try key.getUsages(exec);
+
+ if (key._kind == .public) {
+ return local.resolvePromise(JwkPublic{ .alg = alg, .e = e, .ext = key._extractable, .key_ops = key_ops, .n = n });
+ }
+ return local.resolvePromise(JwkPrivate{
+ .alg = alg,
+ .d = try jwkMember(crypto.RSA_get0_d(rsa), exec),
+ .dp = try jwkMember(crypto.RSA_get0_dmp1(rsa), exec),
+ .dq = try jwkMember(crypto.RSA_get0_dmq1(rsa), exec),
+ .e = e,
+ .ext = key._extractable,
+ .key_ops = key_ops,
+ .n = n,
+ .p = try jwkMember(crypto.RSA_get0_p(rsa), exec),
+ .q = try jwkMember(crypto.RSA_get0_q(rsa), exec),
+ .qi = try jwkMember(crypto.RSA_get0_iqmp(rsa), exec),
+ });
+}
+
+/// A key component as a JWK Base64urlUInt member.
+fn jwkMember(bn: ?*const crypto.BIGNUM, exec: *const Execution) ![]const u8 {
+ return common.base64Encode(exec.local_arena, try bnBytes(bn, exec));
}
/// The public exponent of an RSA EVP_PKEY, big-endian, in the local arena.
fn exponentBytes(pkey: *const crypto.EVP_PKEY, exec: *const Execution) ![]const u8 {
const rsa = crypto.EVP_PKEY_get0_RSA(pkey) orelse return error.OperationError;
- const e = crypto.RSA_get0_e(rsa) orelse return error.OperationError;
- const out = try exec.local_arena.alloc(u8, crypto.BN_num_bytes(e));
- return out[0..crypto.BN_bn2bin(e, out.ptr)];
+ return bnBytes(crypto.RSA_get0_e(rsa), exec);
+}
+
+/// A BIGNUM as big-endian bytes (the minimum number of them), in the local arena.
+fn bnBytes(bn: ?*const crypto.BIGNUM, exec: *const Execution) ![]const u8 {
+ const num = bn orelse return error.OperationError;
+ const out = try exec.local_arena.alloc(u8, crypto.BN_num_bytes(num));
+ return out[0..crypto.BN_bn2bin(num, out.ptr)];
}
/// RSA-OAEP encrypt/decrypt. `encrypting` selects the init/op pair; the
diff --git a/src/browser/webapi/crypto/algorithm.zig b/src/browser/webapi/crypto/algorithm.zig
index 983003860..16d841a7f 100644
--- a/src/browser/webapi/crypto/algorithm.zig
+++ b/src/browser/webapi/crypto/algorithm.zig
@@ -174,15 +174,25 @@ pub const KeyData = union(enum) {
bytes: js.TypedArray(u8),
jwk: Jwk,
- /// Minimal JWK fields we read on import. Symmetric ("oct") keys only need
- /// `kty` and `k`; `d` marks an asymmetric private key. The rest are accepted
- /// for forward-compatibility.
- const Jwk = struct {
+ /// The JWK fields we read on import. Symmetric ("oct") keys only need `kty`
+ /// and `k`; `d` marks an asymmetric private key. RSA keys carry `n`/`e`
+ /// (public) plus `d`, `p`, `q`, `dp`, `dq`, `qi` (private). Every member is
+ /// optional in the JsonWebKey dictionary, `kty` included: a missing `kty`
+ /// is a DataError of the algorithm's import, not a binding TypeError.
+ pub const Jwk = struct {
alg: ?[]const u8 = null,
d: ?[]const u8 = null,
+ dp: ?[]const u8 = null,
+ dq: ?[]const u8 = null,
+ e: ?[]const u8 = null,
ext: ?bool = null,
k: ?[]const u8 = null,
- kty: []const u8,
+ key_ops: ?[]const []const u8 = null,
+ kty: ?[]const u8 = null,
+ n: ?[]const u8 = null,
+ p: ?[]const u8 = null,
+ q: ?[]const u8 = null,
+ qi: ?[]const u8 = null,
use: ?[]const u8 = null,
};
};
diff --git a/src/sys/libcrypto.zig b/src/sys/libcrypto.zig
index 9cb5dd1c9..d4d6fc9c6 100644
--- a/src/sys/libcrypto.zig
+++ b/src/sys/libcrypto.zig
@@ -153,7 +153,36 @@ pub extern fn RSA_generate_key_ex(rsa: *RSA, bits: c_int, e: *const BIGNUM, cb:
pub extern fn RSAPublicKey_dup(rsa: *const RSA) ?*RSA;
pub extern fn EVP_PKEY_set1_RSA(pkey: *EVP_PKEY, key: *RSA) c_int;
pub extern fn EVP_PKEY_get0_RSA(pkey: *const EVP_PKEY) ?*RSA;
+pub extern fn RSA_get0_n(rsa: *const RSA) ?*const BIGNUM;
pub extern fn RSA_get0_e(rsa: *const RSA) ?*const BIGNUM;
+pub extern fn RSA_get0_d(rsa: *const RSA) ?*const BIGNUM;
+pub extern fn RSA_get0_p(rsa: *const RSA) ?*const BIGNUM;
+pub extern fn RSA_get0_q(rsa: *const RSA) ?*const BIGNUM;
+pub extern fn RSA_get0_dmp1(rsa: *const RSA) ?*const BIGNUM;
+pub extern fn RSA_get0_dmq1(rsa: *const RSA) ?*const BIGNUM;
+pub extern fn RSA_get0_iqmp(rsa: *const RSA) ?*const BIGNUM;
+// Build a key from its components; NULL on error or an invalid (inconsistent) key.
+pub extern fn RSA_new_public_key(n: *const BIGNUM, e: *const BIGNUM) ?*RSA;
+pub extern fn RSA_new_private_key(
+ n: *const BIGNUM,
+ e: *const BIGNUM,
+ d: *const BIGNUM,
+ p: *const BIGNUM,
+ q: *const BIGNUM,
+ dmp1: *const BIGNUM,
+ dmq1: *const BIGNUM,
+ iqmp: *const BIGNUM,
+) ?*RSA;
+
+// DER encoders. With `*outp == null`, libcrypto allocates the output (release
+// it with OPENSSL_free) and stores it in `*outp`. Returns the length, or a
+// negative value on error.
+const struct_pkcs8_priv_key_info_st = opaque {};
+pub const PKCS8_PRIV_KEY_INFO = struct_pkcs8_priv_key_info_st;
+pub extern fn i2d_PUBKEY(pkey: *const EVP_PKEY, outp: *[*c]u8) c_int;
+pub extern fn EVP_PKEY2PKCS8(pkey: *const EVP_PKEY) ?*PKCS8_PRIV_KEY_INFO;
+pub extern fn i2d_PKCS8_PRIV_KEY_INFO(key: *const PKCS8_PRIV_KEY_INFO, outp: *[*c]u8) c_int;
+pub extern fn PKCS8_PRIV_KEY_INFO_free(key: ?*PKCS8_PRIV_KEY_INFO) void;
pub extern fn BN_new() ?*BIGNUM;
pub extern fn BN_free(bn: ?*BIGNUM) void;