Lightpanda: the headless browser designed for AI and automation
webapi: EC key import and export (spki, pkcs8, raw, jwk)
orezraey042b58a5eb99
diff --git a/src/browser/tests/crypto.html b/src/browser/tests/crypto.htmlindex 408eb21f2..4995056b7 100644--- a/src/browser/tests/crypto.html+++ b/src/browser/tests/crypto.html@@ -959,6 +959,170 @@});</script>+<script id=ec-key-formats type=module>+ const state = await testing.async();+ const subtle = crypto.subtle;+ const errorName = async (fn) => {+ try {+ await fn();+ return null;+ } catch (err) {+ return err.name;+ }+ };+ const hex = (buf) => Array.from(new Uint8Array(buf), (b) => b.toString(16).padStart(2, "0")).join("");+ const b64urlLen = (s) => atob(s.replace(/-/g, "+").replace(/_/g, "/")).length;+ const ecdsa = (namedCurve) => ({ name: "ECDSA", namedCurve });+ const ecdh = (namedCurve) => ({ name: "ECDH", namedCurve });+ const data = new TextEncoder().encode("ec key formats");++ // Every format round trips: spki/pkcs8 byte for byte, raw as 0x04 || x || y.+ const pair = await subtle.generateKey(ecdsa("P-256"), true, ["sign", "verify"]);+ const raw = new Uint8Array(await subtle.exportKey("raw", pair.publicKey));+ const spki = await subtle.exportKey("spki", pair.publicKey);+ const pkcs8 = await subtle.exportKey("pkcs8", pair.privateKey);+ const publicJwk = await subtle.exportKey("jwk", pair.publicKey);+ const privateJwk = await subtle.exportKey("jwk", pair.privateKey);+ const fromRaw = await subtle.importKey("raw", raw, ecdsa("P-256"), true, ["verify"]);+ const fromSpki = await subtle.importKey("spki", spki, ecdsa("P-256"), true, ["verify"]);+ const fromPkcs8 = await subtle.importKey("pkcs8", pkcs8, ecdsa("P-256"), true, ["sign"]);+ const fromPublicJwk = await subtle.importKey("jwk", publicJwk, ecdsa("P-256"), true, ["verify"]);+ const fromPrivateJwk = await subtle.importKey("jwk", privateJwk, ecdsa("P-256"), true, ["sign"]);+ // A compressed point (0x02/0x03 || x) imports to the same key.+ const compressed = new Uint8Array(33);+ compressed[0] = raw[64] & 1 ? 3 : 2;+ compressed.set(raw.subarray(1, 33), 1);+ const fromCompressed = await subtle.importKey("raw", compressed, ecdsa("P-256"), true, ["verify"]);+ // The imported keys work: one signs, the others verify.+ const signature = await subtle.sign({ name: "ECDSA", hash: "SHA-256" }, fromPrivateJwk, data);+ const verified = [];+ for (const key of [fromRaw, fromSpki, fromPublicJwk, fromCompressed, pair.publicKey]) {+ verified.push(await subtle.verify({ name: "ECDSA", hash: "SHA-256" }, key, signature, data));+ }++ // ECDH: the sizes of each curve, and JWK keys that derive the same secret.+ const sizes = [];+ for (const curve of ["P-256", "P-384", "P-521"]) {+ const k = await subtle.generateKey(ecdh(curve), true, ["deriveBits"]);+ const j = await subtle.exportKey("jwk", k.privateKey);+ sizes.push(`${(await subtle.exportKey("raw", k.publicKey)).byteLength}/${b64urlLen(j.x)}/${b64urlLen(j.d)}`);+ }+ const alice = await subtle.generateKey(ecdh("P-384"), true, ["deriveBits"]);+ const bob = await subtle.generateKey(ecdh("P-384"), true, ["deriveBits"]);+ const aliceJwk = await subtle.importKey("jwk", await subtle.exportKey("jwk", alice.privateKey), ecdh("P-384"), false, ["deriveBits"]);+ const bobRaw = await subtle.importKey("raw", await subtle.exportKey("raw", bob.publicKey), ecdh("P-384"), true, []);+ const secret = hex(await subtle.deriveBits({ name: "ECDH", public: bob.publicKey }, alice.privateKey, 384));+ // P-521: 66-byte coordinates, compressed too, and ES512.+ const p521 = await subtle.generateKey(ecdsa("P-521"), true, ["sign", "verify"]);+ const p521Raw = new Uint8Array(await subtle.exportKey("raw", p521.publicKey));+ const p521Compressed = new Uint8Array(67);+ p521Compressed[0] = p521Raw[132] & 1 ? 3 : 2;+ p521Compressed.set(p521Raw.subarray(1, 67), 1);+ const p521FromCompressed = hex(await subtle.exportKey("raw", await subtle.importKey("raw", p521Compressed, ecdsa("P-521"), true, ["verify"])));+ const p521Jwk = await subtle.exportKey("jwk", p521.publicKey);+ const p521ES512 = await errorName(() => subtle.importKey("jwk", { ...p521Jwk, alg: "ES512" }, ecdsa("P-521"), true, ["verify"]));+ const p521ES256 = await errorName(() => subtle.importKey("jwk", { ...p521Jwk, alg: "ES256" }, ecdsa("P-521"), true, ["verify"]));+ const secretFromImports = hex(await subtle.deriveBits({ name: "ECDH", public: bobRaw }, aliceJwk, 384));+ const dhPublicJwk = await subtle.exportKey("jwk", alice.publicKey);+ const dhPrivateJwk = await subtle.exportKey("jwk", alice.privateKey);++ const other = await subtle.exportKey("jwk", (await subtle.generateKey(ecdsa("P-256"), true, ["sign"])).privateKey);+ const zeroPrefixed = (b64url) => btoa("\0" + atob(b64url.replace(/-/g, "+").replace(/_/g, "/"))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");+ const offCurve = raw.slice();+ offCurve[64] ^= 1;+ const { y: _y, ...noY } = publicJwk;+ const importPublic = (jwk) => errorName(() => subtle.importKey("jwk", jwk, ecdsa("P-256"), true, ["verify"]));++ const results = {+ // raw is the public point only, of the requested curve.+ rawShort: await errorName(() => subtle.importKey("raw", raw.slice(0, 64), ecdsa("P-256"), true, ["verify"])),+ rawOffCurve: await errorName(() => subtle.importKey("raw", offCurve, ecdsa("P-256"), true, ["verify"])),+ rawOtherCurve: await errorName(() => subtle.importKey("raw", raw, ecdsa("P-384"), true, ["verify"])),+ rawForSign: await errorName(() => subtle.importKey("raw", raw, ecdsa("P-256"), true, ["sign"])),+ rawOfPrivate: await errorName(() => subtle.exportKey("raw", pair.privateKey)),+ dhRawWithUsage: await errorName(() => subtle.importKey("raw", raw, ecdh("P-256"), true, ["deriveBits"])),+ // DER of another key type, or of another curve than the requested one, is DataError.+ rsaSpki: await errorName(() => subtle.importKey("spki", rsaTestKey.spki, ecdsa("P-256"), true, ["verify"])),+ rsaPkcs8: await errorName(() => subtle.importKey("pkcs8", rsaTestKey.pkcs8, ecdh("P-256"), true, ["deriveBits"])),+ spkiOtherCurve: await errorName(() => subtle.importKey("spki", spki, ecdsa("P-384"), true, ["verify"])),+ pkcs8OtherCurve: await errorName(() => subtle.importKey("pkcs8", pkcs8, ecdsa("P-521"), true, ["sign"])),+ spkiOfPrivate: await errorName(() => subtle.exportKey("spki", pair.privateKey)),+ pkcs8OfPublic: await errorName(() => subtle.exportKey("pkcs8", pair.publicKey)),+ // JWK: kty "EC" and crv, matched case-sensitively; ECDSA's alg names the curve.+ ktyLower: await importPublic({ ...publicJwk, kty: "ec" }),+ crvLower: await importPublic({ ...publicJwk, crv: "p-256" }),+ crvOther: await importPublic({ ...publicJwk, crv: "P-384" }),+ algES256: await importPublic({ ...publicJwk, alg: "ES256" }),+ algES384: await importPublic({ ...publicJwk, alg: "ES384" }),+ useEnc: await importPublic({ ...publicJwk, use: "enc" }),+ noY: await importPublic(noY),+ shortX: await importPublic({ ...publicJwk, x: publicJwk.x.slice(0, -2) }),+ paddedD: await errorName(() => subtle.importKey("jwk", { ...privateJwk, d: zeroPrefixed(privateJwk.d) }, ecdsa("P-256"), true, ["sign"])),+ otherD: await errorName(() => subtle.importKey("jwk", { ...privateJwk, d: other.d }, ecdsa("P-256"), true, ["sign"])),+ // ECDH ignores alg, and its keys are "enc" ones (checked when usages are asked for).+ dhAlg: await errorName(() => subtle.importKey("jwk", { ...dhPublicJwk, alg: "bogus" }, ecdh("P-384"), true, [])),+ dhPublicUseSig: await errorName(() => subtle.importKey("jwk", { ...dhPublicJwk, use: "sig" }, ecdh("P-384"), true, [])),+ dhPrivateUseSig: await errorName(() => subtle.importKey("jwk", { ...dhPrivateJwk, use: "sig" }, ecdh("P-384"), true, ["deriveBits"])),+ // Other algorithms ignore a stray namedCurve.+ aesWithCurve: await errorName(() => subtle.importKey("raw", new Uint8Array(16), { name: "AES-GCM", namedCurve: "P-256" }, true, ["encrypt"])),+ };+ const again = {+ raw: hex(await subtle.exportKey("raw", fromRaw)),+ compressed: hex(await subtle.exportKey("raw", fromCompressed)),+ spki: hex(await subtle.exportKey("spki", fromSpki)),+ pkcs8: hex(await subtle.exportKey("pkcs8", fromPkcs8)),+ privateJwk: JSON.stringify(await subtle.exportKey("jwk", fromPrivateJwk)),+ };++ state.resolve();+ await state.done(() => {+ testing.expectEqual("65 4", `${raw.length} ${raw[0]}`);+ testing.expectEqual(hex(raw), again.raw);+ testing.expectEqual(hex(raw), again.compressed);+ testing.expectEqual(hex(spki), again.spki);+ testing.expectEqual(hex(pkcs8), again.pkcs8);+ testing.expectEqual(JSON.stringify(privateJwk), again.privateJwk);+ testing.expectEqual("crv,ext,key_ops,kty,x,y", Object.keys(publicJwk).join(","));+ testing.expectEqual("crv,d,ext,key_ops,kty,x,y", Object.keys(privateJwk).join(","));+ testing.expectEqual("P-256 EC verify sign", `${publicJwk.crv} ${publicJwk.kty} ${publicJwk.key_ops} ${privateJwk.key_ops}`);+ testing.expectEqual("ECDSA P-256 public", `${fromPublicJwk.algorithm.name} ${fromPublicJwk.algorithm.namedCurve} ${fromPublicJwk.type}`);+ testing.expectEqual("private", fromPrivateJwk.type);+ testing.expectEqual("true,true,true,true,true", verified.join(","));+ testing.expectEqual("65/32/32,97/48/48,133/66/66", sizes.join(","));+ testing.expectEqual(secret, secretFromImports);+ testing.expectEqual(hex(p521Raw), p521FromCompressed);+ testing.expectEqual(null, p521ES512);+ testing.expectEqual("DataError", p521ES256);+ testing.expectEqual("", dhPublicJwk.key_ops.join(","));+ testing.expectEqual("DataError", results.rawShort);+ testing.expectEqual("DataError", results.rawOffCurve);+ testing.expectEqual("DataError", results.rawOtherCurve);+ testing.expectEqual("SyntaxError", results.rawForSign);+ testing.expectEqual("InvalidAccessError", results.rawOfPrivate);+ testing.expectEqual("SyntaxError", results.dhRawWithUsage);+ testing.expectEqual("DataError", results.rsaSpki);+ testing.expectEqual("DataError", results.rsaPkcs8);+ testing.expectEqual("DataError", results.spkiOtherCurve);+ testing.expectEqual("DataError", results.pkcs8OtherCurve);+ testing.expectEqual("InvalidAccessError", results.spkiOfPrivate);+ testing.expectEqual("InvalidAccessError", results.pkcs8OfPublic);+ testing.expectEqual("DataError", results.ktyLower);+ testing.expectEqual("DataError", results.crvLower);+ testing.expectEqual("DataError", results.crvOther);+ testing.expectEqual(null, results.algES256);+ testing.expectEqual("DataError", results.algES384);+ testing.expectEqual("DataError", results.useEnc);+ testing.expectEqual("DataError", results.noY);+ testing.expectEqual("DataError", results.shortX);+ testing.expectEqual("DataError", results.paddedD);+ testing.expectEqual("DataError", results.otherD);+ testing.expectEqual(null, results.dhAlg);+ testing.expectEqual(null, results.dhPublicUseSig);+ testing.expectEqual("DataError", results.dhPrivateUseSig);+ testing.expectEqual(null, results.aesWithCurve);+ });+</script>+<script id=wrap-unwrap type=module>const state = await testing.async();const subtle = crypto.subtle;@@ -1065,7 +1229,7 @@// The wrapped key: exportable, in a format it has.notExtractable: await errorName(() => subtle.wrapKey("raw", locked, wrapper, gcm)),rsaRaw: await errorName(() => subtle.wrapKey("raw", rsa.privateKey, wrapper, gcm)),- // Only a public key has a raw form; EC's (the public point) isn't implemented.+ // Only a public key has a raw form (EC's is the public point).x25519PrivateRaw: await errorName(() => subtle.wrapKey("raw", x25519.privateKey, wrapper, gcm)),ecPrivateRaw: await errorName(() => subtle.wrapKey("raw", ecdh.privateKey, wrapper, gcm)),ecPublicRaw: await errorName(() => subtle.wrapKey("raw", ecdh.publicKey, wrapper, gcm)),@@ -1096,7 +1260,7 @@testing.expectEqual("NotSupportedError", results.rsaRaw);testing.expectEqual("InvalidAccessError", results.x25519PrivateRaw);testing.expectEqual("InvalidAccessError", results.ecPrivateRaw);- testing.expectEqual("NotSupportedError", results.ecPublicRaw);+ testing.expectEqual(null, results.ecPublicRaw);testing.expectEqual(null, results.x25519PublicRaw);testing.expectEqual("TypeError", results.badFormat);testing.expectEqual("NotSupportedError", results.encryptWithKw);diff --git a/src/browser/webapi/SubtleCrypto.zig b/src/browser/webapi/SubtleCrypto.zigindex b8624e42a..bc1fe52f6 100644--- a/src/browser/webapi/SubtleCrypto.zig+++ b/src/browser/webapi/SubtleCrypto.zig@@ -134,11 +134,17 @@ pub fn importKey(// Public keys may have empty usages; secret/private keys may not.const mask = try common.usageMaskInner(allowed, key_usages, is_private);if (EC.canonicalName(name) != null) {- const der = switch (key_data) {- .bytes => |b| b.values,- .jwk => return error.NotSupported,- };- return EC.import(name, algo.namedCurve(), format, der, 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 EC.import(name, algo.namedCurve(), format, b.values, is_private, extractable, mask, exec);+ },+ .jwk => |jwk| {+ if (!is_jwk) return local.typeError("this format expects a BufferSource");+ return EC.importJwk(name, algo.namedCurve(), jwk, extractable, mask, exec);+ },+ }}if (RSA.scheme(name)) |scheme| {const hash_name = importHash(algo) orelse return local.typeError("RSA import requires a hash");@@ -308,11 +314,12 @@ const Exported = union(enum) {const Jwk = union(enum) {secret: JwkSecret,rsa: RSA.Jwk,+ ec: EC.Jwk,fn toJs(self: Jwk, local: *const js.Local) !js.Value {return switch (self) {.secret => |jwk| local.zigValueToJs(jwk, .{}),- .rsa => |rsa| switch (rsa) {+ inline .rsa, .ec => |asymmetric| switch (asymmetric) {inline else => |jwk| local.zigValueToJs(jwk, .{}),},};@@ -323,7 +330,7 @@ const Jwk = union(enum) {fn toJson(self: Jwk, allocator: std.mem.Allocator) ![]const u8 {return switch (self) {.secret => |jwk| std.json.Stringify.valueAlloc(allocator, jwk, .{}),- .rsa => |rsa| switch (rsa) {+ inline .rsa, .ec => |asymmetric| switch (asymmetric) {inline else => |jwk| std.json.Stringify.valueAlloc(allocator, jwk, .{}),},};@@ -347,10 +354,9 @@ fn exportAs(format: []const u8, key: *CryptoKey, exec: *const Execution) !Exportreturn error.InvalidAccessError;}// EC keys live in `_vary.pkey` too, with no bytes in `_key`: their raw- // form (the public point) isn't implemented, and an empty buffer- // would pass for one.+ // form is the public point.if (key._type == .ec) {- return error.NotSupported;+ return .{ .bytes = try EC.exportRaw(key, exec) };}return .{ .bytes = key._key };}@@ -361,8 +367,8 @@ fn exportAs(format: []const u8, key: *CryptoKey, exec: *const Execution) !Exportconst is_der = std.mem.eql(u8, format, "pkcs8") or std.mem.eql(u8, format, "spki");if (is_der) {- if (key._type == .rsa) {- return .{ .bytes = try RSA.exportDer(format, key, exec) };+ if (key._type == .rsa or key._type == .ec) {+ return .{ .bytes = try common.exportDer(format, key, exec) };}log.debug(.not_implemented, "SubtleCrypto.exportKey", .{ .format = format });return error.NotSupported;@@ -386,6 +392,7 @@ fn exportJwk(key: *CryptoKey, exec: *const Execution) !Jwk {.aes => try AES.jwkAlg(key._algorithm.name, key._key.len, exec),.hmac => try HMAC.jwkAlg(key._algorithm.hash orelse "SHA-", exec),.rsa => return .{ .rsa = try RSA.exportJwk(key, exec) },+ .ec => return .{ .ec = try EC.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/EC.zig b/src/browser/webapi/crypto/EC.zigindex bc0d72922..363663b0e 100644--- a/src/browser/webapi/crypto/EC.zig+++ b/src/browser/webapi/crypto/EC.zig@@ -16,9 +16,9 @@// 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/>.-//! ECDSA / ECDH key generation, import (spki/pkcs8 via DER), ECDSA sign and-//! verify, and ECDH key agreement. Key bytes live as a libcrypto EVP_PKEY in-//! `CryptoKey._vary.pkey`.+//! ECDSA / ECDH key generation, import and export (spki/pkcs8 DER, raw public+//! points and JWK), ECDSA sign and verify, and ECDH key agreement. Key bytes+//! live as a libcrypto EVP_PKEY in `CryptoKey._vary.pkey`.const std = @import("std");const crypto = @import("../../../sys/libcrypto.zig");@@ -42,16 +42,27 @@ pub fn canonicalName(name: []const u8) ?[]const u8 {return null;}-fn curveNid(named_curve: []const u8) ?c_int {- if (eqlIgnoreCase(named_curve, "P-256")) return crypto.NID_X9_62_prime256v1;- if (eqlIgnoreCase(named_curve, "P-384")) return crypto.NID_secp384r1;- if (eqlIgnoreCase(named_curve, "P-521")) return crypto.NID_secp521r1;- return null;-}--fn curveCanonical(named_curve: []const u8) ?[]const u8 {- inline for ([_][]const u8{ "P-256", "P-384", "P-521" }) |c| {- if (eqlIgnoreCase(named_curve, c)) return c;+/// A curve ECDSA and ECDH keys can be on.+const Curve = struct {+ /// The registered `namedCurve`, also the JWK `crv`.+ name: []const u8,+ nid: c_int,+ /// The size in bytes of a coordinate, and of the private scalar.+ size: usize,+ /// The JWK `alg` of an ECDSA key on the curve (JWA, section 3.1).+ jwk_alg: []const u8,+};++const curves = [_]Curve{+ .{ .name = "P-256", .nid = crypto.NID_X9_62_prime256v1, .size = 32, .jwk_alg = "ES256" },+ .{ .name = "P-384", .nid = crypto.NID_secp384r1, .size = 48, .jwk_alg = "ES384" },+ .{ .name = "P-521", .nid = crypto.NID_secp521r1, .size = 66, .jwk_alg = "ES512" },+};++/// The curve of a `namedCurve` (case-insensitive), or null if it isn't one.+fn curveOf(named_curve: []const u8) ?*const Curve {+ for (&curves) |*c| {+ if (eqlIgnoreCase(named_curve, c.name)) return c;}return null;}@@ -77,7 +88,7 @@ pub fn validate(params: algorithm.Init.EcKeyGen, key_usages: []const []const u8)}}- if (curveNid(params.namedCurve) == null) {+ if (curveOf(params.namedCurve) == null) {// Per spec, an unsupported `namedCurve` is NotSupportedError.return error.NotSupported;}@@ -98,8 +109,7 @@ pub fn generate(try validate(params, key_usages);const name = canonicalName(params.name).?;- const curve = curveCanonical(params.namedCurve).?;- const nid = curveNid(params.namedCurve).?;+ const curve = curveOf(params.namedCurve).?;const sets = usageSets(name);// Split the requested usages across the pair: each key keeps only the@@ -107,7 +117,7 @@ pub fn generate(const private_mask = maskOf(sets.private, key_usages);const public_mask = maskOf(sets.public, key_usages);- const ec = crypto.EC_KEY_new_by_curve_name(nid) orelse return error.OutOfMemory;+ const ec = crypto.EC_KEY_new_by_curve_name(curve.nid) orelse return error.OutOfMemory;defer crypto.EC_KEY_free(ec);if (crypto.EC_KEY_generate_key(ec) != 1) {return error.OperationError;@@ -118,7 +128,7 @@ pub fn generate(if (crypto.EVP_PKEY_set1_EC_KEY(private_pkey, ec) != 1) return error.OutOfMemory;// A public-only EVP_PKEY (same curve, just the public point) for the peer.- const pub_ec = crypto.EC_KEY_new_by_curve_name(nid) orelse return error.OutOfMemory;+ const pub_ec = crypto.EC_KEY_new_by_curve_name(curve.nid) orelse return error.OutOfMemory;defer crypto.EC_KEY_free(pub_ec);const point = crypto.EC_KEY_get0_public_key(ec) orelse return error.OperationError;if (crypto.EC_KEY_set_public_key(pub_ec, point) != 1) return error.OperationError;@@ -126,37 +136,23 @@ pub fn generate(errdefer crypto.EVP_PKEY_free(public_pkey);if (crypto.EVP_PKEY_set1_EC_KEY(public_pkey, pub_ec) != 1) return error.OutOfMemory;- const private = try CryptoKey.init(exec, .{- ._type = .ec,- ._kind = .private,- ._extractable = extractable,- ._usages = private_mask,- ._key = &.{},- ._algorithm = .{ .name = name, .named_curve = curve },- ._vary = .{ .pkey = private_pkey },- });-- const public = try CryptoKey.init(exec, .{- ._type = .ec,- ._kind = .public,- // Public keys are always extractable.- ._extractable = true,- ._usages = public_mask,- ._key = &.{},- ._algorithm = .{ .name = name, .named_curve = curve },- ._vary = .{ .pkey = public_pkey },- });+ const private = try newKey(private_pkey, name, curve.name, true, extractable, private_mask, exec);+ // Public keys are always extractable.+ const public = try newKey(public_pkey, name, curve.name, false, true, public_mask, exec);return local.resolvePromise(CryptoKey.Pair{ .privateKey = private, .publicKey = public });}-/// Imports an EC key from DER (`spki` public / `pkcs8` private). jwk/raw aren't-/// handled yet. libcrypto parses the DER, so a malformed structure is DataError.+/// Imports an EC key from `spki` (public) or `pkcs8` (private) DER, or from a+/// `raw` public point (SEC 1: uncompressed or compressed). libcrypto parses+/// the data, so a malformed structure, a point that isn't on the curve, or a+/// key on another curve than `named_curve` is DataError. JWK goes through+/// `importJwk`.pub fn import(name: []const u8,named_curve: []const u8,format: []const u8,- der: []const u8,+ data: []const u8,is_private: bool,extractable: bool,usages_mask: u8,@@ -165,23 +161,27 @@ pub fn import(const local = exec.js.local.?;const canonical = canonicalName(name).?;- const curve = curveCanonical(named_curve) orelse {+ const curve = curveOf(named_curve) orelse {return error.NotSupported;};- var ptr: [*c]const u8 = der.ptr;+ var ptr: [*c]const u8 = data.ptr;const pkey: *crypto.EVP_PKEY = blk: {if (std.mem.eql(u8, format, "spki")) {- break :blk crypto.d2i_PUBKEY(null, &ptr, @intCast(der.len)) orelse {+ break :blk crypto.d2i_PUBKEY(null, &ptr, @intCast(data.len)) orelse {+ crypto.ERR_clear_error();return error.DataError;};}if (std.mem.eql(u8, format, "pkcs8")) {- break :blk crypto.d2i_AutoPrivateKey(null, &ptr, @intCast(der.len)) orelse {+ break :blk crypto.d2i_AutoPrivateKey(null, &ptr, @intCast(data.len)) orelse {+ crypto.ERR_clear_error();return error.DataError;};}- // jwk / raw not implemented yet.+ if (std.mem.eql(u8, format, "raw")) {+ break :blk try keyFromPoint(curve, data, null);+ }return error.NotSupported;};errdefer crypto.EVP_PKEY_free(pkey);@@ -189,18 +189,199 @@ pub fn import(if (crypto.EVP_PKEY_id(pkey) != crypto.EVP_PKEY_EC) {return error.DataError;}+ const ec = crypto.EVP_PKEY_get0_EC_KEY(pkey) orelse return error.DataError;+ const group = crypto.EC_KEY_get0_group(ec) orelse return error.DataError;+ if (crypto.EC_GROUP_get_curve_name(group) != curve.nid) {+ return error.DataError;+ }+ // A private key whose public point doesn't match its scalar, say.+ if (crypto.EC_KEY_check_key(ec) != 1) {+ crypto.ERR_clear_error();+ return error.DataError;+ }++ return local.resolvePromise(try newKey(pkey, canonical, curve.name, is_private, extractable, usages_mask, exec));+}++/// Imports an EC key from a JSON Web Key: `crv`, `x` and `y` for a public key,+/// plus `d` for a private one (the presence of `d` decides, as in+/// SubtleCrypto.importKind, which already validated the usages against it).+/// Follows the "jwk" steps of ECDSA's and ECDH's "import key": kty "EC", the+/// common use ("sig" for ECDSA, "enc" for ECDH) / key_ops / ext checks, `crv`+/// equal to the requested curve and, for ECDSA, an `alg` naming it (ES256,+/// ...); then coordinates of the curve's size that make a valid key. Anything+/// else is DataError.+pub fn importJwk(+ name: []const u8,+ named_curve: []const u8,+ jwk: algorithm.KeyData.Jwk,+ extractable: bool,+ usages_mask: u8,+ exec: *const Execution,+) !js.Promise {+ const local = exec.js.local.?;++ const canonical = canonicalName(name).?;+ const curve = curveOf(named_curve) orelse return error.NotSupported;+ const is_ecdsa = std.mem.eql(u8, canonical, "ECDSA");++ if (!std.mem.eql(u8, jwk.kty orelse "", "EC")) return error.DataError;+ try common.checkJwk(jwk, if (is_ecdsa) "sig" else "enc", usages_mask, extractable);+ // `crv` and `alg` are matched case-sensitively; ECDH ignores `alg`.+ if (!std.mem.eql(u8, jwk.crv orelse "", curve.name)) return error.DataError;+ if (is_ecdsa) {+ if (jwk.alg) |alg| {+ if (!std.mem.eql(u8, alg, curve.jwk_alg)) return error.DataError;+ }+ }++ // The public point, uncompressed: 0x04 || x || y.+ const n = curve.size;+ const point = try exec.local_arena.alloc(u8, 1 + 2 * n);+ point[0] = 0x04;+ @memcpy(point[1 .. 1 + n], try jwkCoordinate(jwk.x, n, exec));+ @memcpy(point[1 + n ..], try jwkCoordinate(jwk.y, n, exec));+ const d = if (jwk.d) |member| try jwkCoordinate(member, n, exec) else null;- const crypto_key = try CryptoKey.init(exec, .{+ const pkey = try keyFromPoint(curve, point, d);+ errdefer crypto.EVP_PKEY_free(pkey);+ return local.resolvePromise(try newKey(pkey, canonical, curve.name, d != null, extractable, usages_mask, exec));+}++/// A JWK coordinate or private scalar: base64url of exactly the curve's size.+/// A missing member or one of another size is DataError.+fn jwkCoordinate(member: ?[]const u8, n: usize, exec: *const Execution) ![]const u8 {+ const bytes = try common.base64Decode(exec.local_arena, member orelse return error.DataError);+ if (bytes.len != n) return error.DataError;+ return bytes;+}++/// An EC EVP_PKEY on `curve` from an encoded public point and, for a private+/// key, its scalar. A point not on the curve, or a scalar that doesn't match+/// it, is DataError.+fn keyFromPoint(curve: *const Curve, point: []const u8, private: ?[]const u8) !*crypto.EVP_PKEY {+ const ec = crypto.EC_KEY_new_by_curve_name(curve.nid) orelse return error.OutOfMemory;+ defer crypto.EC_KEY_free(ec);+ const group = crypto.EC_KEY_get0_group(ec) orelse return error.OperationError;++ const pub_point = crypto.EC_POINT_new(group) orelse return error.OutOfMemory;+ defer crypto.EC_POINT_free(pub_point);+ if (point.len == 0 or crypto.EC_POINT_oct2point(group, pub_point, point.ptr, point.len, null) != 1) {+ crypto.ERR_clear_error();+ return error.DataError;+ }+ if (crypto.EC_KEY_set_public_key(ec, pub_point) != 1) return error.DataError;++ if (private) |scalar| {+ const bn = crypto.BN_bin2bn(scalar.ptr, scalar.len, null) orelse return error.OutOfMemory;+ defer crypto.BN_free(bn);+ if (crypto.EC_KEY_set_private_key(ec, bn) != 1) {+ crypto.ERR_clear_error();+ return error.DataError;+ }+ }+ if (crypto.EC_KEY_check_key(ec) != 1) {+ crypto.ERR_clear_error();+ return error.DataError;+ }++ const pkey = crypto.EVP_PKEY_new() orelse return error.OutOfMemory;+ errdefer crypto.EVP_PKEY_free(pkey);+ if (crypto.EVP_PKEY_set1_EC_KEY(pkey, ec) != 1) return error.OutOfMemory;+ return pkey;+}++/// Wraps an EC `pkey` in a CryptoKey. The key takes ownership of `pkey` only+/// on success.+fn newKey(+ pkey: *crypto.EVP_PKEY,+ name: []const u8,+ curve: []const u8,+ is_private: bool,+ extractable: bool,+ usages_mask: u8,+ exec: *const Execution,+) !*CryptoKey {+ return CryptoKey.init(exec, .{._type = .ec,._kind = if (is_private) .private else .public,._extractable = extractable,._usages = usages_mask,._key = &.{},- ._algorithm = .{ .name = canonical, .named_curve = curve },+ ._algorithm = .{ .name = name, .named_curve = curve },._vary = .{ .pkey = pkey },});+}++/// The public point of an EC key, uncompressed (0x04 || x || y): the `raw`+/// export, and the source of a JWK's `x` and `y`.+pub fn exportRaw(key: *const CryptoKey, exec: *const Execution) ![]const u8 {+ const ec = crypto.EVP_PKEY_get0_EC_KEY(key.getKeyObject()) orelse return error.OperationError;+ const group = crypto.EC_KEY_get0_group(ec) orelse return error.OperationError;+ const point = crypto.EC_KEY_get0_public_key(ec) orelse return error.OperationError;+ const len = crypto.EC_POINT_point2oct(group, point, crypto.POINT_CONVERSION_UNCOMPRESSED, null, 0, null);+ if (len == 0) return error.OperationError;+ const out = try exec.local_arena.alloc(u8, len);+ if (crypto.EC_POINT_point2oct(group, point, crypto.POINT_CONVERSION_UNCOMPRESSED, out.ptr, out.len, null) != len) {+ return error.OperationError;+ }+ return out;+}- return local.resolvePromise(crypto_key);+/// The JWK of an EC key (JWA, section 6.2). Members are listed in+/// lexicographic order, the order browsers return a JsonWebKey in; there's no+/// `alg`, as browsers don't set one either.+const JwkPublic = struct {+ crv: []const u8,+ ext: bool,+ key_ops: []const []const u8,+ kty: []const u8 = "EC",+ x: []const u8,+ y: []const u8,+};++const JwkPrivate = struct {+ crv: []const u8,+ d: []const u8,+ ext: bool,+ key_ops: []const []const u8,+ kty: []const u8 = "EC",+ x: []const u8,+ y: []const u8,+};++/// The JWK of either half of an EC key.+pub const Jwk = union(enum) {+ public: JwkPublic,+ private: JwkPrivate,+};++/// Exports an EC key as a JWK: `crv`, `x` and `y` for either half, plus `d`+/// for the private key, each coordinate of the curve's size.+pub fn exportJwk(key: *const CryptoKey, exec: *const Execution) !Jwk {+ const curve = curveOf(key._algorithm.named_curve orelse "") orelse return error.OperationError;+ const n = curve.size;+ const point = try exportRaw(key, exec);+ if (point.len != 1 + 2 * n) return error.OperationError;+ const x = try common.base64Encode(exec.local_arena, point[1 .. 1 + n]);+ const y = try common.base64Encode(exec.local_arena, point[1 + n ..]);+ const key_ops = try key.getUsages(exec);++ if (key._kind == .public) {+ return .{ .public = .{ .crv = curve.name, .ext = key._extractable, .key_ops = key_ops, .x = x, .y = y } };+ }+ const ec = crypto.EVP_PKEY_get0_EC_KEY(key.getKeyObject()) orelse return error.OperationError;+ const scalar = crypto.EC_KEY_get0_private_key(ec) orelse return error.OperationError;+ const d = try exec.local_arena.alloc(u8, n);+ if (crypto.BN_bn2bin_padded(d.ptr, n, scalar) != 1) return error.OperationError;+ return .{ .private = .{+ .crv = curve.name,+ .d = try common.base64Encode(exec.local_arena, d),+ .ext = key._extractable,+ .key_ops = key_ops,+ .x = x,+ .y = y,+ } };}/// ECDH key agreement: derive `length_in_bits` from `private` + the peerdiff --git a/src/browser/webapi/crypto/RSA.zig b/src/browser/webapi/crypto/RSA.zigindex 915cc62ca..327a2aae1 100644--- a/src/browser/webapi/crypto/RSA.zig+++ b/src/browser/webapi/crypto/RSA.zig@@ -371,28 +371,6 @@ fn newKey(});}-/// 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) ![]const u8 {- 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;-- return exec.local_arena.dupe(u8, out[0..@intCast(len)]);-}-/// The JWK of an RSA key (JWA, section 6.3). Members are listed in/// lexicographic order, the order browsers return a JsonWebKey in.const JwkPublic = struct {diff --git a/src/browser/webapi/crypto/algorithm.zig b/src/browser/webapi/crypto/algorithm.zigindex a2534d5e2..b5a27e438 100644--- a/src/browser/webapi/crypto/algorithm.zig+++ b/src/browser/webapi/crypto/algorithm.zig@@ -187,11 +187,13 @@ pub const KeyData = union(enum) {/// 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.+ /// (public) plus `d`, `p`, `q`, `dp`, `dq`, `qi` (private); EC keys `crv`,+ /// `x`, `y` (public) plus `d` (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,+ crv: ?[]const u8 = null,d: ?[]const u8 = null,dp: ?[]const u8 = null,dq: ?[]const u8 = null,@@ -205,6 +207,8 @@ pub const KeyData = union(enum) {q: ?[]const u8 = null,qi: ?[]const u8 = null,use: ?[]const u8 = null,+ x: ?[]const u8 = null,+ y: ?[]const u8 = null,};};diff --git a/src/browser/webapi/crypto/common.zig b/src/browser/webapi/crypto/common.zigindex e1d28669e..973801f8e 100644--- a/src/browser/webapi/crypto/common.zig+++ b/src/browser/webapi/crypto/common.zig@@ -23,8 +23,11 @@const std = @import("std");const Allocator = std.mem.Allocator;+const crypto = @import("../../../sys/libcrypto.zig");+const js = @import("../../js/js.zig");const CryptoKey = @import("../CryptoKey.zig");const algorithm = @import("algorithm.zig");+const Execution = js.Execution;/// The hashes the algorithms take (their `hash` member).pub const hashes = [_][]const u8{ "SHA-1", "SHA-256", "SHA-384", "SHA-512" };@@ -150,3 +153,26 @@ pub fn base64Encode(allocator: Allocator, bytes: []const u8) error{OutOfMemory}!const out = try allocator.alloc(u8, encoder.calcSize(bytes.len));return encoder.encode(out, bytes);}++/// Exports an asymmetric key (RSA, EC) 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) ![]const u8 {+ 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;++ return exec.local_arena.dupe(u8, out[0..@intCast(len)]);+}diff --git a/src/sys/libcrypto.zig b/src/sys/libcrypto.zigindex 1584559b2..5876677ef 100644--- a/src/sys/libcrypto.zig+++ b/src/sys/libcrypto.zig@@ -149,11 +149,26 @@ pub extern fn EC_KEY_generate_key(key: *EC_KEY) c_int;pub extern fn EC_KEY_free(key: ?*EC_KEY) void;pub extern fn EC_KEY_get0_public_key(key: *const EC_KEY) ?*const EC_POINT;pub extern fn EC_KEY_set_public_key(key: *EC_KEY, point: *const EC_POINT) c_int;+pub extern fn EC_KEY_get0_private_key(key: *const EC_KEY) ?*const BIGNUM;+pub extern fn EC_KEY_set_private_key(key: *EC_KEY, priv: *const BIGNUM) c_int;+/// 1 when the public key is a valid point (not infinity) and matches the+/// private key, if any.+pub extern fn EC_KEY_check_key(key: *const EC_KEY) c_int;pub extern fn EVP_PKEY_get0_EC_KEY(pkey: *const EVP_PKEY) ?*EC_KEY;const struct_ec_group_st = opaque {};const EC_GROUP = struct_ec_group_st;pub extern fn EC_KEY_get0_group(key: *const EC_KEY) ?*const EC_GROUP;pub extern fn EC_GROUP_get0_order(group: *const EC_GROUP) ?*const BIGNUM;+pub extern fn EC_GROUP_get_curve_name(group: *const EC_GROUP) c_int;++// SEC 1 point encodings: 0x04 || x || y, or compressed 0x02/0x03 || x.+pub const POINT_CONVERSION_UNCOMPRESSED = 4;+pub extern fn EC_POINT_new(group: *const EC_GROUP) ?*EC_POINT;+pub extern fn EC_POINT_free(point: ?*EC_POINT) void;+/// Fails for an encoding that isn't a point on the curve.+pub extern fn EC_POINT_oct2point(group: *const EC_GROUP, point: *EC_POINT, buf: [*]const u8, len: usize, ctx: ?*anyopaque) c_int;+/// With a null `buf`, returns the encoding's length; 0 on error.+pub extern fn EC_POINT_point2oct(group: *const EC_GROUP, point: *const EC_POINT, form: c_int, buf: ?[*]u8, len: usize, ctx: ?*anyopaque) usize;// ECDSA over a digest, with the signature as an (r, s) pair.const struct_ecdsa_sig_st = opaque {};