Skip to content

Lightpanda: the headless browser designed for AI and automation

webapi: ECDSA sign and verify

orezraey2be292812191
diff --git a/src/browser/tests/crypto.html b/src/browser/tests/crypto.html
index 41970f776..aba551733 100644
--- a/src/browser/tests/crypto.html
+++ b/src/browser/tests/crypto.html
@@ -833,6 +833,132 @@
});
</script>
+<script id=ecdsa-sign-verify 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 fromB64 = (b64) => Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
+ const data = new TextEncoder().encode("lightpanda ecdsa");
+ // Throwaway keys, and signatures of `data` that OpenSSL made with them,
+ // converted from DER to WebCrypto's r || s.
+ const p256 = {
+ spki: fromB64("MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEoLfGjL6RrYuRawPRHVMVVWbfQjA0SUPVcXxj4+OpAd0YGC6lz0zcwfw4T+jGcunCMagRwyhFvrGXWtSUfTFwqg=="),
+ pkcs8: fromB64("MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgbrRKMgf6KKhsWivZyuUW3iAiSirTaww3eop42SkjMg2hRANCAASgt8aMvpGti5FrA9EdUxVVZt9CMDRJQ9VxfGPj46kB3RgYLqXPTNzB/DhP6MZy6cIxqBHDKEW+sZda1JR9MXCq"),
+ // SHA-256.
+ signature: fromB64("mJ/UOhqLiZvLoi3d+N93gDe2oNSOT69aUhAHVfAnX3fPK9LSkG/zJRoBhp6urX0wwL8ASw/e6ALW1G0tsZKYew=="),
+ };
+ const p521 = {
+ spki: fromB64("MIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQBRaetQGuHTbgL1x0ddDqG21VmJRsM1E9TgE8oGSz82+b0d9Zlwx6jaN5UQnEn0S/47b8hwxnrQIyXz45aiDlnaWgB9uH2ytl/9TA4W7gqMjK6zSsP13IgZeAc68s0PTRSubL2ipe7+rpJ6kJONBnUGSVZ5skllnLm1sQrKICI8kR4690="),
+ // SHA-384; r starts with a zero byte, kept to fill its 66 bytes.
+ signature: fromB64("AKNno4WltwC1Sj70LqtrcxbpkJVWfgwPoao6KxBJV+zljaja/YvlQbAA3hnp2pSwoI6FCi3oqr2LlMM1zfU2PT+qAE1FbZR5OB3/4eb/0cg6HX/y/assF4OqYPDHJJ/c394darQGfoiBDj5t3ygmI1G1rGbJwJf6Yw8eaGC3QKNZCZav"),
+ };
+ const ecdsa = (namedCurve) => ({ name: "ECDSA", namedCurve });
+ const withHash = (hash) => ({ name: "ECDSA", hash });
+ const publicKey = await subtle.importKey("spki", p256.spki, ecdsa("P-256"), false, ["verify"]);
+ const privateKey = await subtle.importKey("pkcs8", p256.pkcs8, ecdsa("P-256"), false, ["sign"]);
+ const p521Public = await subtle.importKey("spki", p521.spki, ecdsa("P-521"), false, ["verify"]);
+
+ const sig = p256.signature;
+ const tampered = sig.slice();
+ tampered[5] ^= 1;
+ const n = sig.length / 2;
+ const padded = new Uint8Array([0, ...sig.subarray(0, n), 0, ...sig.subarray(n)]);
+
+ // Signatures made here: randomized, so two differ, and both verify.
+ const signed = await subtle.sign(withHash("SHA-256"), privateKey, data);
+ const signedAgain = await subtle.sign(withHash("sha-256"), privateKey, data);
+ // The hash is the operation's, not the key's: any of them, as a string or an object.
+ const sha512 = await subtle.sign(withHash({ name: "SHA-512" }), privateKey, data);
+ const pair = await subtle.generateKey(ecdsa("P-384"), true, ["sign", "verify"]);
+ const p384Signature = await subtle.sign(withHash("SHA-1"), pair.privateKey, data);
+ // P-521's scalars are 521 bits, so r and s are each padded to 66 bytes.
+ const p521Pair = await subtle.generateKey(ecdsa("P-521"), true, ["sign", "verify"]);
+ const p521Signatures = [];
+ for (let i = 0; i < 8; i++) p521Signatures.push(await subtle.sign(withHash("SHA-512"), p521Pair.privateKey, data));
+ const ecdh = await subtle.generateKey({ name: "ECDH", namedCurve: "P-256" }, true, ["deriveBits"]);
+ const hmac = await subtle.generateKey({ name: "HMAC", hash: "SHA-256" }, true, ["sign"]);
+ const noHashPromise = subtle.sign("ECDSA", privateKey, data);
+ const noHashIsPromise = noHashPromise instanceof Promise;
+ await noHashPromise.catch(() => {});
+
+ const results = {
+ // Verifying OpenSSL's signatures.
+ openssl: await subtle.verify(withHash("SHA-256"), publicKey, sig, data),
+ opensslP521: await subtle.verify(withHash("SHA-384"), p521Public, p521.signature, data),
+ otherHash: await subtle.verify(withHash("SHA-384"), publicKey, sig, data),
+ otherData: await subtle.verify(withHash("SHA-256"), publicKey, sig, new TextEncoder().encode("other")),
+ tampered: await subtle.verify(withHash("SHA-256"), publicKey, tampered, data),
+ // Only r || s of the curve's size verifies: not a shorter, padded, empty or zero one.
+ truncated: await subtle.verify(withHash("SHA-256"), publicKey, sig.subarray(0, sig.length - 1), data),
+ padded: await subtle.verify(withHash("SHA-256"), publicKey, padded, data),
+ empty: await subtle.verify(withHash("SHA-256"), publicKey, new Uint8Array(0), data),
+ zeros: await subtle.verify(withHash("SHA-256"), publicKey, new Uint8Array(64), data),
+ // Verifying ours.
+ signedValid: await subtle.verify(withHash("SHA-256"), publicKey, signed, data),
+ signedAgainValid: await subtle.verify(withHash("SHA-256"), publicKey, signedAgain, data),
+ sha512Valid: await subtle.verify(withHash("SHA-512"), publicKey, sha512, data),
+ sha512AsSha256: await subtle.verify(withHash("SHA-256"), publicKey, sha512, data),
+ p384Valid: await subtle.verify(withHash("SHA-1"), pair.publicKey, p384Signature, data),
+ p521Valid: (await Promise.all(p521Signatures.map((s) => subtle.verify(withHash("SHA-512"), p521Pair.publicKey, s, data)))).every((v) => v),
+ // EcdsaParams: the hash is required (TypeError) and must be a known one
+ // (NotSupportedError), checked before the key.
+ noHash: await errorName(() => subtle.sign("ECDSA", privateKey, data)),
+ noHashObject: await errorName(() => subtle.verify({ name: "ECDSA" }, publicKey, sig, data)),
+ noDash: await errorName(() => subtle.verify(withHash("SHA256"), publicKey, sig, data)),
+ // An object hash needs its name.
+ hashWithoutName: await errorName(() => subtle.sign(withHash({}), privateKey, data)),
+ sha224: await errorName(() => subtle.sign(withHash("SHA-224"), privateKey, data)),
+ badHashOnHmac: await errorName(() => subtle.sign(withHash("SHA256"), hmac, data)),
+ // The key: its own algorithm, its usage, its half.
+ publicSign: await errorName(() => subtle.sign(withHash("SHA-256"), pair.publicKey, data)),
+ privateVerify: await errorName(() => subtle.verify(withHash("SHA-256"), pair.privateKey, sig, data)),
+ ecdhKey: await errorName(() => subtle.sign(withHash("SHA-256"), ecdh.privateKey, data)),
+ // Other algorithms ignore a stray hash.
+ hmacWithHash: await errorName(() => subtle.sign({ name: "HMAC", hash: "bogus" }, hmac, data)),
+ };
+
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual(true, results.openssl);
+ testing.expectEqual(true, results.opensslP521);
+ testing.expectEqual(false, results.otherHash);
+ testing.expectEqual(false, results.otherData);
+ testing.expectEqual(false, results.tampered);
+ testing.expectEqual(false, results.truncated);
+ testing.expectEqual(false, results.padded);
+ testing.expectEqual(false, results.empty);
+ testing.expectEqual(false, results.zeros);
+ testing.expectEqual(64, signed.byteLength);
+ testing.expectEqual(false, Array.from(new Uint8Array(signed)).join() === Array.from(new Uint8Array(signedAgain)).join());
+ testing.expectEqual(true, results.signedValid);
+ testing.expectEqual(true, results.signedAgainValid);
+ testing.expectEqual(true, results.sha512Valid);
+ testing.expectEqual(false, results.sha512AsSha256);
+ testing.expectEqual(96, p384Signature.byteLength);
+ testing.expectEqual(true, results.p384Valid);
+ testing.expectEqual("132", p521Signatures.map((s) => s.byteLength).join().split(",").filter((l, i, all) => all.indexOf(l) === i).join());
+ testing.expectEqual(true, results.p521Valid);
+ testing.expectEqual("TypeError", results.noHash);
+ testing.expectEqual("TypeError", results.noHashObject);
+ testing.expectEqual(true, noHashIsPromise);
+ testing.expectEqual("NotSupportedError", results.noDash);
+ testing.expectEqual("TypeError", results.hashWithoutName);
+ testing.expectEqual("NotSupportedError", results.sha224);
+ testing.expectEqual("NotSupportedError", results.badHashOnHmac);
+ testing.expectEqual("InvalidAccessError", results.publicSign);
+ testing.expectEqual("InvalidAccessError", results.privateVerify);
+ testing.expectEqual("InvalidAccessError", results.ecdhKey);
+ testing.expectEqual(null, results.hmacWithHash);
+ });
+</script>
+
<script id=wrap-unwrap type=module>
const state = await testing.async();
const subtle = crypto.subtle;
@@ -1167,9 +1293,6 @@
noSign: await errorName(() => subtle.sign("HMAC", verifyOnly, data)),
noVerify: await errorName(() => subtle.verify("HMAC", signOnly, mac, data)),
ecdsaPublicSign: await errorName(() => subtle.sign(ecdsaAlgo, ecdsa.publicKey, data)),
- // ECDSA signing isn't implemented yet.
- ecdsaSign: await errorName(() => subtle.sign(ecdsaAlgo, ecdsa.privateKey, data)),
- ecdsaVerify: await errorName(() => subtle.verify(ecdsaAlgo, ecdsa.publicKey, new Uint8Array(64), data)),
};
state.resolve();
@@ -1188,8 +1311,6 @@
testing.expectEqual("InvalidAccessError", results.noSign);
testing.expectEqual("InvalidAccessError", results.noVerify);
testing.expectEqual("InvalidAccessError", results.ecdsaPublicSign);
- testing.expectEqual("NotSupportedError", results.ecdsaSign);
- testing.expectEqual("NotSupportedError", results.ecdsaVerify);
});
</script>
diff --git a/src/browser/webapi/SubtleCrypto.zig b/src/browser/webapi/SubtleCrypto.zig
index 15441109d..a268c2320 100644
--- a/src/browser/webapi/SubtleCrypto.zig
+++ b/src/browser/webapi/SubtleCrypto.zig
@@ -652,12 +652,13 @@ pub fn sign(
exec: *const Execution,
) !js.Promise {
const local = exec.js.local.?;
- const salt_length = try pssSaltLength(algo, local);
+ const params = try signParams(algo, local);
try checkSigningKey(algo, key, CryptoKey.Usages.sign);
const signature = switch (key._type) {
.hmac => try HMAC.sign(key, data, exec),
- .rsa => try RSA.sign(key, data, salt_length, exec),
- // A signing algorithm with no sign here yet (ECDSA).
+ .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).
else => {
log.debug(.not_implemented, "SubtleCrypto.sign", .{ .key_type = key._type });
return error.NotSupported;
@@ -676,12 +677,13 @@ pub fn verify(
exec: *const Execution,
) !js.Promise {
const local = exec.js.local.?;
- const salt_length = try pssSaltLength(algo, local);
+ const params = try signParams(algo, local);
try checkSigningKey(algo, key, CryptoKey.Usages.verify);
const valid = switch (key._type) {
.hmac => try HMAC.verify(key, signature, data),
- .rsa => try RSA.verify(key, signature, data, salt_length),
- // A signing algorithm with no verify here yet (ECDSA).
+ .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).
else => {
log.debug(.not_implemented, "SubtleCrypto.verify", .{ .key_type = key._type });
return error.NotSupported;
@@ -690,15 +692,48 @@ pub fn verify(
return local.resolvePromise(valid);
}
-/// The `saltLength` of an RSA-PSS algorithm (RsaPssParams), null for the other
-/// algorithms. Normalization comes before the key checks: a missing member or
-/// one outside [EnforceRange] unsigned long is a TypeError.
-fn pssSaltLength(algo: algorithm.Sign, local: *const js.Local) !?u32 {
- if (!eqlIgnoreCase(algo.algoName(), "RSA-PSS")) {
- return null;
+/// The members of a sign/verify algorithm that normalization converts:
+/// RSA-PSS's `saltLength` (RsaPssParams) and ECDSA's `hash` (EcdsaParams).
+/// The other algorithms ignore them.
+const SignParams = struct {
+ salt_length: ?u32 = null,
+ /// A canonical hash name.
+ hash: ?[]const u8 = null,
+};
+
+/// Normalizes `algo`'s params, before the key checks: a missing member, a
+/// saltLength outside [EnforceRange] unsigned long or a hash that isn't an
+/// algorithm identifier is a TypeError, an unknown hash NotSupportedError.
+fn signParams(algo: algorithm.Sign, local: *const js.Local) !SignParams {
+ const name = algo.algoName();
+ if (eqlIgnoreCase(name, "RSA-PSS")) {
+ const value = algo.saltLength() orelse return local.typeError("RSA-PSS requires a saltLength");
+ const salt_length = js.enforceRange(u32, try value.toF64()) catch return local.typeError("saltLength is out of range");
+ return .{ .salt_length = salt_length };
+ }
+ if (eqlIgnoreCase(name, "ECDSA")) {
+ const value = algo.hash() orelse return local.typeError("ECDSA requires a hash");
+ return .{ .hash = common.canonicalHash(try hashName(value, local)) orelse return error.NotSupported };
}
- const value = algo.saltLength() orelse return local.typeError("RSA-PSS requires a saltLength");
- return js.enforceRange(u32, try value.toF64()) catch local.typeError("saltLength is out of range");
+ return .{};
+}
+
+/// The name of a HashAlgorithmIdentifier, `(object or DOMString)`: an object's
+/// `name`, required (a TypeError without one), or the value as a string.
+fn hashName(value: js.Value, local: *const js.Local) ![]const u8 {
+ const Algorithm = struct { name: []const u8 };
+ const name = blk: {
+ if (value.isObject()) {
+ const object = local.jsValueToZig(Algorithm, value) catch |err| break :blk err;
+ break :blk object.name;
+ }
+ break :blk local.jsValueToZig([]const u8, value);
+ } catch |err| switch (err) {
+ // The page's own exception (a throwing getter or toString), pending.
+ error.JsException => return err,
+ else => return local.typeError("hash is not an algorithm identifier"),
+ };
+ return name;
}
/// The checks sign/verify make before the algorithm's own, in the spec's
diff --git a/src/browser/webapi/crypto/EC.zig b/src/browser/webapi/crypto/EC.zig
index 73bc5d392..bc0d72922 100644
--- a/src/browser/webapi/crypto/EC.zig
+++ b/src/browser/webapi/crypto/EC.zig
@@ -16,8 +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) and ECDH key
-//! agreement. Key bytes live as a libcrypto EVP_PKEY in `CryptoKey._vary.pkey`.
+//! 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`.
const std = @import("std");
const crypto = @import("../../../sys/libcrypto.zig");
@@ -254,6 +255,83 @@ pub fn deriveBits(
return out;
}
+/// The size in bytes of each of r and s in an ECDSA signature with `ec`: that
+/// of its curve's order (32, 48 and 66 for P-256, P-384 and P-521). Read from
+/// the key itself rather than its `namedCurve`.
+fn scalarBytes(ec: *const crypto.EC_KEY) ?usize {
+ const group = crypto.EC_KEY_get0_group(ec) orelse return null;
+ const order = crypto.EC_GROUP_get0_order(group) orelse return null;
+ return crypto.BN_num_bytes(order);
+}
+
+/// ECDSA signature generation (FIPS 186-5, section 6.4.1) of `data` hashed
+/// with `hash_name`, the hash of the operation's params (not of the key). The
+/// signature is r followed by s, each a big-endian integer of the curve
+/// order's size: the IEEE P1363 form WebCrypto uses, not DER. SubtleCrypto.sign
+/// checked the algorithm and the sign usage; only a private key signs.
+pub fn sign(key: *const CryptoKey, data: []const u8, hash_name: []const u8, exec: *const Execution) ![]const u8 {
+ if (key._kind != .private) return error.InvalidAccessError;
+ const ec = crypto.EVP_PKEY_get0_EC_KEY(key.getKeyObject()) orelse return error.OperationError;
+ const n = scalarBytes(ec) orelse return error.OperationError;
+
+ var buf: [crypto.EVP_MAX_MD_SIZE]u8 = undefined;
+ const digest = try digestOf(data, hash_name, &buf);
+ const sig = crypto.ECDSA_do_sign(digest.ptr, digest.len, ec) orelse return error.OperationError;
+ defer crypto.ECDSA_SIG_free(sig);
+
+ var r: ?*const crypto.BIGNUM = null;
+ var s: ?*const crypto.BIGNUM = null;
+ crypto.ECDSA_SIG_get0(sig, &r, &s);
+ const out = try exec.local_arena.alloc(u8, 2 * n);
+ if (crypto.BN_bn2bin_padded(out.ptr, n, r orelse return error.OperationError) != 1) return error.OperationError;
+ if (crypto.BN_bn2bin_padded(out[n..].ptr, n, s orelse return error.OperationError) != 1) return error.OperationError;
+ return out;
+}
+
+/// ECDSA signature verification (FIPS 186-5, section 6.4.2) of `signature`
+/// (r followed by s, as `sign` produces) over `data` hashed with `hash_name`.
+/// SubtleCrypto.verify checked the algorithm and the verify usage; only a
+/// public key verifies. A signature that doesn't match is false, whatever its
+/// length: one with extra padding, for one, isn't of the curve's size.
+pub fn verify(key: *const CryptoKey, signature: []const u8, data: []const u8, hash_name: []const u8) !bool {
+ if (key._kind != .public) return error.InvalidAccessError;
+ const ec = crypto.EVP_PKEY_get0_EC_KEY(key.getKeyObject()) orelse return error.OperationError;
+ const n = scalarBytes(ec) orelse return error.OperationError;
+
+ var buf: [crypto.EVP_MAX_MD_SIZE]u8 = undefined;
+ const digest = try digestOf(data, hash_name, &buf);
+ if (signature.len != 2 * n) {
+ return false;
+ }
+
+ const sig = crypto.ECDSA_SIG_new() orelse return error.OutOfMemory;
+ defer crypto.ECDSA_SIG_free(sig);
+ const r = crypto.BN_bin2bn(signature.ptr, n, null) orelse return error.OutOfMemory;
+ const s = crypto.BN_bin2bn(signature[n..].ptr, n, null) orelse {
+ crypto.BN_free(r);
+ return error.OutOfMemory;
+ };
+ if (crypto.ECDSA_SIG_set0(sig, r, s) != 1) {
+ crypto.BN_free(r);
+ crypto.BN_free(s);
+ return error.OutOfMemory;
+ }
+
+ if (crypto.ECDSA_do_verify(digest.ptr, digest.len, sig, ec) == 1) return true;
+ // A bad signature is an expected outcome, not a failure: don't leave it on
+ // the thread's error queue for the next libcrypto caller.
+ crypto.ERR_clear_error();
+ return false;
+}
+
+/// The `hash_name` digest of `data`, written to `out`.
+fn digestOf(data: []const u8, hash_name: []const u8, out: *[crypto.EVP_MAX_MD_SIZE]u8) ![]const u8 {
+ const md = crypto.findDigest(hash_name) catch return error.OperationError;
+ var len: c_uint = 0;
+ if (crypto.EVP_Digest(data.ptr, data.len, out, &len, md, null) != 1) return error.OperationError;
+ return out[0..len];
+}
+
fn contains(set: []const []const u8, usage: []const u8) bool {
for (set) |s| {
if (std.mem.eql(u8, s, usage)) {
diff --git a/src/browser/webapi/crypto/RSA.zig b/src/browser/webapi/crypto/RSA.zig
index 131965766..f89f4e890 100644
--- a/src/browser/webapi/crypto/RSA.zig
+++ b/src/browser/webapi/crypto/RSA.zig
@@ -131,17 +131,8 @@ pub fn scheme(name: []const u8) ?*const Scheme {
return null;
}
-const hashes = [_][]const u8{ "SHA-1", "SHA-256", "SHA-384", "SHA-512" };
-
-/// The registered hash name (case-insensitive), or null if not a supported
-/// hash. Stored on the key, so `.algorithm.hash.name` reports it and
-/// `findDigest` (which is case-sensitive) can look it up.
-pub fn canonicalHash(name: []const u8) ?[]const u8 {
- for (hashes) |canonical| {
- if (eql(name, canonical)) return canonical;
- }
- return null;
-}
+const hashes = common.hashes;
+const canonicalHash = common.canonicalHash;
/// The JWK `alg` of `s` for a canonical hash name.
fn jwkAlgOfHash(s: *const Scheme, hash: []const u8) ?[]const u8 {
diff --git a/src/browser/webapi/crypto/algorithm.zig b/src/browser/webapi/crypto/algorithm.zig
index 96e0064bc..edbb59cf2 100644
--- a/src/browser/webapi/crypto/algorithm.zig
+++ b/src/browser/webapi/crypto/algorithm.zig
@@ -225,6 +225,9 @@ pub const Encrypt = union(enum) {
pub const Sign = union(enum) {
string: []const u8,
object: struct {
+ /// ECDSA. Kept as a value, like `saltLength`: it's only converted
+ /// (a HashAlgorithmIdentifier) when the algorithm is ECDSA.
+ hash: ?js.Value = null,
name: []const u8,
/// RSA-PSS. Kept as a value: it's only converted (an [EnforceRange]
/// unsigned long) when the algorithm is RSA-PSS, so another algorithm
@@ -239,6 +242,14 @@ pub const Sign = union(enum) {
};
}
+ /// The `hash` member, if present.
+ pub fn hash(self: Sign) ?js.Value {
+ return switch (self) {
+ .string => null,
+ .object => |object| object.hash,
+ };
+ }
+
/// The `saltLength` member, if present.
pub fn saltLength(self: Sign) ?js.Value {
return switch (self) {
diff --git a/src/browser/webapi/crypto/common.zig b/src/browser/webapi/crypto/common.zig
index ad86a7012..e1d28669e 100644
--- a/src/browser/webapi/crypto/common.zig
+++ b/src/browser/webapi/crypto/common.zig
@@ -26,6 +26,19 @@ const Allocator = std.mem.Allocator;
const CryptoKey = @import("../CryptoKey.zig");
const algorithm = @import("algorithm.zig");
+/// The hashes the algorithms take (their `hash` member).
+pub const hashes = [_][]const u8{ "SHA-1", "SHA-256", "SHA-384", "SHA-512" };
+
+/// The registered hash name (case-insensitive), or null if not a supported
+/// hash. Stored on the key, so `.algorithm.hash.name` reports it and
+/// `findDigest` (which is case-sensitive) can look it up.
+pub fn canonicalHash(name: []const u8) ?[]const u8 {
+ for (hashes) |canonical| {
+ if (std.ascii.eqlIgnoreCase(name, canonical)) return canonical;
+ }
+ return null;
+}
+
/// Maps a usage string to its `CryptoKey.Usages` bit, or null if unknown.
pub fn usageBit(name: []const u8) ?u8 {
const U = CryptoKey.Usages;
diff --git a/src/sys/libcrypto.zig b/src/sys/libcrypto.zig
index 7434d2747..1584559b2 100644
--- a/src/sys/libcrypto.zig
+++ b/src/sys/libcrypto.zig
@@ -25,7 +25,7 @@ pub const EVP_MD = struct_env_md_st;
const struct_engine_st = opaque {};
const ENGINE = struct_engine_st;
const struct_ec_key_st = opaque {};
-const EC_KEY = struct_ec_key_st;
+pub const EC_KEY = struct_ec_key_st;
const struct_evp_pkey_st = opaque {};
pub const EVP_PKEY = struct_evp_pkey_st;
const struct_evp_pkey_ctx_st = opaque {};
@@ -149,6 +149,23 @@ 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 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;
+
+// ECDSA over a digest, with the signature as an (r, s) pair.
+const struct_ecdsa_sig_st = opaque {};
+pub const ECDSA_SIG = struct_ecdsa_sig_st;
+pub extern fn ECDSA_do_sign(digest: [*]const u8, digest_len: usize, key: *const EC_KEY) ?*ECDSA_SIG;
+/// Returns 1 for a valid signature, 0 otherwise (on the error queue).
+pub extern fn ECDSA_do_verify(digest: [*]const u8, digest_len: usize, sig: *const ECDSA_SIG, key: *const EC_KEY) c_int;
+pub extern fn ECDSA_SIG_new() ?*ECDSA_SIG;
+pub extern fn ECDSA_SIG_free(sig: ?*ECDSA_SIG) void;
+pub extern fn ECDSA_SIG_get0(sig: *const ECDSA_SIG, out_r: *?*const BIGNUM, out_s: *?*const BIGNUM) void;
+/// Takes ownership of `r` and `s` on success only.
+pub extern fn ECDSA_SIG_set0(sig: *ECDSA_SIG, r: *BIGNUM, s: *BIGNUM) c_int;
// DER decoders (advance `inp` past the parsed structure).
pub extern fn d2i_PUBKEY(out: ?*?*EVP_PKEY, inp: *[*c]const u8, len: c_long) ?*EVP_PKEY;
@@ -207,6 +224,8 @@ pub extern fn BN_free(bn: ?*BIGNUM) void;
pub extern fn BN_bin2bn(in: [*c]const u8, len: usize, ret: ?*BIGNUM) ?*BIGNUM;
pub extern fn BN_num_bytes(bn: *const BIGNUM) c_uint;
pub extern fn BN_bn2bin(in: *const BIGNUM, out: [*]u8) usize;
+/// Big-endian, left-padded with zeros to exactly `len` bytes; 0 if it doesn't fit.
+pub extern fn BN_bn2bin_padded(out: [*]u8, len: usize, in: *const BIGNUM) c_int;
pub extern fn OPENSSL_malloc(size: usize) ?*anyopaque;
pub extern fn OPENSSL_free(ptr: ?*anyopaque) void;