Lightpanda: the headless browser designed for AI and automation
webapi: Ed25519 (generate, import, export, sign, verify)
orezraey03d5ede5fcf1
diff --git a/src/browser/tests/crypto.html b/src/browser/tests/crypto.htmlindex a7913bf11..09124def6 100644--- a/src/browser/tests/crypto.html+++ b/src/browser/tests/crypto.html@@ -2023,6 +2023,148 @@});</script>+<script id=ed25519 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 unhex = (h) => new Uint8Array(h.match(/../g).map((x) => parseInt(x, 16)));+ const describe = (key) => `${key.type}:${key.algorithm.name}:${key.extractable}:${key.usages.join("+")}`;++ // RFC 8032, section 7.1, test 1 (an empty message).+ const seed = unhex("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60");+ const pub = unhex("d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a");+ const sig = "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b";+ const msg = new Uint8Array(0);+ const x = "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo";+ const d = "nWGxne_9WmC6hEr0kuwsxERJxWl7MmkZcDusAxyuf2A";+ const jwkPublic = { kty: "OKP", crv: "Ed25519", x };+ const identity = new Uint8Array(32);+ identity[0] = 1;+ const jwkPrivate = { ...jwkPublic, d };++ const privateKey = await subtle.importKey("jwk", jwkPrivate, "Ed25519", true, ["sign"]);+ const publicKey = await subtle.importKey("raw", pub, { name: "ed25519" }, true, ["verify"]);+ const spki = await subtle.exportKey("spki", publicKey);+ const pkcs8 = await subtle.exportKey("pkcs8", privateKey);+ const generated = await subtle.generateKey("Ed25519", true, ["sign", "verify"]);+ const generatedSig = await subtle.sign("Ed25519", generated.privateKey, msg);+ const ecdsa = await subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign", "verify"]);++ const results = {+ sign: hex(await subtle.sign("Ed25519", privateKey, msg)),+ verify: await subtle.verify("Ed25519", publicKey, unhex(sig), msg),+ // A signature that doesn't verify, or of the wrong size, is false.+ verifyOther: await subtle.verify("Ed25519", publicKey, unhex(sig), new Uint8Array([1])),+ verifyShort: await subtle.verify("Ed25519", publicKey, unhex(sig).slice(0, 63), msg),+ // A small-order public key or R is false, as the spec asks: here the+ // identity, with which R = identity and S = 0 satisfy [S]B = R + [k]A for+ // any message.+ smallOrder: await subtle.verify("Ed25519", await subtle.importKey("raw", identity, "Ed25519", false, ["verify"]), new Uint8Array([...identity, ...new Uint8Array(32)]), msg),+ raw: hex(await subtle.exportKey("raw", publicKey)),+ spki: hex(spki),+ pkcs8: hex(pkcs8),+ jwkPublic: JSON.stringify(await subtle.exportKey("jwk", publicKey)),+ jwkPrivate: JSON.stringify(await subtle.exportKey("jwk", privateKey)),+ algorithm: JSON.stringify(privateKey.algorithm),+ // Each half exports only in its own formats.+ rawPrivate: await errorName(() => subtle.exportKey("raw", privateKey)),+ spkiPrivate: await errorName(() => subtle.exportKey("spki", privateKey)),+ pkcs8Public: await errorName(() => subtle.exportKey("pkcs8", publicKey)),+ importSpki: describe(await subtle.importKey("spki", spki, "Ed25519", false, ["verify"])),+ importPkcs8: describe(await subtle.importKey("pkcs8", pkcs8, "Ed25519", false, ["sign"])),+ importRawNoUsages: describe(await subtle.importKey("raw", pub, "Ed25519", true, [])),+ // A JWK alg, if present, is "Ed25519" or "EdDSA".+ algEdDSA: describe(await subtle.importKey("jwk", { ...jwkPublic, alg: "EdDSA" }, "Ed25519", true, ["verify"])),+ algEd25519: describe(await subtle.importKey("jwk", { ...jwkPublic, alg: "Ed25519" }, "Ed25519", true, ["verify"])),+ algOther: await errorName(() => subtle.importKey("jwk", { ...jwkPublic, alg: "ES256" }, "Ed25519", true, ["verify"])),+ useEnc: await errorName(() => subtle.importKey("jwk", { ...jwkPublic, use: "enc" }, "Ed25519", true, ["verify"])),+ ktyEc: await errorName(() => subtle.importKey("jwk", { ...jwkPublic, kty: "EC" }, "Ed25519", true, ["verify"])),+ crvX25519: await errorName(() => subtle.importKey("jwk", { ...jwkPublic, crv: "X25519" }, "Ed25519", true, ["verify"])),+ crvLower: await errorName(() => subtle.importKey("jwk", { ...jwkPublic, crv: "ed25519" }, "Ed25519", true, ["verify"])),+ missingX: await errorName(() => subtle.importKey("jwk", { kty: "OKP", crv: "Ed25519", d }, "Ed25519", true, ["sign"])),+ shortX: await errorName(() => subtle.importKey("jwk", { ...jwkPublic, x: x.slice(0, -1) }, "Ed25519", true, ["verify"])),+ // A private JWK's x must be its d's public key.+ otherX: await errorName(() => subtle.importKey("jwk", { ...jwkPrivate, x: "hSDwCYkwp1R0i33ctD73Wg2_Og0mOBr066SpjqqbTmo" }, "Ed25519", true, ["sign"])),+ extFalse: await errorName(() => subtle.importKey("jwk", { ...jwkPublic, ext: false }, "Ed25519", true, ["verify"])),+ privateVerify: await errorName(() => subtle.importKey("jwk", jwkPrivate, "Ed25519", true, ["verify"])),+ rawShort: await errorName(() => subtle.importKey("raw", pub.slice(1), "Ed25519", true, ["verify"])),+ rawSign: await errorName(() => subtle.importKey("raw", pub, "Ed25519", true, ["sign"])),+ spkiTrailing: await errorName(() => subtle.importKey("spki", new Uint8Array([...new Uint8Array(spki), 0]), "Ed25519", true, ["verify"])),+ spkiShort: await errorName(() => subtle.importKey("spki", new Uint8Array(spki).slice(0, -1), "Ed25519", true, ["verify"])),+ spkiOfEcdsa: await errorName(async () => subtle.importKey("spki", await subtle.exportKey("spki", ecdsa.publicKey), "Ed25519", true, ["verify"])),+ pkcs8NoUsages: await errorName(() => subtle.importKey("pkcs8", pkcs8, "Ed25519", true, [])),+ // generateKey: sign goes to the private key, verify to the public one.+ generatedPrivate: describe(generated.privateKey),+ generatedPublic: describe(generated.publicKey),+ generatedVerify: await subtle.verify("Ed25519", generated.publicKey, generatedSig, msg),+ generatedSigLength: generatedSig.byteLength,+ generateVerifyOnly: await errorName(() => subtle.generateKey("Ed25519", true, ["verify"])),+ generateEncrypt: await errorName(() => subtle.generateKey("Ed25519", true, ["sign", "encrypt"])),+ // The key checks of sign/verify.+ signWithPublic: await errorName(() => subtle.sign("Ed25519", publicKey, msg)),+ verifyWithPrivate: await errorName(() => subtle.verify("Ed25519", privateKey, unhex(sig), msg)),+ signAsEcdsa: await errorName(() => subtle.sign({ name: "ECDSA", hash: "SHA-256" }, privateKey, msg)),+ ecdsaAsEd25519: await errorName(() => subtle.sign("Ed25519", ecdsa.privateKey, msg)),+ };++ state.resolve();+ await state.done(() => {+ testing.expectEqual(sig, results.sign);+ testing.expectEqual(true, results.verify);+ testing.expectEqual(false, results.verifyOther);+ testing.expectEqual(false, results.verifyShort);+ testing.expectEqual(false, results.smallOrder);+ testing.expectEqual(hex(pub), results.raw);+ testing.expectEqual("302a300506032b6570032100" + hex(pub), results.spki);+ testing.expectEqual("302e020100300506032b657004220420" + hex(seed), results.pkcs8);+ testing.expectEqual(`{"alg":"Ed25519","crv":"Ed25519","ext":true,"key_ops":["verify"],"kty":"OKP","x":"${x}"}`, results.jwkPublic);+ testing.expectEqual(`{"alg":"Ed25519","crv":"Ed25519","d":"${d}","ext":true,"key_ops":["sign"],"kty":"OKP","x":"${x}"}`, results.jwkPrivate);+ testing.expectEqual('{"name":"Ed25519"}', results.algorithm);+ testing.expectEqual("InvalidAccessError", results.rawPrivate);+ testing.expectEqual("InvalidAccessError", results.spkiPrivate);+ testing.expectEqual("InvalidAccessError", results.pkcs8Public);+ testing.expectEqual("public:Ed25519:false:verify", results.importSpki);+ testing.expectEqual("private:Ed25519:false:sign", results.importPkcs8);+ testing.expectEqual("public:Ed25519:true:", results.importRawNoUsages);+ testing.expectEqual("public:Ed25519:true:verify", results.algEdDSA);+ testing.expectEqual("public:Ed25519:true:verify", results.algEd25519);+ testing.expectEqual("DataError", results.algOther);+ testing.expectEqual("DataError", results.useEnc);+ testing.expectEqual("DataError", results.ktyEc);+ testing.expectEqual("DataError", results.crvX25519);+ testing.expectEqual("DataError", results.crvLower);+ testing.expectEqual("DataError", results.missingX);+ testing.expectEqual("DataError", results.shortX);+ testing.expectEqual("DataError", results.otherX);+ testing.expectEqual("DataError", results.extFalse);+ testing.expectEqual("SyntaxError", results.privateVerify);+ testing.expectEqual("DataError", results.rawShort);+ testing.expectEqual("SyntaxError", results.rawSign);+ testing.expectEqual("DataError", results.spkiTrailing);+ testing.expectEqual("DataError", results.spkiShort);+ testing.expectEqual("DataError", results.spkiOfEcdsa);+ testing.expectEqual("SyntaxError", results.pkcs8NoUsages);+ testing.expectEqual("private:Ed25519:true:sign", results.generatedPrivate);+ testing.expectEqual("public:Ed25519:true:verify", results.generatedPublic);+ testing.expectEqual(true, results.generatedVerify);+ testing.expectEqual(64, results.generatedSigLength);+ testing.expectEqual("SyntaxError", results.generateVerifyOnly);+ testing.expectEqual("SyntaxError", results.generateEncrypt);+ testing.expectEqual("InvalidAccessError", results.signWithPublic);+ testing.expectEqual("InvalidAccessError", results.verifyWithPrivate);+ testing.expectEqual("InvalidAccessError", results.signAsEcdsa);+ testing.expectEqual("InvalidAccessError", results.ecdsaAsEd25519);+ });+</script>+<script id="digest" type=module>const state = await testing.async();async function hash(algo, data) {diff --git a/src/browser/webapi/CryptoKey.zig b/src/browser/webapi/CryptoKey.zigindex df6860e01..7aec0019a 100644--- a/src/browser/webapi/CryptoKey.zig+++ b/src/browser/webapi/CryptoKey.zig@@ -77,7 +77,7 @@ pub const Pair = struct {/// Key-creating functions expect this format.pub const KeyOrPair = union(enum) { key: *CryptoKey, pair: Pair };-pub const Type = enum(u8) { hmac, rsa, x25519, aes, derive, ec };+pub const Type = enum(u8) { hmac, rsa, x25519, aes, derive, ec, ed25519 };pub const Kind = enum {secret,diff --git a/src/browser/webapi/SubtleCrypto.zig b/src/browser/webapi/SubtleCrypto.zigindex 8245318d2..0ae11f1a4 100644--- a/src/browser/webapi/SubtleCrypto.zig+++ b/src/browser/webapi/SubtleCrypto.zig@@ -31,6 +31,7 @@ const HMAC = @import("crypto/HMAC.zig");const RSA = @import("crypto/RSA.zig");const X25519 = @import("crypto/X25519.zig");const KDF = @import("crypto/KDF.zig");+const OKP = @import("crypto/OKP.zig");const common = @import("crypto/common.zig");const log = lp.log;@@ -75,15 +76,18 @@ fn generateKeyFromName(if (name.eql(comptime .wrap("X25519"))) {return X25519.init(extractable, key_usages, exec);}+ if (OKP.curveOf(name.str())) |curve| {+ return OKP.generate(curve, extractable, key_usages, exec);+ }{- // Algorithms whose `generateKey` parameters are just `{name}` — Ed25519,- // Ed448, X448. Validates usages so failure-path tests get the spec-mandated+ // Algorithms whose `generateKey` parameters are just `{name}` — Ed448,+ // X448. Validates usages so failure-path tests get the spec-mandated// error name; leaves real key generation to a future change.const allowed: []const []const u8 = blk: {const str = name.str();- if (eqlIgnoreCase(str, "Ed25519") or eqlIgnoreCase(str, "Ed448")) {+ if (eqlIgnoreCase(str, "Ed448")) {break :blk &.{ "sign", "verify" };}if (eqlIgnoreCase(str, "X448")) {@@ -147,6 +151,19 @@ pub fn importKey(},}}+ if (OKP.curveOf(name)) |curve| {+ 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 OKP.import(curve, format, b.values, is_private, extractable, mask, exec);+ },+ .jwk => |jwk| {+ if (!is_jwk) return local.typeError("this format expects a BufferSource");+ return OKP.importJwk(curve, jwk, extractable, mask, exec);+ },+ }+ }if (RSA.scheme(name)) |scheme| {const hash_name = try importHash(algo, local) orelse return local.typeError("RSA import requires a hash");const is_jwk = std.mem.eql(u8, format, "jwk");@@ -263,8 +280,8 @@ fn importKind(format: []const u8, key_data: algorithm.KeyData) bool {}/// The usages permitted for an EC/OKP/RSA key of the given privacy, or null if-/// the algorithm isn't one of the asymmetric algorithms handled here. Only EC-/// and RSA import their keys; for the others this only drives usage+/// the algorithm isn't one of the asymmetric algorithms handled here. Only EC,+/// RSA and Ed25519 import their keys; for the others this only drives usage/// validation.fn asymmetricAllowedUsages(name: []const u8, is_private: bool) ?[]const []const u8 {if (eqlIgnoreCase(name, "ECDSA") or eqlIgnoreCase(name, "Ed25519") or eqlIgnoreCase(name, "Ed448")) {@@ -313,11 +330,12 @@ const Jwk = union(enum) {secret: JwkSecret,rsa: RSA.Jwk,ec: EC.Jwk,+ okp: OKP.Jwk,fn toJs(self: Jwk, local: *const js.Local) !js.Value {return switch (self) {.secret => |jwk| local.zigValueToJs(jwk, .{}),- inline .rsa, .ec => |asymmetric| switch (asymmetric) {+ inline .rsa, .ec, .okp => |asymmetric| switch (asymmetric) {inline else => |jwk| local.zigValueToJs(jwk, .{}),},};@@ -328,7 +346,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, .{}),- inline .rsa, .ec => |asymmetric| switch (asymmetric) {+ inline .rsa, .ec, .okp => |asymmetric| switch (asymmetric) {inline else => |jwk| std.json.Stringify.valueAlloc(allocator, jwk, .{}),},};@@ -356,6 +374,9 @@ fn exportAs(format: []const u8, key: *CryptoKey, exec: *const Execution) !Exportif (key._type == .ec) {return .{ .bytes = try EC.exportRaw(key, exec) };}+ if (key._type == .ed25519) {+ return .{ .bytes = try OKP.exportRaw(key, exec) };+ }return .{ .bytes = key._key };}@@ -365,7 +386,7 @@ 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 or key._type == .ec) {+ if (key._type == .rsa or key._type == .ec or key._type == .ed25519) {return .{ .bytes = try common.exportDer(format, key, exec) };}log.debug(.not_implemented, "SubtleCrypto.exportKey", .{ .format = format });@@ -391,6 +412,7 @@ fn exportJwk(key: *CryptoKey, exec: *const Execution) !Jwk {.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) },+ .ed25519 => return .{ .okp = try OKP.exportJwk(key, exec) },else => {log.debug(.not_implemented, "SubtleCrypto.exportKey", .{ .format = "jwk", .type = key._type });return error.NotSupported;@@ -710,7 +732,8 @@ pub fn sign(.hmac => try HMAC.sign(key, data, exec),.rsa => try RSA.sign(key, data, params.salt_length, exec),.ec => try EC.sign(key, data, params.hash orelse return error.OperationError, exec),- // A signing algorithm with no sign here yet (Ed25519, Ed448).+ .ed25519 => try OKP.sign(key, data, exec),+ // A signing algorithm with no sign here yet (Ed448).else => {log.debug(.not_implemented, "SubtleCrypto.sign", .{ .key_type = key._type });return error.NotSupported;@@ -736,7 +759,8 @@ pub fn verify(.hmac => try HMAC.verify(key, signature, data),.rsa => try RSA.verify(key, signature, data, params.salt_length),.ec => try EC.verify(key, signature, data, params.hash orelse return error.OperationError),- // A signing algorithm with no verify here yet (Ed25519, Ed448).+ .ed25519 => try OKP.verify(key, signature, data),+ // A signing algorithm with no verify here yet (Ed448).else => {log.debug(.not_implemented, "SubtleCrypto.verify", .{ .key_type = key._type });return error.NotSupported;diff --git a/src/browser/webapi/crypto/EC.zig b/src/browser/webapi/crypto/EC.zigindex 363663b0e..128fc7ad6 100644--- a/src/browser/webapi/crypto/EC.zig+++ b/src/browser/webapi/crypto/EC.zig@@ -83,7 +83,7 @@ pub fn validate(params: algorithm.Init.EcKeyGen, key_usages: []const []const u8)};// A usage that belongs to neither the private nor the public set is illegal.for (key_usages) |usage| {- if (!contains(sets.private, usage) and !contains(sets.public, usage)) {+ if (!common.usageIn(sets.private, usage) and !common.usageIn(sets.public, usage)) {return error.SyntaxError;}}@@ -114,8 +114,8 @@ pub fn generate(// Split the requested usages across the pair: each key keeps only the// usages legal for it. validate() already rejected anything illegal.- const private_mask = maskOf(sets.private, key_usages);- const public_mask = maskOf(sets.public, key_usages);+ const private_mask = common.usageIntersection(sets.private, key_usages);+ const public_mask = common.usageIntersection(sets.public, key_usages);const ec = crypto.EC_KEY_new_by_curve_name(curve.nid) orelse return error.OutOfMemory;defer crypto.EC_KEY_free(ec);@@ -239,23 +239,15 @@ pub fn importJwk(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;+ @memcpy(point[1 .. 1 + n], try common.jwkBytes(exec.local_arena, jwk.x, n));+ @memcpy(point[1 + n ..], try common.jwkBytes(exec.local_arena, jwk.y, n));+ const d = if (jwk.d) |member| try common.jwkBytes(exec.local_arena, member, n) else null;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.@@ -513,26 +505,6 @@ fn digestOf(data: []const u8, hash_name: []const u8, out: *[crypto.EVP_MAX_MD_SIreturn out[0..len];}-fn contains(set: []const []const u8, usage: []const u8) bool {- for (set) |s| {- if (std.mem.eql(u8, s, usage)) {- return true;- }- }- return false;-}--/// The usage bitmask of those `usages` that belong to `set`.-fn maskOf(set: []const []const u8, usages: []const []const u8) u8 {- var mask: u8 = 0;- for (usages) |u| {- if (contains(set, u)) {- mask |= common.usageBit(u).?;- }- }- return mask;-}-fn eqlIgnoreCase(a: []const u8, b: []const u8) bool {return std.ascii.eqlIgnoreCase(a, b);}diff --git a/src/browser/webapi/crypto/OKP.zig b/src/browser/webapi/crypto/OKP.zignew file mode 100644index 000000000..ca5a5eba9--- /dev/null+++ b/src/browser/webapi/crypto/OKP.zig@@ -0,0 +1,317 @@+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)+//+// Francis Bouvier <[email protected]>+// Pierre Tachoire <[email protected]>+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as+// published by the Free Software Foundation, either version 3 of the+// License, or (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// 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/>.++//! Ed25519 keys (RFC 8032): generate, import and export (raw, spki and pkcs8+//! per RFC 8410, jwk per RFC 8037), and sign / verify. The key material lives+//! as a libcrypto EVP_PKEY in `CryptoKey._vary.pkey`, as for EC and RSA.++const std = @import("std");+const crypto = @import("../../../sys/libcrypto.zig");++const js = @import("../../js/js.zig");+const algorithm = @import("algorithm.zig");+const common = @import("common.zig");++const CryptoKey = @import("../CryptoKey.zig");+const Execution = js.Execution;++/// An Octet Key Pair algorithm: its name, which is also its JWK `crv`, and+/// how libcrypto knows it.+pub const Curve = struct {+ name: []const u8,+ key_type: CryptoKey.Type,+ pkey_type: c_int,+ /// The size of the public key and of the private seed.+ size: usize,+};++const curves = [_]Curve{+ .{ .name = "Ed25519", .key_type = .ed25519, .pkey_type = crypto.EVP_PKEY_ED25519, .size = 32 },+};++/// The curve an algorithm name refers to, case-insensitively, or null.+pub fn curveOf(name: []const u8) ?*const Curve {+ for (&curves) |*curve| {+ if (std.ascii.eqlIgnoreCase(name, curve.name)) return curve;+ }+ return null;+}++const private_usages: []const []const u8 = &.{"sign"};+const public_usages: []const []const u8 = &.{"verify"};++/// Generates an Ed25519 key pair: the private key gets the "sign" usage, the+/// public key "verify". Any other usage, or none for the private key, is+/// SyntaxError.+pub fn generate(curve: *const Curve, extractable: bool, key_usages: []const []const u8, exec: *const Execution) !js.Promise {+ const local = exec.js.local.?;++ for (key_usages) |usage| {+ if (!common.usageIn(private_usages, usage) and !common.usageIn(public_usages, usage)) {+ return error.SyntaxError;+ }+ }+ const private_mask = common.usageIntersection(private_usages, key_usages);+ const public_mask = common.usageIntersection(public_usages, key_usages);+ if (private_mask == 0) return error.SyntaxError;++ var public_key: [crypto.ED25519_PUBLIC_KEY_LEN]u8 = undefined;+ var private_key: [crypto.ED25519_PRIVATE_KEY_LEN]u8 = undefined;+ defer std.crypto.secureZero(u8, &private_key);+ crypto.ED25519_keypair(&public_key, &private_key);++ // libcrypto takes the private key as its 32-byte seed.+ const private_pkey = crypto.EVP_PKEY_new_raw_private_key(curve.pkey_type, null, &private_key, curve.size) orelse return error.OutOfMemory;+ errdefer crypto.EVP_PKEY_free(private_pkey);+ const public_pkey = crypto.EVP_PKEY_new_raw_public_key(curve.pkey_type, null, &public_key, public_key.len) orelse return error.OutOfMemory;+ errdefer crypto.EVP_PKEY_free(public_pkey);++ const private = try newKey(curve, private_pkey, true, extractable, private_mask, exec);+ // Public keys are always extractable.+ const public = try newKey(curve, public_pkey, false, true, public_mask, exec);+ return local.resolvePromise(CryptoKey.Pair{ .privateKey = private, .publicKey = public });+}++/// Imports a key from `spki` or `pkcs8` DER, or a `raw` public key. A+/// malformed structure, a key of another algorithm, or a raw key of the wrong+/// size is DataError. JWK goes through `importJwk`. The usages were already+/// checked against the key's kind (SubtleCrypto.importKey).+pub fn import(+ curve: *const Curve,+ format: []const u8,+ data: []const u8,+ is_private: bool,+ extractable: bool,+ usages_mask: u8,+ exec: *const Execution,+) !js.Promise {+ const local = exec.js.local.?;++ 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(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(data.len)) orelse {+ crypto.ERR_clear_error();+ return error.DataError;+ };+ }+ if (std.mem.eql(u8, format, "raw")) {+ if (data.len != curve.size) return error.DataError;+ break :blk crypto.EVP_PKEY_new_raw_public_key(curve.pkey_type, null, data.ptr, data.len) orelse {+ crypto.ERR_clear_error();+ return error.DataError;+ };+ }+ return error.NotSupported;+ };+ errdefer crypto.EVP_PKEY_free(pkey);++ // The DER's own algorithm identifier must be this curve's, and nothing+ // may follow its structure (`raw` doesn't move `ptr`).+ if (crypto.EVP_PKEY_id(pkey) != curve.pkey_type) return error.DataError;+ if (!std.mem.eql(u8, format, "raw") and ptr != data.ptr + data.len) return error.DataError;++ return local.resolvePromise(try newKey(curve, pkey, is_private, extractable, usages_mask, exec));+}++/// Imports a key from a JSON Web Key (RFC 8037): kty "OKP", the common `use`+/// ("sig") / key_ops / ext checks, `crv` naming the curve, an `alg`, if any,+/// of the curve's name or "EdDSA", and `x` (plus `d` for a private key) of the+/// curve's size, `x` being `d`'s public key. Anything else is DataError.+pub fn importJwk(+ curve: *const Curve,+ jwk: algorithm.KeyData.Jwk,+ extractable: bool,+ usages_mask: u8,+ exec: *const Execution,+) !js.Promise {+ const local = exec.js.local.?;++ if (!std.mem.eql(u8, jwk.kty orelse "", "OKP")) return error.DataError;+ try common.checkJwk(jwk, "sig", usages_mask, extractable);+ if (!std.mem.eql(u8, jwk.crv orelse "", curve.name)) return error.DataError;+ if (jwk.alg) |alg| {+ if (!std.mem.eql(u8, alg, curve.name) and !std.mem.eql(u8, alg, "EdDSA")) return error.DataError;+ }++ const x = try common.jwkBytes(exec.local_arena, jwk.x, curve.size);+ const pkey = blk: {+ const d = jwk.d orelse {+ break :blk crypto.EVP_PKEY_new_raw_public_key(curve.pkey_type, null, x.ptr, x.len) orelse {+ crypto.ERR_clear_error();+ return error.DataError;+ };+ };+ const seed = try common.jwkBytes(exec.local_arena, d, curve.size);+ defer std.crypto.secureZero(u8, seed);+ break :blk crypto.EVP_PKEY_new_raw_private_key(curve.pkey_type, null, seed.ptr, seed.len) orelse {+ crypto.ERR_clear_error();+ return error.DataError;+ };+ };+ errdefer crypto.EVP_PKEY_free(pkey);++ // A private key's `x` must be its own public key.+ if (jwk.d != null) {+ const public = try rawPublic(pkey, exec);+ if (!std.mem.eql(u8, public, x)) return error.DataError;+ }++ return local.resolvePromise(try newKey(curve, pkey, jwk.d != null, extractable, usages_mask, exec));+}++/// Wraps `pkey` in a CryptoKey, which takes ownership of it on success only.+fn newKey(+ curve: *const Curve,+ pkey: *crypto.EVP_PKEY,+ is_private: bool,+ extractable: bool,+ usages_mask: u8,+ exec: *const Execution,+) !*CryptoKey {+ return CryptoKey.init(exec, .{+ ._type = curve.key_type,+ ._kind = if (is_private) .private else .public,+ ._extractable = extractable,+ ._usages = usages_mask,+ ._key = &.{},+ ._algorithm = .{ .name = curve.name },+ ._vary = .{ .pkey = pkey },+ });+}++/// The public key's bytes: the `raw` export, and a JWK's `x`.+fn rawPublic(pkey: *const crypto.EVP_PKEY, exec: *const Execution) ![]u8 {+ var len: usize = 0;+ if (crypto.EVP_PKEY_get_raw_public_key(pkey, null, &len) != 1) return error.OperationError;+ const out = try exec.local_arena.alloc(u8, len);+ if (crypto.EVP_PKEY_get_raw_public_key(pkey, out.ptr, &len) != 1) return error.OperationError;+ return out[0..len];+}++/// The `raw` export of a public key.+pub fn exportRaw(key: *const CryptoKey, exec: *const Execution) ![]const u8 {+ return rawPublic(key.getKeyObject(), exec);+}++/// The JWK of an OKP key (RFC 8037). Members are listed in lexicographic+/// order, the order browsers return a JsonWebKey in; `alg` is the algorithm's+/// name.+const JwkPublic = struct {+ alg: []const u8,+ crv: []const u8,+ ext: bool,+ key_ops: []const []const u8,+ kty: []const u8 = "OKP",+ x: []const u8,+};++const JwkPrivate = struct {+ alg: []const u8,+ crv: []const u8,+ d: []const u8,+ ext: bool,+ key_ops: []const []const u8,+ kty: []const u8 = "OKP",+ x: []const u8,+};++/// The JWK of either half of an OKP key.+pub const Jwk = union(enum) {+ public: JwkPublic,+ private: JwkPrivate,+};++/// Exports a key as a JWK: `x` for either half, plus `d` for the private key.+pub fn exportJwk(key: *const CryptoKey, exec: *const Execution) !Jwk {+ const name = key._algorithm.name;+ const pkey = key.getKeyObject();+ const x = try common.base64Encode(exec.local_arena, try rawPublic(pkey, exec));+ const key_ops = try key.getUsages(exec);++ if (key._kind == .public) {+ return .{ .public = .{ .alg = name, .crv = name, .ext = key._extractable, .key_ops = key_ops, .x = x } };+ }+ var len: usize = 0;+ if (crypto.EVP_PKEY_get_raw_private_key(pkey, null, &len) != 1) return error.OperationError;+ const seed = try exec.local_arena.alloc(u8, len);+ defer std.crypto.secureZero(u8, seed);+ if (crypto.EVP_PKEY_get_raw_private_key(pkey, seed.ptr, &len) != 1) return error.OperationError;+ return .{ .private = .{+ .alg = name,+ .crv = name,+ .d = try common.base64Encode(exec.local_arena, seed[0..len]),+ .ext = key._extractable,+ .key_ops = key_ops,+ .x = x,+ } };+}++/// Signs `data` with a private key (pure Ed25519, no prehash).+pub fn sign(key: *const CryptoKey, data: []const u8, exec: *const Execution) ![]const u8 {+ const ctx = crypto.EVP_MD_CTX_new() orelse return error.OutOfMemory;+ defer crypto.EVP_MD_CTX_free(ctx);+ if (crypto.EVP_DigestSignInit(ctx, null, null, null, key.getKeyObject()) != 1) {+ crypto.ERR_clear_error();+ return error.OperationError;+ }+ const signature = try exec.local_arena.alloc(u8, crypto.ED25519_SIGNATURE_LEN);+ var len: usize = signature.len;+ if (crypto.EVP_DigestSign(ctx, signature.ptr, &len, data.ptr, data.len) != 1) {+ crypto.ERR_clear_error();+ return error.OperationError;+ }+ return signature[0..len];+}++/// Verifies `signature` over `data` with a public key. A signature of the+/// wrong size, or one that doesn't verify, is false, not an error. So is one+/// whose public key or R (the signature's first half) is an invalid point or+/// a small-order element, as the spec's verify steps ask; libcrypto doesn't+/// check that (w3c/webcrypto#423: not every implementation does).+pub fn verify(key: *const CryptoKey, signature: []const u8, data: []const u8) !bool {+ if (signature.len != crypto.ED25519_SIGNATURE_LEN) return false;++ var public: [crypto.ED25519_PUBLIC_KEY_LEN]u8 = undefined;+ var len: usize = public.len;+ if (crypto.EVP_PKEY_get_raw_public_key(key.getKeyObject(), &public, &len) != 1) return error.OperationError;+ if (!isStrongPoint(public) or !isStrongPoint(signature[0..32].*)) return false;++ const ctx = crypto.EVP_MD_CTX_new() orelse return error.OutOfMemory;+ defer crypto.EVP_MD_CTX_free(ctx);+ if (crypto.EVP_DigestVerifyInit(ctx, null, null, null, key.getKeyObject()) != 1) {+ crypto.ERR_clear_error();+ return error.OperationError;+ }+ const valid = crypto.EVP_DigestVerify(ctx, signature.ptr, signature.len, data.ptr, data.len) == 1;+ if (!valid) crypto.ERR_clear_error();+ return valid;+}++/// Whether `encoding` decodes to an Ed25519 point that isn't of small order.+fn isStrongPoint(encoding: [32]u8) bool {+ const point = std.crypto.ecc.Edwards25519.fromBytes(encoding) catch return false;+ point.rejectLowOrder() catch return false;+ return true;+}diff --git a/src/browser/webapi/crypto/RSA.zig b/src/browser/webapi/crypto/RSA.zigindex 4c7b0fd41..a127551e5 100644--- a/src/browser/webapi/crypto/RSA.zig+++ b/src/browser/webapi/crypto/RSA.zig@@ -180,8 +180,8 @@ pub fn generate(if (requested_bits > max_modulus_length) return error.OperationError;const hash_name = canonicalHash(requested_hash).?;- const private_mask = maskOf(s.private_usages, key_usages);- const public_mask = maskOf(s.public_usages, key_usages);+ const private_mask = common.usageIntersection(s.private_usages, key_usages);+ const public_mask = common.usageIntersection(s.public_usages, key_usages);// The private key must end up with at least one usage.if (private_mask == 0) return error.SyntaxError;@@ -564,20 +564,6 @@ fn digestContext(key: *const CryptoKey, verifying: bool, salt_length: ?u32) !*crreturn ctx;}-/// The usage bitmask of those `usages` that belong to `set`.-fn maskOf(set: []const []const u8, usages: []const []const u8) u8 {- var mask: u8 = 0;- for (usages) |u| {- for (set) |s| {- if (std.mem.eql(u8, s, u)) {- mask |= common.usageBit(u).?;- break;- }- }- }- return mask;-}-fn eql(a: []const u8, b: []const u8) bool {return std.ascii.eqlIgnoreCase(a, b);}diff --git a/src/browser/webapi/crypto/common.zig b/src/browser/webapi/crypto/common.zigindex 973801f8e..286a2dfb9 100644--- a/src/browser/webapi/crypto/common.zig+++ b/src/browser/webapi/crypto/common.zig@@ -85,6 +85,24 @@ pub fn usageMaskInner(allowed: []const []const u8, usages: []const []const u8, rreturn mask;}+/// Whether `usage` is one of `set`.+pub fn usageIn(set: []const []const u8, usage: []const u8) bool {+ for (set) |s| {+ if (std.mem.eql(u8, s, usage)) return true;+ }+ return false;+}++/// The usage intersection of `usages` and `set`, as a bitmask: how a key+/// pair's usages are split between its halves.+pub fn usageIntersection(set: []const []const u8, usages: []const []const u8) u8 {+ var mask: u8 = 0;+ for (usages) |usage| {+ if (usageIn(set, usage)) mask |= usageBit(usage).?;+ }+ return mask;+}+/// The key bytes of a symmetric ("oct") JWK: its `kty` must be "oct" and its/// `k` present and decodable (JWA, section 6.4). Anything else is DataError.pub fn octKey(jwk: algorithm.KeyData.Jwk, allocator: Allocator) error{ OutOfMemory, DataError }![]u8 {@@ -122,6 +140,14 @@ pub fn checkJwk(}}+/// A JWK key member (a coordinate, `x`, `d`, ...): base64url of exactly `n`+/// bytes. A missing member or one of another size is DataError.+pub fn jwkBytes(allocator: Allocator, member: ?[]const u8, n: usize) error{ OutOfMemory, DataError }![]u8 {+ const bytes = try base64Decode(allocator, member orelse return error.DataError);+ if (bytes.len != n) return error.DataError;+ return bytes;+}+/// Decodes a base64url (or base64) string, tolerating either alphabet and/// optional padding. Returns DataError on malformed input, per the JWK import/// rules.diff --git a/src/sys/libcrypto.zig b/src/sys/libcrypto.zigindex 5876677ef..3ce9e0610 100644--- a/src/sys/libcrypto.zig+++ b/src/sys/libcrypto.zig@@ -265,6 +265,15 @@ pub const EVP_PKEY_ED25519 = NID_ED25519;pub extern fn EVP_PKEY_new_raw_private_key(@"type": c_int, unused: ?*ENGINE, in: [*c]const u8, len: usize) ?*EVP_PKEY;pub extern fn EVP_PKEY_new_raw_public_key(@"type": c_int, unused: ?*ENGINE, in: [*c]const u8, len: usize) ?*EVP_PKEY;+/// With `out` null, sets `out_len` to the key's size; otherwise writes it.+pub extern fn EVP_PKEY_get_raw_private_key(pkey: *const EVP_PKEY, out: [*c]u8, out_len: *usize) c_int;+pub extern fn EVP_PKEY_get_raw_public_key(pkey: *const EVP_PKEY, out: [*c]u8, out_len: *usize) c_int;++pub const ED25519_PUBLIC_KEY_LEN = 32;+/// BoringSSL's Ed25519 private key: the 32-byte seed, then the public key.+pub const ED25519_PRIVATE_KEY_LEN = 64;+pub const ED25519_SIGNATURE_LEN = 64;+pub extern fn ED25519_keypair(out_public_key: *[ED25519_PUBLIC_KEY_LEN]u8, out_private_key: *[ED25519_PRIVATE_KEY_LEN]u8) void;pub extern fn EVP_PKEY_CTX_new(pkey: ?*EVP_PKEY, e: ?*ENGINE) ?*EVP_PKEY_CTX;pub extern fn EVP_PKEY_CTX_free(ctx: ?*EVP_PKEY_CTX) void;pub extern fn EVP_PKEY_derive_init(ctx: ?*EVP_PKEY_CTX) c_int;